blob: c1a331faecb68892c039f5e802bf359ddb61b194 [file] [log] [blame]
Chris Lattner233f7dc2002-08-12 21:17:25 +00001//===- InstructionCombining.cpp - Combine multiple instructions -----------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner8a2a3112001-12-14 16:52:21 +00009//
10// InstructionCombining - Combine instructions to form fewer, simple
Chris Lattner62b14df2002-09-02 04:59:56 +000011// instructions. This pass does not modify the CFG This pass is where algebraic
12// simplification happens.
Chris Lattner8a2a3112001-12-14 16:52:21 +000013//
14// This pass combines things like:
Chris Lattner32ed46b2004-05-04 15:19:33 +000015// %Y = add int %X, 1
16// %Z = add int %Y, 1
Chris Lattner8a2a3112001-12-14 16:52:21 +000017// into:
Chris Lattner32ed46b2004-05-04 15:19:33 +000018// %Z = add int %X, 2
Chris Lattner8a2a3112001-12-14 16:52:21 +000019//
20// This is a simple worklist driven algorithm.
21//
Chris Lattner065a6162003-09-10 05:29:43 +000022// This pass guarantees that the following canonicalizations are performed on
Chris Lattner2cd91962003-07-23 21:41:57 +000023// the program:
24// 1. If a binary operator has a constant operand, it is moved to the RHS
Chris Lattnerdf17af12003-08-12 21:53:41 +000025// 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.
Reid Spencere4d87aa2006-12-23 06:05:41 +000027// 3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
28// 4. All cmp instructions on boolean values are replaced with logical ops
Chris Lattnere92d2f42003-08-13 04:18:28 +000029// 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.
Chris Lattnerbac32862004-11-14 19:13:23 +000032// ... etc.
Chris Lattner2cd91962003-07-23 21:41:57 +000033//
Chris Lattner8a2a3112001-12-14 16:52:21 +000034//===----------------------------------------------------------------------===//
35
Chris Lattner0cea42a2004-03-13 23:54:27 +000036#define DEBUG_TYPE "instcombine"
Chris Lattner022103b2002-05-07 20:03:00 +000037#include "llvm/Transforms/Scalar.h"
Chris Lattner35b9e482004-10-12 04:52:52 +000038#include "llvm/IntrinsicInst.h"
Chris Lattnerbd0ef772002-02-26 21:46:54 +000039#include "llvm/Pass.h"
Chris Lattner0864acf2002-11-04 16:18:53 +000040#include "llvm/DerivedTypes.h"
Chris Lattner833b8a42003-06-26 05:06:25 +000041#include "llvm/GlobalVariable.h"
Chris Lattnerbc61e662003-11-02 05:57:39 +000042#include "llvm/Target/TargetData.h"
43#include "llvm/Transforms/Utils/BasicBlockUtils.h"
44#include "llvm/Transforms/Utils/Local.h"
Chris Lattner28977af2004-04-05 01:30:19 +000045#include "llvm/Support/CallSite.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000046#include "llvm/Support/Debug.h"
Chris Lattner28977af2004-04-05 01:30:19 +000047#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattnerdd841ae2002-04-18 17:39:14 +000048#include "llvm/Support/InstVisitor.h"
Chris Lattnerbcd7db52005-08-02 19:16:58 +000049#include "llvm/Support/MathExtras.h"
Chris Lattneracd1f0f2004-07-30 07:50:03 +000050#include "llvm/Support/PatternMatch.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000051#include "llvm/Support/Compiler.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000052#include "llvm/ADT/Statistic.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000053#include "llvm/ADT/STLExtras.h"
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000054#include <algorithm>
Chris Lattner67b1e1b2003-12-07 01:24:23 +000055using namespace llvm;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000056using namespace llvm::PatternMatch;
Brian Gaeked0fde302003-11-11 22:41:34 +000057
Chris Lattner0e5f4992006-12-19 21:40:18 +000058STATISTIC(NumCombined , "Number of insts combined");
59STATISTIC(NumConstProp, "Number of constant folds");
60STATISTIC(NumDeadInst , "Number of dead inst eliminated");
61STATISTIC(NumDeadStore, "Number of dead stores eliminated");
62STATISTIC(NumSunkInst , "Number of instructions sunk");
Chris Lattnera92f6962002-10-01 22:38:41 +000063
Chris Lattner0e5f4992006-12-19 21:40:18 +000064namespace {
Chris Lattnerf4b54612006-06-28 22:08:15 +000065 class VISIBILITY_HIDDEN InstCombiner
66 : public FunctionPass,
67 public InstVisitor<InstCombiner, Instruction*> {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000068 // Worklist of all of the instructions that need to be simplified.
69 std::vector<Instruction*> WorkList;
Chris Lattnerbc61e662003-11-02 05:57:39 +000070 TargetData *TD;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000071
Chris Lattner7bcc0e72004-02-28 05:22:00 +000072 /// AddUsersToWorkList - When an instruction is simplified, add all users of
73 /// the instruction to the work lists because they might get more simplified
74 /// now.
75 ///
Chris Lattner6dce1a72006-02-07 06:56:34 +000076 void AddUsersToWorkList(Value &I) {
Chris Lattner7e708292002-06-25 16:13:24 +000077 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattnerdd841ae2002-04-18 17:39:14 +000078 UI != UE; ++UI)
79 WorkList.push_back(cast<Instruction>(*UI));
80 }
81
Chris Lattner7bcc0e72004-02-28 05:22:00 +000082 /// AddUsesToWorkList - When an instruction is simplified, add operands to
83 /// the work lists because they might get more simplified now.
84 ///
85 void AddUsesToWorkList(Instruction &I) {
86 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
87 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
88 WorkList.push_back(Op);
89 }
Chris Lattner867b99f2006-10-05 06:55:50 +000090
91 /// AddSoonDeadInstToWorklist - The specified instruction is about to become
92 /// dead. Add all of its operands to the worklist, turning them into
93 /// undef's to reduce the number of uses of those instructions.
94 ///
95 /// Return the specified operand before it is turned into an undef.
96 ///
97 Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
98 Value *R = I.getOperand(op);
99
100 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
101 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i))) {
102 WorkList.push_back(Op);
103 // Set the operand to undef to drop the use.
104 I.setOperand(i, UndefValue::get(Op->getType()));
105 }
106
107 return R;
108 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000109
Chris Lattner62b14df2002-09-02 04:59:56 +0000110 // removeFromWorkList - remove all instances of I from the worklist.
111 void removeFromWorkList(Instruction *I);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000112 public:
Chris Lattner7e708292002-06-25 16:13:24 +0000113 virtual bool runOnFunction(Function &F);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000114
Chris Lattner97e52e42002-04-28 21:27:06 +0000115 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerbc61e662003-11-02 05:57:39 +0000116 AU.addRequired<TargetData>();
Owen Andersond1b78a12006-07-10 19:03:49 +0000117 AU.addPreservedID(LCSSAID);
Chris Lattnercb2610e2002-10-21 20:00:28 +0000118 AU.setPreservesCFG();
Chris Lattner97e52e42002-04-28 21:27:06 +0000119 }
120
Chris Lattner28977af2004-04-05 01:30:19 +0000121 TargetData &getTargetData() const { return *TD; }
122
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000123 // Visitation implementation - Implement instruction combining for different
124 // instruction types. The semantics are as follows:
125 // Return Value:
126 // null - No change was made
Chris Lattner233f7dc2002-08-12 21:17:25 +0000127 // I - Change was made, I is still valid, I may be dead though
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000128 // otherwise - Change was made, replace I with returned instruction
Misha Brukmanfd939082005-04-21 23:48:37 +0000129 //
Chris Lattner7e708292002-06-25 16:13:24 +0000130 Instruction *visitAdd(BinaryOperator &I);
131 Instruction *visitSub(BinaryOperator &I);
132 Instruction *visitMul(BinaryOperator &I);
Reid Spencer0a783f72006-11-02 01:53:59 +0000133 Instruction *visitURem(BinaryOperator &I);
134 Instruction *visitSRem(BinaryOperator &I);
135 Instruction *visitFRem(BinaryOperator &I);
136 Instruction *commonRemTransforms(BinaryOperator &I);
137 Instruction *commonIRemTransforms(BinaryOperator &I);
Reid Spencer1628cec2006-10-26 06:15:43 +0000138 Instruction *commonDivTransforms(BinaryOperator &I);
139 Instruction *commonIDivTransforms(BinaryOperator &I);
140 Instruction *visitUDiv(BinaryOperator &I);
141 Instruction *visitSDiv(BinaryOperator &I);
142 Instruction *visitFDiv(BinaryOperator &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000143 Instruction *visitAnd(BinaryOperator &I);
144 Instruction *visitOr (BinaryOperator &I);
145 Instruction *visitXor(BinaryOperator &I);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000146 Instruction *visitFCmpInst(FCmpInst &I);
147 Instruction *visitICmpInst(ICmpInst &I);
148 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
Chris Lattner484d3cf2005-04-24 06:59:08 +0000149
Reid Spencere4d87aa2006-12-23 06:05:41 +0000150 Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
151 ICmpInst::Predicate Cond, Instruction &I);
Chris Lattnerea340052003-03-10 19:16:08 +0000152 Instruction *visitShiftInst(ShiftInst &I);
Reid Spencerb83eb642006-10-20 07:07:24 +0000153 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Chris Lattner4d5542c2006-01-06 07:12:35 +0000154 ShiftInst &I);
Reid Spencer3da59db2006-11-27 01:05:10 +0000155 Instruction *commonCastTransforms(CastInst &CI);
156 Instruction *commonIntCastTransforms(CastInst &CI);
157 Instruction *visitTrunc(CastInst &CI);
158 Instruction *visitZExt(CastInst &CI);
159 Instruction *visitSExt(CastInst &CI);
160 Instruction *visitFPTrunc(CastInst &CI);
161 Instruction *visitFPExt(CastInst &CI);
162 Instruction *visitFPToUI(CastInst &CI);
163 Instruction *visitFPToSI(CastInst &CI);
164 Instruction *visitUIToFP(CastInst &CI);
165 Instruction *visitSIToFP(CastInst &CI);
166 Instruction *visitPtrToInt(CastInst &CI);
167 Instruction *visitIntToPtr(CastInst &CI);
168 Instruction *visitBitCast(CastInst &CI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +0000169 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
170 Instruction *FI);
Chris Lattner3d69f462004-03-12 05:52:32 +0000171 Instruction *visitSelectInst(SelectInst &CI);
Chris Lattner9fe38862003-06-19 17:00:31 +0000172 Instruction *visitCallInst(CallInst &CI);
173 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner7e708292002-06-25 16:13:24 +0000174 Instruction *visitPHINode(PHINode &PN);
175 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner0864acf2002-11-04 16:18:53 +0000176 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner67b1e1b2003-12-07 01:24:23 +0000177 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner833b8a42003-06-26 05:06:25 +0000178 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner2f503e62005-01-31 05:36:43 +0000179 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattnerc4d10eb2003-06-04 04:46:00 +0000180 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner46238a62004-07-03 00:26:11 +0000181 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattnerefb47352006-04-15 01:39:45 +0000182 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchino1d7456d2006-01-13 22:48:06 +0000183 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +0000184 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000185
186 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner7e708292002-06-25 16:13:24 +0000187 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner8b170942002-08-09 23:47:40 +0000188
Chris Lattner9fe38862003-06-19 17:00:31 +0000189 private:
Chris Lattnera44d8a22003-10-07 22:32:43 +0000190 Instruction *visitCallSite(CallSite CS);
Chris Lattner9fe38862003-06-19 17:00:31 +0000191 bool transformConstExprCastCall(CallSite CS);
192
Chris Lattner28977af2004-04-05 01:30:19 +0000193 public:
Chris Lattner8b170942002-08-09 23:47:40 +0000194 // InsertNewInstBefore - insert an instruction New before instruction Old
195 // in the program. Add the new instruction to the worklist.
196 //
Chris Lattner955f3312004-09-28 21:48:02 +0000197 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattnere6f9a912002-08-23 18:32:43 +0000198 assert(New && New->getParent() == 0 &&
199 "New instruction already inserted into a basic block!");
Chris Lattner8b170942002-08-09 23:47:40 +0000200 BasicBlock *BB = Old.getParent();
201 BB->getInstList().insert(&Old, New); // Insert inst
202 WorkList.push_back(New); // Add to worklist
Chris Lattner4cb170c2004-02-23 06:38:22 +0000203 return New;
Chris Lattner8b170942002-08-09 23:47:40 +0000204 }
205
Chris Lattner0c967662004-09-24 15:21:34 +0000206 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
207 /// This also adds the cast to the worklist. Finally, this returns the
208 /// cast.
Reid Spencer17212df2006-12-12 09:18:51 +0000209 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
210 Instruction &Pos) {
Chris Lattner0c967662004-09-24 15:21:34 +0000211 if (V->getType() == Ty) return V;
Misha Brukmanfd939082005-04-21 23:48:37 +0000212
Chris Lattnere2ed0572006-04-06 19:19:17 +0000213 if (Constant *CV = dyn_cast<Constant>(V))
Reid Spencer17212df2006-12-12 09:18:51 +0000214 return ConstantExpr::getCast(opc, CV, Ty);
Chris Lattnere2ed0572006-04-06 19:19:17 +0000215
Reid Spencer17212df2006-12-12 09:18:51 +0000216 Instruction *C = CastInst::create(opc, V, Ty, V->getName(), &Pos);
Chris Lattner0c967662004-09-24 15:21:34 +0000217 WorkList.push_back(C);
218 return C;
219 }
220
Chris Lattner8b170942002-08-09 23:47:40 +0000221 // ReplaceInstUsesWith - This method is to be used when an instruction is
222 // found to be dead, replacable with another preexisting expression. Here
223 // we add all uses of I to the worklist, replace all uses of I with the new
224 // value, then return I, so that the inst combiner will know that I was
225 // modified.
226 //
227 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000228 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner15a76c02004-04-05 02:10:19 +0000229 if (&I != V) {
230 I.replaceAllUsesWith(V);
231 return &I;
232 } else {
233 // If we are replacing the instruction with itself, this must be in a
234 // segment of unreachable code, so just clobber the instruction.
Chris Lattner17be6352004-10-18 02:59:09 +0000235 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +0000236 return &I;
237 }
Chris Lattner8b170942002-08-09 23:47:40 +0000238 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000239
Chris Lattner6dce1a72006-02-07 06:56:34 +0000240 // UpdateValueUsesWith - This method is to be used when an value is
241 // found to be replacable with another preexisting expression or was
242 // updated. Here we add all uses of I to the worklist, replace all uses of
243 // I with the new value (unless the instruction was just updated), then
244 // return true, so that the inst combiner will know that I was modified.
245 //
246 bool UpdateValueUsesWith(Value *Old, Value *New) {
247 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
248 if (Old != New)
249 Old->replaceAllUsesWith(New);
250 if (Instruction *I = dyn_cast<Instruction>(Old))
251 WorkList.push_back(I);
Chris Lattnerf8c36f52006-02-12 08:02:11 +0000252 if (Instruction *I = dyn_cast<Instruction>(New))
253 WorkList.push_back(I);
Chris Lattner6dce1a72006-02-07 06:56:34 +0000254 return true;
255 }
256
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000257 // EraseInstFromFunction - When dealing with an instruction that has side
258 // effects or produces a void value, we can't rely on DCE to delete the
259 // instruction. Instead, visit methods should return the value returned by
260 // this function.
261 Instruction *EraseInstFromFunction(Instruction &I) {
262 assert(I.use_empty() && "Cannot erase instruction that is used!");
263 AddUsesToWorkList(I);
264 removeFromWorkList(&I);
Chris Lattner954f66a2004-11-18 21:41:39 +0000265 I.eraseFromParent();
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000266 return 0; // Don't do anything with FI
267 }
268
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000269 private:
Chris Lattner24c8e382003-07-24 17:35:25 +0000270 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
271 /// InsertBefore instruction. This is specialized a bit to avoid inserting
272 /// casts that are known to not do anything...
273 ///
Reid Spencer17212df2006-12-12 09:18:51 +0000274 Value *InsertOperandCastBefore(Instruction::CastOps opcode,
275 Value *V, const Type *DestTy,
Chris Lattner24c8e382003-07-24 17:35:25 +0000276 Instruction *InsertBefore);
277
Reid Spencere4d87aa2006-12-23 06:05:41 +0000278 /// SimplifyCommutative - This performs a few simplifications for
279 /// commutative operators.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000280 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000281
Reid Spencere4d87aa2006-12-23 06:05:41 +0000282 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
283 /// most-complex to least-complex order.
284 bool SimplifyCompare(CmpInst &I);
285
Chris Lattner255d8912006-02-11 09:31:47 +0000286 bool SimplifyDemandedBits(Value *V, uint64_t Mask,
287 uint64_t &KnownZero, uint64_t &KnownOne,
288 unsigned Depth = 0);
Chris Lattner4e998b22004-09-29 05:07:12 +0000289
Chris Lattner867b99f2006-10-05 06:55:50 +0000290 Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
291 uint64_t &UndefElts, unsigned Depth = 0);
292
Chris Lattner4e998b22004-09-29 05:07:12 +0000293 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
294 // PHI node as operand #0, see if we can fold the instruction into the PHI
295 // (which is only possible if all operands to the PHI are constants).
296 Instruction *FoldOpIntoPhi(Instruction &I);
297
Chris Lattnerbac32862004-11-14 19:13:23 +0000298 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
299 // operator and they all are only used by the PHI, PHI together their
300 // inputs, and do the operation once, to the result of the PHI.
301 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
Chris Lattner7da52b22006-11-01 04:51:18 +0000302 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
303
304
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000305 Instruction *OptAndOp(Instruction *Op, ConstantIntegral *OpRHS,
306 ConstantIntegral *AndRHS, BinaryOperator &TheAnd);
Chris Lattnerc8e77562005-09-18 04:24:45 +0000307
308 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantIntegral *Mask,
309 bool isSub, Instruction &I);
Chris Lattnera96879a2004-09-29 17:40:11 +0000310 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000311 bool isSigned, bool Inside, Instruction &IB);
Chris Lattnerb3f83972005-10-24 06:03:58 +0000312 Instruction *PromoteCastOfAllocation(CastInst &CI, AllocationInst &AI);
Chris Lattnerafe91a52006-06-15 19:07:26 +0000313 Instruction *MatchBSwap(BinaryOperator &I);
314
Reid Spencerc55b2432006-12-13 18:21:21 +0000315 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000316 };
Chris Lattnerf6293092002-07-23 18:06:35 +0000317
Chris Lattner7f8897f2006-08-27 22:42:52 +0000318 RegisterPass<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000319}
320
Chris Lattner4f98c562003-03-10 21:43:22 +0000321// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattnere87597f2004-10-16 18:11:37 +0000322// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattner4f98c562003-03-10 21:43:22 +0000323static unsigned getComplexity(Value *V) {
324 if (isa<Instruction>(V)) {
325 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattnere87597f2004-10-16 18:11:37 +0000326 return 3;
327 return 4;
Chris Lattner4f98c562003-03-10 21:43:22 +0000328 }
Chris Lattnere87597f2004-10-16 18:11:37 +0000329 if (isa<Argument>(V)) return 3;
330 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattner4f98c562003-03-10 21:43:22 +0000331}
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000332
Chris Lattnerc8802d22003-03-11 00:12:48 +0000333// isOnlyUse - Return true if this instruction will be deleted if we stop using
334// it.
335static bool isOnlyUse(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000336 return V->hasOneUse() || isa<Constant>(V);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000337}
338
Chris Lattner4cb170c2004-02-23 06:38:22 +0000339// getPromotedType - Return the specified type promoted as it would be to pass
340// though a va_arg area...
341static const Type *getPromotedType(const Type *Ty) {
Chris Lattner5dd04022004-06-17 18:16:02 +0000342 switch (Ty->getTypeID()) {
Reid Spencerc5b206b2006-12-31 05:48:39 +0000343 case Type::Int8TyID:
344 case Type::Int16TyID: return Type::Int32Ty;
Chris Lattner4cb170c2004-02-23 06:38:22 +0000345 case Type::FloatTyID: return Type::DoubleTy;
346 default: return Ty;
347 }
348}
349
Reid Spencer3da59db2006-11-27 01:05:10 +0000350/// getBitCastOperand - If the specified operand is a CastInst or a constant
351/// expression bitcast, return the operand value, otherwise return null.
352static Value *getBitCastOperand(Value *V) {
353 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
Chris Lattnereed48272005-09-13 00:40:14 +0000354 return I->getOperand(0);
355 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Reid Spencer3da59db2006-11-27 01:05:10 +0000356 if (CE->getOpcode() == Instruction::BitCast)
Chris Lattnereed48272005-09-13 00:40:14 +0000357 return CE->getOperand(0);
358 return 0;
359}
360
Reid Spencer3da59db2006-11-27 01:05:10 +0000361/// This function is a wrapper around CastInst::isEliminableCastPair. It
362/// simply extracts arguments and returns what that function returns.
363/// @Determine if it is valid to eliminate a Convert pair
364static Instruction::CastOps
365isEliminableCastPair(
366 const CastInst *CI, ///< The first cast instruction
367 unsigned opcode, ///< The opcode of the second cast instruction
368 const Type *DstTy, ///< The target type for the second cast instruction
369 TargetData *TD ///< The target data for pointer size
370) {
371
372 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
373 const Type *MidTy = CI->getType(); // B from above
Chris Lattner33a61132006-05-06 09:00:16 +0000374
Reid Spencer3da59db2006-11-27 01:05:10 +0000375 // Get the opcodes of the two Cast instructions
376 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
377 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner33a61132006-05-06 09:00:16 +0000378
Reid Spencer3da59db2006-11-27 01:05:10 +0000379 return Instruction::CastOps(
380 CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
381 DstTy, TD->getIntPtrType()));
Chris Lattner33a61132006-05-06 09:00:16 +0000382}
383
384/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
385/// in any code being generated. It does not require codegen if V is simple
386/// enough or if the cast can be folded into other casts.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000387static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
388 const Type *Ty, TargetData *TD) {
Chris Lattner33a61132006-05-06 09:00:16 +0000389 if (V->getType() == Ty || isa<Constant>(V)) return false;
390
391 // If this is a noop cast, it isn't real codegen.
Reid Spencer3da59db2006-11-27 01:05:10 +0000392 if (V->getType()->canLosslesslyBitCastTo(Ty))
Chris Lattner33a61132006-05-06 09:00:16 +0000393 return false;
394
Chris Lattner01575b72006-05-25 23:24:33 +0000395 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner33a61132006-05-06 09:00:16 +0000396 if (const CastInst *CI = dyn_cast<CastInst>(V))
Reid Spencere4d87aa2006-12-23 06:05:41 +0000397 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner33a61132006-05-06 09:00:16 +0000398 return false;
399 return true;
400}
401
402/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
403/// InsertBefore instruction. This is specialized a bit to avoid inserting
404/// casts that are known to not do anything...
405///
Reid Spencer17212df2006-12-12 09:18:51 +0000406Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
407 Value *V, const Type *DestTy,
Chris Lattner33a61132006-05-06 09:00:16 +0000408 Instruction *InsertBefore) {
409 if (V->getType() == DestTy) return V;
410 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencer17212df2006-12-12 09:18:51 +0000411 return ConstantExpr::getCast(opcode, C, DestTy);
Chris Lattner33a61132006-05-06 09:00:16 +0000412
Reid Spencer17212df2006-12-12 09:18:51 +0000413 return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
Chris Lattner33a61132006-05-06 09:00:16 +0000414}
415
Chris Lattner4f98c562003-03-10 21:43:22 +0000416// SimplifyCommutative - This performs a few simplifications for commutative
417// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000418//
Chris Lattner4f98c562003-03-10 21:43:22 +0000419// 1. Order operands such that they are listed from right (least complex) to
420// left (most complex). This puts constants before unary operators before
421// binary operators.
422//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000423// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
424// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000425//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000426bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000427 bool Changed = false;
428 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
429 Changed = !I.swapOperands();
Misha Brukmanfd939082005-04-21 23:48:37 +0000430
Chris Lattner4f98c562003-03-10 21:43:22 +0000431 if (!I.isAssociative()) return Changed;
432 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000433 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
434 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
435 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner2a9c8472003-05-27 16:40:51 +0000436 Constant *Folded = ConstantExpr::get(I.getOpcode(),
437 cast<Constant>(I.getOperand(1)),
438 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000439 I.setOperand(0, Op->getOperand(0));
440 I.setOperand(1, Folded);
441 return true;
442 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
443 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
444 isOnlyUse(Op) && isOnlyUse(Op1)) {
445 Constant *C1 = cast<Constant>(Op->getOperand(1));
446 Constant *C2 = cast<Constant>(Op1->getOperand(1));
447
448 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner2a9c8472003-05-27 16:40:51 +0000449 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000450 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
451 Op1->getOperand(0),
452 Op1->getName(), &I);
453 WorkList.push_back(New);
454 I.setOperand(0, New);
455 I.setOperand(1, Folded);
456 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000457 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000458 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000459 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000460}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000461
Reid Spencere4d87aa2006-12-23 06:05:41 +0000462/// SimplifyCompare - For a CmpInst this function just orders the operands
463/// so that theyare listed from right (least complex) to left (most complex).
464/// This puts constants before unary operators before binary operators.
465bool InstCombiner::SimplifyCompare(CmpInst &I) {
466 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
467 return false;
468 I.swapOperands();
469 // Compare instructions are not associative so there's nothing else we can do.
470 return true;
471}
472
Chris Lattner8d969642003-03-10 23:06:50 +0000473// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
474// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000475//
Chris Lattner8d969642003-03-10 23:06:50 +0000476static inline Value *dyn_castNegVal(Value *V) {
477 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000478 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000479
Chris Lattner0ce85802004-12-14 20:08:06 +0000480 // Constants can be considered to be negated values if they can be folded.
481 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
482 return ConstantExpr::getNeg(C);
Chris Lattner8d969642003-03-10 23:06:50 +0000483 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000484}
485
Chris Lattner8d969642003-03-10 23:06:50 +0000486static inline Value *dyn_castNotVal(Value *V) {
487 if (BinaryOperator::isNot(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000488 return BinaryOperator::getNotArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000489
490 // Constants can be considered to be not'ed values...
Chris Lattner3f2ec392003-04-30 22:34:06 +0000491 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
Chris Lattner448c3232004-06-10 02:12:35 +0000492 return ConstantExpr::getNot(C);
Chris Lattner8d969642003-03-10 23:06:50 +0000493 return 0;
494}
495
Chris Lattnerc8802d22003-03-11 00:12:48 +0000496// dyn_castFoldableMul - If this value is a multiply that can be folded into
497// other computations (because it has a constant operand), return the
Chris Lattner50af16a2004-11-13 19:50:12 +0000498// non-constant operand of the multiply, and set CST to point to the multiplier.
499// Otherwise, return null.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000500//
Chris Lattner50af16a2004-11-13 19:50:12 +0000501static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000502 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner50af16a2004-11-13 19:50:12 +0000503 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000504 if (I->getOpcode() == Instruction::Mul)
Chris Lattner50e60c72004-11-15 05:54:07 +0000505 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000506 return I->getOperand(0);
Chris Lattner50af16a2004-11-13 19:50:12 +0000507 if (I->getOpcode() == Instruction::Shl)
Chris Lattner50e60c72004-11-15 05:54:07 +0000508 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000509 // The multiplier is really 1 << CST.
510 Constant *One = ConstantInt::get(V->getType(), 1);
511 CST = cast<ConstantInt>(ConstantExpr::getShl(One, CST));
512 return I->getOperand(0);
513 }
514 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000515 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000516}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000517
Chris Lattner574da9b2005-01-13 20:14:25 +0000518/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
519/// expression, return it.
520static User *dyn_castGetElementPtr(Value *V) {
521 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
522 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
523 if (CE->getOpcode() == Instruction::GetElementPtr)
524 return cast<User>(V);
525 return false;
526}
527
Chris Lattner955f3312004-09-28 21:48:02 +0000528// AddOne, SubOne - Add or subtract a constant one from an integer constant...
Chris Lattnera96879a2004-09-29 17:40:11 +0000529static ConstantInt *AddOne(ConstantInt *C) {
530 return cast<ConstantInt>(ConstantExpr::getAdd(C,
531 ConstantInt::get(C->getType(), 1)));
Chris Lattner955f3312004-09-28 21:48:02 +0000532}
Chris Lattnera96879a2004-09-29 17:40:11 +0000533static ConstantInt *SubOne(ConstantInt *C) {
534 return cast<ConstantInt>(ConstantExpr::getSub(C,
535 ConstantInt::get(C->getType(), 1)));
Chris Lattner955f3312004-09-28 21:48:02 +0000536}
537
Chris Lattner255d8912006-02-11 09:31:47 +0000538/// GetConstantInType - Return a ConstantInt with the specified type and value.
539///
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000540static ConstantIntegral *GetConstantInType(const Type *Ty, uint64_t Val) {
Reid Spencerc5b206b2006-12-31 05:48:39 +0000541 if (Ty->getTypeID() == Type::BoolTyID)
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000542 return ConstantBool::get(Val);
Reid Spencerc5b206b2006-12-31 05:48:39 +0000543 return ConstantInt::get(Ty, Val);
Chris Lattner255d8912006-02-11 09:31:47 +0000544}
545
546
Chris Lattner68d5ff22006-02-09 07:38:58 +0000547/// ComputeMaskedBits - Determine which of the bits specified in Mask are
548/// known to be either zero or one and return them in the KnownZero/KnownOne
549/// bitsets. This code only analyzes bits in Mask, in order to short-circuit
550/// processing.
551static void ComputeMaskedBits(Value *V, uint64_t Mask, uint64_t &KnownZero,
552 uint64_t &KnownOne, unsigned Depth = 0) {
Chris Lattner5931c542005-09-24 23:43:33 +0000553 // Note, we cannot consider 'undef' to be "IsZero" here. The problem is that
554 // we cannot optimize based on the assumption that it is zero without changing
Chris Lattner3bedbd92006-02-07 07:27:52 +0000555 // it to be an explicit zero. If we don't change it to zero, other code could
Chris Lattner5931c542005-09-24 23:43:33 +0000556 // optimized based on the contradictory assumption that it is non-zero.
557 // Because instcombine aggressively folds operations with undef args anyway,
558 // this won't lose us code quality.
Chris Lattner68d5ff22006-02-09 07:38:58 +0000559 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V)) {
560 // We know all of the bits for a constant!
Chris Lattner255d8912006-02-11 09:31:47 +0000561 KnownOne = CI->getZExtValue() & Mask;
Chris Lattner68d5ff22006-02-09 07:38:58 +0000562 KnownZero = ~KnownOne & Mask;
563 return;
564 }
565
566 KnownZero = KnownOne = 0; // Don't know anything.
Chris Lattner74c51a02006-02-07 08:05:22 +0000567 if (Depth == 6 || Mask == 0)
Chris Lattner68d5ff22006-02-09 07:38:58 +0000568 return; // Limit search depth.
569
570 uint64_t KnownZero2, KnownOne2;
Chris Lattner255d8912006-02-11 09:31:47 +0000571 Instruction *I = dyn_cast<Instruction>(V);
572 if (!I) return;
573
Chris Lattnere3158302006-05-04 17:33:35 +0000574 Mask &= V->getType()->getIntegralTypeMask();
575
Chris Lattner255d8912006-02-11 09:31:47 +0000576 switch (I->getOpcode()) {
577 case Instruction::And:
578 // If either the LHS or the RHS are Zero, the result is zero.
579 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
580 Mask &= ~KnownZero;
581 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
582 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
583 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
584
585 // Output known-1 bits are only known if set in both the LHS & RHS.
586 KnownOne &= KnownOne2;
587 // Output known-0 are known to be clear if zero in either the LHS | RHS.
588 KnownZero |= KnownZero2;
589 return;
590 case Instruction::Or:
591 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
592 Mask &= ~KnownOne;
593 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
594 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
595 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
596
597 // Output known-0 bits are only known if clear in both the LHS & RHS.
598 KnownZero &= KnownZero2;
599 // Output known-1 are known to be set if set in either the LHS | RHS.
600 KnownOne |= KnownOne2;
601 return;
602 case Instruction::Xor: {
603 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
604 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
605 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
606 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
607
608 // Output known-0 bits are known if clear or set in both the LHS & RHS.
609 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
610 // Output known-1 are known to be set if set in only one of the LHS, RHS.
611 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
612 KnownZero = KnownZeroOut;
613 return;
614 }
615 case Instruction::Select:
616 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
617 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
618 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
619 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
620
621 // Only known if known in both the LHS and RHS.
622 KnownOne &= KnownOne2;
623 KnownZero &= KnownZero2;
624 return;
Reid Spencer3da59db2006-11-27 01:05:10 +0000625 case Instruction::FPTrunc:
626 case Instruction::FPExt:
627 case Instruction::FPToUI:
628 case Instruction::FPToSI:
629 case Instruction::SIToFP:
630 case Instruction::PtrToInt:
631 case Instruction::UIToFP:
632 case Instruction::IntToPtr:
633 return; // Can't work with floating point or pointers
634 case Instruction::Trunc:
635 // All these have integer operands
636 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
637 return;
638 case Instruction::BitCast: {
Chris Lattner255d8912006-02-11 09:31:47 +0000639 const Type *SrcTy = I->getOperand(0)->getType();
Reid Spencer3da59db2006-11-27 01:05:10 +0000640 if (SrcTy->isIntegral()) {
Chris Lattner255d8912006-02-11 09:31:47 +0000641 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
Chris Lattner68d5ff22006-02-09 07:38:58 +0000642 return;
643 }
Reid Spencer3da59db2006-11-27 01:05:10 +0000644 break;
645 }
646 case Instruction::ZExt: {
647 // Compute the bits in the result that are not present in the input.
648 const Type *SrcTy = I->getOperand(0)->getType();
Chris Lattner255d8912006-02-11 09:31:47 +0000649 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
650 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
Chris Lattner60de63d2005-10-09 06:36:35 +0000651
Reid Spencer3da59db2006-11-27 01:05:10 +0000652 Mask &= SrcTy->getIntegralTypeMask();
653 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
654 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
655 // The top bits are known to be zero.
656 KnownZero |= NewBits;
657 return;
658 }
659 case Instruction::SExt: {
660 // Compute the bits in the result that are not present in the input.
661 const Type *SrcTy = I->getOperand(0)->getType();
662 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
663 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
664
665 Mask &= SrcTy->getIntegralTypeMask();
666 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
667 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner74c51a02006-02-07 08:05:22 +0000668
Reid Spencer3da59db2006-11-27 01:05:10 +0000669 // If the sign bit of the input is known set or clear, then we know the
670 // top bits of the result.
671 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
672 if (KnownZero & InSignBit) { // Input sign bit known zero
673 KnownZero |= NewBits;
674 KnownOne &= ~NewBits;
675 } else if (KnownOne & InSignBit) { // Input sign bit known set
676 KnownOne |= NewBits;
677 KnownZero &= ~NewBits;
678 } else { // Input sign bit unknown
679 KnownZero &= ~NewBits;
680 KnownOne &= ~NewBits;
Chris Lattner255d8912006-02-11 09:31:47 +0000681 }
682 return;
683 }
684 case Instruction::Shl:
685 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
Reid Spencerb83eb642006-10-20 07:07:24 +0000686 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
687 uint64_t ShiftAmt = SA->getZExtValue();
688 Mask >>= ShiftAmt;
Chris Lattner255d8912006-02-11 09:31:47 +0000689 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
690 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Reid Spencerb83eb642006-10-20 07:07:24 +0000691 KnownZero <<= ShiftAmt;
692 KnownOne <<= ShiftAmt;
693 KnownZero |= (1ULL << ShiftAmt)-1; // low bits known zero.
Chris Lattner255d8912006-02-11 09:31:47 +0000694 return;
695 }
696 break;
Reid Spencer3822ff52006-11-08 06:47:33 +0000697 case Instruction::LShr:
Chris Lattner255d8912006-02-11 09:31:47 +0000698 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
Reid Spencerb83eb642006-10-20 07:07:24 +0000699 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Chris Lattner255d8912006-02-11 09:31:47 +0000700 // Compute the new bits that are at the top now.
Reid Spencerb83eb642006-10-20 07:07:24 +0000701 uint64_t ShiftAmt = SA->getZExtValue();
702 uint64_t HighBits = (1ULL << ShiftAmt)-1;
703 HighBits <<= I->getType()->getPrimitiveSizeInBits()-ShiftAmt;
Chris Lattner255d8912006-02-11 09:31:47 +0000704
Reid Spencer3822ff52006-11-08 06:47:33 +0000705 // Unsigned shift right.
706 Mask <<= ShiftAmt;
707 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
708 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
709 KnownZero >>= ShiftAmt;
710 KnownOne >>= ShiftAmt;
711 KnownZero |= HighBits; // high bits known zero.
712 return;
713 }
714 break;
715 case Instruction::AShr:
716 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
717 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
718 // Compute the new bits that are at the top now.
719 uint64_t ShiftAmt = SA->getZExtValue();
720 uint64_t HighBits = (1ULL << ShiftAmt)-1;
721 HighBits <<= I->getType()->getPrimitiveSizeInBits()-ShiftAmt;
722
723 // Signed shift right.
724 Mask <<= ShiftAmt;
725 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
726 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
727 KnownZero >>= ShiftAmt;
728 KnownOne >>= ShiftAmt;
Chris Lattner255d8912006-02-11 09:31:47 +0000729
Reid Spencer3822ff52006-11-08 06:47:33 +0000730 // Handle the sign bits.
731 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
732 SignBit >>= ShiftAmt; // Adjust to where it is now in the mask.
Chris Lattner255d8912006-02-11 09:31:47 +0000733
Reid Spencer3822ff52006-11-08 06:47:33 +0000734 if (KnownZero & SignBit) { // New bits are known zero.
735 KnownZero |= HighBits;
736 } else if (KnownOne & SignBit) { // New bits are known one.
737 KnownOne |= HighBits;
Chris Lattner68d5ff22006-02-09 07:38:58 +0000738 }
739 return;
Chris Lattner60de63d2005-10-09 06:36:35 +0000740 }
Chris Lattner255d8912006-02-11 09:31:47 +0000741 break;
Chris Lattner5931c542005-09-24 23:43:33 +0000742 }
Chris Lattner74c51a02006-02-07 08:05:22 +0000743}
744
745/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
746/// this predicate to simplify operations downstream. Mask is known to be zero
747/// for bits that V cannot have.
748static bool MaskedValueIsZero(Value *V, uint64_t Mask, unsigned Depth = 0) {
Chris Lattner68d5ff22006-02-09 07:38:58 +0000749 uint64_t KnownZero, KnownOne;
750 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
751 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
752 return (KnownZero & Mask) == Mask;
Chris Lattner5931c542005-09-24 23:43:33 +0000753}
754
Chris Lattner255d8912006-02-11 09:31:47 +0000755/// ShrinkDemandedConstant - Check to see if the specified operand of the
756/// specified instruction is a constant integer. If so, check to see if there
757/// are any bits set in the constant that are not demanded. If so, shrink the
758/// constant and return true.
759static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
760 uint64_t Demanded) {
761 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
762 if (!OpC) return false;
763
764 // If there are no bits set that aren't demanded, nothing to do.
765 if ((~Demanded & OpC->getZExtValue()) == 0)
766 return false;
767
768 // This is producing any bits that are not needed, shrink the RHS.
769 uint64_t Val = Demanded & OpC->getZExtValue();
770 I->setOperand(OpNo, GetConstantInType(OpC->getType(), Val));
771 return true;
772}
773
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000774// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
775// set of known zero and one bits, compute the maximum and minimum values that
776// could have the specified known zero and known one bits, returning them in
777// min/max.
778static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
779 uint64_t KnownZero,
780 uint64_t KnownOne,
781 int64_t &Min, int64_t &Max) {
782 uint64_t TypeBits = Ty->getIntegralTypeMask();
783 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
784
785 uint64_t SignBit = 1ULL << (Ty->getPrimitiveSizeInBits()-1);
786
787 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
788 // bit if it is unknown.
789 Min = KnownOne;
790 Max = KnownOne|UnknownBits;
791
792 if (SignBit & UnknownBits) { // Sign bit is unknown
793 Min |= SignBit;
794 Max &= ~SignBit;
795 }
796
797 // Sign extend the min/max values.
798 int ShAmt = 64-Ty->getPrimitiveSizeInBits();
799 Min = (Min << ShAmt) >> ShAmt;
800 Max = (Max << ShAmt) >> ShAmt;
801}
802
803// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
804// a set of known zero and one bits, compute the maximum and minimum values that
805// could have the specified known zero and known one bits, returning them in
806// min/max.
807static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
808 uint64_t KnownZero,
809 uint64_t KnownOne,
810 uint64_t &Min,
811 uint64_t &Max) {
812 uint64_t TypeBits = Ty->getIntegralTypeMask();
813 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
814
815 // The minimum value is when the unknown bits are all zeros.
816 Min = KnownOne;
817 // The maximum value is when the unknown bits are all ones.
818 Max = KnownOne|UnknownBits;
819}
Chris Lattner255d8912006-02-11 09:31:47 +0000820
821
822/// SimplifyDemandedBits - Look at V. At this point, we know that only the
823/// DemandedMask bits of the result of V are ever used downstream. If we can
824/// use this information to simplify V, do so and return true. Otherwise,
825/// analyze the expression and return a mask of KnownOne and KnownZero bits for
826/// the expression (used to simplify the caller). The KnownZero/One bits may
827/// only be accurate for those bits in the DemandedMask.
828bool InstCombiner::SimplifyDemandedBits(Value *V, uint64_t DemandedMask,
829 uint64_t &KnownZero, uint64_t &KnownOne,
Chris Lattner6dce1a72006-02-07 06:56:34 +0000830 unsigned Depth) {
Chris Lattner255d8912006-02-11 09:31:47 +0000831 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V)) {
832 // We know all of the bits for a constant!
833 KnownOne = CI->getZExtValue() & DemandedMask;
834 KnownZero = ~KnownOne & DemandedMask;
835 return false;
836 }
837
838 KnownZero = KnownOne = 0;
Chris Lattner6dce1a72006-02-07 06:56:34 +0000839 if (!V->hasOneUse()) { // Other users may use these bits.
Chris Lattner255d8912006-02-11 09:31:47 +0000840 if (Depth != 0) { // Not at the root.
841 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
842 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
Chris Lattner6dce1a72006-02-07 06:56:34 +0000843 return false;
Chris Lattner255d8912006-02-11 09:31:47 +0000844 }
Chris Lattner6dce1a72006-02-07 06:56:34 +0000845 // If this is the root being simplified, allow it to have multiple uses,
Chris Lattner255d8912006-02-11 09:31:47 +0000846 // just set the DemandedMask to all bits.
847 DemandedMask = V->getType()->getIntegralTypeMask();
848 } else if (DemandedMask == 0) { // Not demanding any bits from V.
Chris Lattner74c51a02006-02-07 08:05:22 +0000849 if (V != UndefValue::get(V->getType()))
850 return UpdateValueUsesWith(V, UndefValue::get(V->getType()));
851 return false;
Chris Lattner6dce1a72006-02-07 06:56:34 +0000852 } else if (Depth == 6) { // Limit search depth.
853 return false;
854 }
855
856 Instruction *I = dyn_cast<Instruction>(V);
857 if (!I) return false; // Only analyze instructions.
858
Chris Lattnere3158302006-05-04 17:33:35 +0000859 DemandedMask &= V->getType()->getIntegralTypeMask();
860
Reid Spencer3da59db2006-11-27 01:05:10 +0000861 uint64_t KnownZero2 = 0, KnownOne2 = 0;
Chris Lattner6dce1a72006-02-07 06:56:34 +0000862 switch (I->getOpcode()) {
863 default: break;
864 case Instruction::And:
Chris Lattner255d8912006-02-11 09:31:47 +0000865 // If either the LHS or the RHS are Zero, the result is zero.
866 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
867 KnownZero, KnownOne, Depth+1))
868 return true;
869 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
870
871 // If something is known zero on the RHS, the bits aren't demanded on the
872 // LHS.
873 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownZero,
874 KnownZero2, KnownOne2, Depth+1))
875 return true;
876 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
877
Reid Spencer3da59db2006-11-27 01:05:10 +0000878 // If all of the demanded bits are known 1 on one side, return the other.
Chris Lattner255d8912006-02-11 09:31:47 +0000879 // These bits cannot contribute to the result of the 'and'.
880 if ((DemandedMask & ~KnownZero2 & KnownOne) == (DemandedMask & ~KnownZero2))
881 return UpdateValueUsesWith(I, I->getOperand(0));
882 if ((DemandedMask & ~KnownZero & KnownOne2) == (DemandedMask & ~KnownZero))
883 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattnerf8c36f52006-02-12 08:02:11 +0000884
885 // If all of the demanded bits in the inputs are known zeros, return zero.
886 if ((DemandedMask & (KnownZero|KnownZero2)) == DemandedMask)
887 return UpdateValueUsesWith(I, Constant::getNullValue(I->getType()));
888
Chris Lattner255d8912006-02-11 09:31:47 +0000889 // If the RHS is a constant, see if we can simplify it.
Chris Lattnerf8c36f52006-02-12 08:02:11 +0000890 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~KnownZero2))
Chris Lattner255d8912006-02-11 09:31:47 +0000891 return UpdateValueUsesWith(I, I);
892
893 // Output known-1 bits are only known if set in both the LHS & RHS.
894 KnownOne &= KnownOne2;
895 // Output known-0 are known to be clear if zero in either the LHS | RHS.
896 KnownZero |= KnownZero2;
897 break;
898 case Instruction::Or:
899 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
900 KnownZero, KnownOne, Depth+1))
901 return true;
902 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
903 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownOne,
904 KnownZero2, KnownOne2, Depth+1))
905 return true;
906 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
907
908 // If all of the demanded bits are known zero on one side, return the other.
909 // These bits cannot contribute to the result of the 'or'.
Jeff Cohenbce48052006-02-18 03:20:33 +0000910 if ((DemandedMask & ~KnownOne2 & KnownZero) == (DemandedMask & ~KnownOne2))
Chris Lattner255d8912006-02-11 09:31:47 +0000911 return UpdateValueUsesWith(I, I->getOperand(0));
Jeff Cohenbce48052006-02-18 03:20:33 +0000912 if ((DemandedMask & ~KnownOne & KnownZero2) == (DemandedMask & ~KnownOne))
Chris Lattner255d8912006-02-11 09:31:47 +0000913 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattnerf8c36f52006-02-12 08:02:11 +0000914
915 // If all of the potentially set bits on one side are known to be set on
916 // the other side, just use the 'other' side.
917 if ((DemandedMask & (~KnownZero) & KnownOne2) ==
918 (DemandedMask & (~KnownZero)))
919 return UpdateValueUsesWith(I, I->getOperand(0));
Nate Begeman368e18d2006-02-16 21:11:51 +0000920 if ((DemandedMask & (~KnownZero2) & KnownOne) ==
921 (DemandedMask & (~KnownZero2)))
922 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner255d8912006-02-11 09:31:47 +0000923
924 // If the RHS is a constant, see if we can simplify it.
925 if (ShrinkDemandedConstant(I, 1, DemandedMask))
926 return UpdateValueUsesWith(I, I);
927
928 // Output known-0 bits are only known if clear in both the LHS & RHS.
929 KnownZero &= KnownZero2;
930 // Output known-1 are known to be set if set in either the LHS | RHS.
931 KnownOne |= KnownOne2;
932 break;
933 case Instruction::Xor: {
934 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
935 KnownZero, KnownOne, Depth+1))
936 return true;
937 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
938 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
939 KnownZero2, KnownOne2, Depth+1))
940 return true;
941 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
942
943 // If all of the demanded bits are known zero on one side, return the other.
944 // These bits cannot contribute to the result of the 'xor'.
945 if ((DemandedMask & KnownZero) == DemandedMask)
946 return UpdateValueUsesWith(I, I->getOperand(0));
947 if ((DemandedMask & KnownZero2) == DemandedMask)
948 return UpdateValueUsesWith(I, I->getOperand(1));
949
950 // Output known-0 bits are known if clear or set in both the LHS & RHS.
951 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
952 // Output known-1 are known to be set if set in only one of the LHS, RHS.
953 uint64_t KnownOneOut = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
954
Chris Lattnerf2f16432006-11-27 19:55:07 +0000955 // If all of the demanded bits are known to be zero on one side or the
956 // other, turn this into an *inclusive* or.
Chris Lattnerf8c36f52006-02-12 08:02:11 +0000957 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerf2f16432006-11-27 19:55:07 +0000958 if ((DemandedMask & ~KnownZero & ~KnownZero2) == 0) {
959 Instruction *Or =
960 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
961 I->getName());
962 InsertNewInstBefore(Or, *I);
963 return UpdateValueUsesWith(I, Or);
Chris Lattner6dce1a72006-02-07 06:56:34 +0000964 }
Chris Lattner255d8912006-02-11 09:31:47 +0000965
Chris Lattnerf8c36f52006-02-12 08:02:11 +0000966 // If all of the demanded bits on one side are known, and all of the set
967 // bits on that side are also known to be set on the other side, turn this
968 // into an AND, as we know the bits will be cleared.
969 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
970 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask) { // all known
971 if ((KnownOne & KnownOne2) == KnownOne) {
972 Constant *AndC = GetConstantInType(I->getType(),
973 ~KnownOne & DemandedMask);
974 Instruction *And =
975 BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
976 InsertNewInstBefore(And, *I);
977 return UpdateValueUsesWith(I, And);
978 }
979 }
980
Chris Lattner255d8912006-02-11 09:31:47 +0000981 // If the RHS is a constant, see if we can simplify it.
982 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
983 if (ShrinkDemandedConstant(I, 1, DemandedMask))
984 return UpdateValueUsesWith(I, I);
985
986 KnownZero = KnownZeroOut;
987 KnownOne = KnownOneOut;
988 break;
989 }
990 case Instruction::Select:
991 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
992 KnownZero, KnownOne, Depth+1))
993 return true;
994 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
995 KnownZero2, KnownOne2, Depth+1))
996 return true;
997 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
998 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
999
1000 // If the operands are constants, see if we can simplify them.
1001 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1002 return UpdateValueUsesWith(I, I);
1003 if (ShrinkDemandedConstant(I, 2, DemandedMask))
1004 return UpdateValueUsesWith(I, I);
1005
1006 // Only known if known in both the LHS and RHS.
1007 KnownOne &= KnownOne2;
1008 KnownZero &= KnownZero2;
1009 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00001010 case Instruction::Trunc:
1011 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1012 KnownZero, KnownOne, Depth+1))
1013 return true;
1014 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1015 break;
1016 case Instruction::BitCast:
1017 if (!I->getOperand(0)->getType()->isIntegral())
1018 return false;
Chris Lattnerf6bd07c2006-09-16 03:14:10 +00001019
Reid Spencer3da59db2006-11-27 01:05:10 +00001020 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1021 KnownZero, KnownOne, Depth+1))
1022 return true;
1023 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1024 break;
1025 case Instruction::ZExt: {
1026 // Compute the bits in the result that are not present in the input.
1027 const Type *SrcTy = I->getOperand(0)->getType();
Chris Lattner255d8912006-02-11 09:31:47 +00001028 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
1029 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
1030
Reid Spencer3da59db2006-11-27 01:05:10 +00001031 DemandedMask &= SrcTy->getIntegralTypeMask();
1032 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1033 KnownZero, KnownOne, Depth+1))
1034 return true;
1035 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1036 // The top bits are known to be zero.
1037 KnownZero |= NewBits;
1038 break;
1039 }
1040 case Instruction::SExt: {
1041 // Compute the bits in the result that are not present in the input.
1042 const Type *SrcTy = I->getOperand(0)->getType();
1043 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
1044 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
1045
1046 // Get the sign bit for the source type
1047 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
1048 int64_t InputDemandedBits = DemandedMask & SrcTy->getIntegralTypeMask();
Chris Lattnerf345fe42006-02-13 22:41:07 +00001049
Reid Spencer3da59db2006-11-27 01:05:10 +00001050 // If any of the sign extended bits are demanded, we know that the sign
1051 // bit is demanded.
1052 if (NewBits & DemandedMask)
1053 InputDemandedBits |= InSignBit;
Chris Lattnerf345fe42006-02-13 22:41:07 +00001054
Reid Spencer3da59db2006-11-27 01:05:10 +00001055 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1056 KnownZero, KnownOne, Depth+1))
1057 return true;
1058 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner255d8912006-02-11 09:31:47 +00001059
Reid Spencer3da59db2006-11-27 01:05:10 +00001060 // If the sign bit of the input is known set or clear, then we know the
1061 // top bits of the result.
Chris Lattner6dce1a72006-02-07 06:56:34 +00001062
Reid Spencer3da59db2006-11-27 01:05:10 +00001063 // If the input sign bit is known zero, or if the NewBits are not demanded
1064 // convert this into a zero extension.
1065 if ((KnownZero & InSignBit) || (NewBits & ~DemandedMask) == NewBits) {
1066 // Convert to ZExt cast
1067 CastInst *NewCast = CastInst::create(
1068 Instruction::ZExt, I->getOperand(0), I->getType(), I->getName(), I);
1069 return UpdateValueUsesWith(I, NewCast);
1070 } else if (KnownOne & InSignBit) { // Input sign bit known set
1071 KnownOne |= NewBits;
1072 KnownZero &= ~NewBits;
1073 } else { // Input sign bit unknown
1074 KnownZero &= ~NewBits;
1075 KnownOne &= ~NewBits;
Chris Lattner6dce1a72006-02-07 06:56:34 +00001076 }
Chris Lattner255d8912006-02-11 09:31:47 +00001077 break;
Chris Lattner6dce1a72006-02-07 06:56:34 +00001078 }
Chris Lattnerb4a2f052006-11-09 05:12:27 +00001079 case Instruction::Add:
1080 // If there is a constant on the RHS, there are a variety of xformations
1081 // we can do.
1082 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1083 // If null, this should be simplified elsewhere. Some of the xforms here
1084 // won't work if the RHS is zero.
1085 if (RHS->isNullValue())
1086 break;
1087
1088 // Figure out what the input bits are. If the top bits of the and result
1089 // are not demanded, then the add doesn't demand them from its input
1090 // either.
1091
1092 // Shift the demanded mask up so that it's at the top of the uint64_t.
1093 unsigned BitWidth = I->getType()->getPrimitiveSizeInBits();
1094 unsigned NLZ = CountLeadingZeros_64(DemandedMask << (64-BitWidth));
1095
1096 // If the top bit of the output is demanded, demand everything from the
1097 // input. Otherwise, we demand all the input bits except NLZ top bits.
1098 uint64_t InDemandedBits = ~0ULL >> 64-BitWidth+NLZ;
1099
1100 // Find information about known zero/one bits in the input.
1101 if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits,
1102 KnownZero2, KnownOne2, Depth+1))
1103 return true;
1104
1105 // If the RHS of the add has bits set that can't affect the input, reduce
1106 // the constant.
1107 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1108 return UpdateValueUsesWith(I, I);
1109
1110 // Avoid excess work.
1111 if (KnownZero2 == 0 && KnownOne2 == 0)
1112 break;
1113
1114 // Turn it into OR if input bits are zero.
1115 if ((KnownZero2 & RHS->getZExtValue()) == RHS->getZExtValue()) {
1116 Instruction *Or =
1117 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1118 I->getName());
1119 InsertNewInstBefore(Or, *I);
1120 return UpdateValueUsesWith(I, Or);
1121 }
1122
1123 // We can say something about the output known-zero and known-one bits,
1124 // depending on potential carries from the input constant and the
1125 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1126 // bits set and the RHS constant is 0x01001, then we know we have a known
1127 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1128
1129 // To compute this, we first compute the potential carry bits. These are
1130 // the bits which may be modified. I'm not aware of a better way to do
1131 // this scan.
1132 uint64_t RHSVal = RHS->getZExtValue();
1133
1134 bool CarryIn = false;
1135 uint64_t CarryBits = 0;
1136 uint64_t CurBit = 1;
1137 for (unsigned i = 0; i != BitWidth; ++i, CurBit <<= 1) {
1138 // Record the current carry in.
1139 if (CarryIn) CarryBits |= CurBit;
1140
1141 bool CarryOut;
1142
1143 // This bit has a carry out unless it is "zero + zero" or
1144 // "zero + anything" with no carry in.
1145 if ((KnownZero2 & CurBit) && ((RHSVal & CurBit) == 0)) {
1146 CarryOut = false; // 0 + 0 has no carry out, even with carry in.
1147 } else if (!CarryIn &&
1148 ((KnownZero2 & CurBit) || ((RHSVal & CurBit) == 0))) {
1149 CarryOut = false; // 0 + anything has no carry out if no carry in.
1150 } else {
1151 // Otherwise, we have to assume we have a carry out.
1152 CarryOut = true;
1153 }
1154
1155 // This stage's carry out becomes the next stage's carry-in.
1156 CarryIn = CarryOut;
1157 }
1158
1159 // Now that we know which bits have carries, compute the known-1/0 sets.
1160
1161 // Bits are known one if they are known zero in one operand and one in the
1162 // other, and there is no input carry.
1163 KnownOne = ((KnownZero2 & RHSVal) | (KnownOne2 & ~RHSVal)) & ~CarryBits;
1164
1165 // Bits are known zero if they are known zero in both operands and there
1166 // is no input carry.
1167 KnownZero = KnownZero2 & ~RHSVal & ~CarryBits;
1168 }
1169 break;
Chris Lattner6dce1a72006-02-07 06:56:34 +00001170 case Instruction::Shl:
Reid Spencerb83eb642006-10-20 07:07:24 +00001171 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1172 uint64_t ShiftAmt = SA->getZExtValue();
1173 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask >> ShiftAmt,
Chris Lattner255d8912006-02-11 09:31:47 +00001174 KnownZero, KnownOne, Depth+1))
1175 return true;
1176 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Reid Spencerb83eb642006-10-20 07:07:24 +00001177 KnownZero <<= ShiftAmt;
1178 KnownOne <<= ShiftAmt;
1179 KnownZero |= (1ULL << ShiftAmt) - 1; // low bits known zero.
Chris Lattner255d8912006-02-11 09:31:47 +00001180 }
Chris Lattner6dce1a72006-02-07 06:56:34 +00001181 break;
Reid Spencer3822ff52006-11-08 06:47:33 +00001182 case Instruction::LShr:
1183 // For a logical shift right
1184 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1185 unsigned ShiftAmt = SA->getZExtValue();
1186
1187 // Compute the new bits that are at the top now.
1188 uint64_t HighBits = (1ULL << ShiftAmt)-1;
1189 HighBits <<= I->getType()->getPrimitiveSizeInBits() - ShiftAmt;
1190 uint64_t TypeMask = I->getType()->getIntegralTypeMask();
1191 // Unsigned shift right.
1192 if (SimplifyDemandedBits(I->getOperand(0),
1193 (DemandedMask << ShiftAmt) & TypeMask,
1194 KnownZero, KnownOne, Depth+1))
1195 return true;
1196 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1197 KnownZero &= TypeMask;
1198 KnownOne &= TypeMask;
1199 KnownZero >>= ShiftAmt;
1200 KnownOne >>= ShiftAmt;
1201 KnownZero |= HighBits; // high bits known zero.
1202 }
1203 break;
1204 case Instruction::AShr:
Chris Lattnerb7363792006-09-18 04:31:40 +00001205 // If this is an arithmetic shift right and only the low-bit is set, we can
1206 // always convert this into a logical shr, even if the shift amount is
1207 // variable. The low bit of the shift cannot be an input sign bit unless
1208 // the shift amount is >= the size of the datatype, which is undefined.
Reid Spencer3822ff52006-11-08 06:47:33 +00001209 if (DemandedMask == 1) {
1210 // Perform the logical shift right.
1211 Value *NewVal = new ShiftInst(Instruction::LShr, I->getOperand(0),
1212 I->getOperand(1), I->getName());
Reid Spencer811b0cb2006-10-26 19:19:06 +00001213 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
Chris Lattnerb7363792006-09-18 04:31:40 +00001214 return UpdateValueUsesWith(I, NewVal);
1215 }
1216
Reid Spencerb83eb642006-10-20 07:07:24 +00001217 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1218 unsigned ShiftAmt = SA->getZExtValue();
Chris Lattner255d8912006-02-11 09:31:47 +00001219
1220 // Compute the new bits that are at the top now.
Reid Spencerb83eb642006-10-20 07:07:24 +00001221 uint64_t HighBits = (1ULL << ShiftAmt)-1;
1222 HighBits <<= I->getType()->getPrimitiveSizeInBits() - ShiftAmt;
Chris Lattnerc15637b2006-02-13 06:09:08 +00001223 uint64_t TypeMask = I->getType()->getIntegralTypeMask();
Reid Spencer3822ff52006-11-08 06:47:33 +00001224 // Signed shift right.
1225 if (SimplifyDemandedBits(I->getOperand(0),
1226 (DemandedMask << ShiftAmt) & TypeMask,
1227 KnownZero, KnownOne, Depth+1))
1228 return true;
1229 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1230 KnownZero &= TypeMask;
1231 KnownOne &= TypeMask;
1232 KnownZero >>= ShiftAmt;
1233 KnownOne >>= ShiftAmt;
Chris Lattner255d8912006-02-11 09:31:47 +00001234
Reid Spencer3822ff52006-11-08 06:47:33 +00001235 // Handle the sign bits.
1236 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
1237 SignBit >>= ShiftAmt; // Adjust to where it is now in the mask.
Chris Lattner255d8912006-02-11 09:31:47 +00001238
Reid Spencer3822ff52006-11-08 06:47:33 +00001239 // If the input sign bit is known to be zero, or if none of the top bits
1240 // are demanded, turn this into an unsigned shift right.
1241 if ((KnownZero & SignBit) || (HighBits & ~DemandedMask) == HighBits) {
1242 // Perform the logical shift right.
1243 Value *NewVal = new ShiftInst(Instruction::LShr, I->getOperand(0),
1244 SA, I->getName());
1245 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1246 return UpdateValueUsesWith(I, NewVal);
1247 } else if (KnownOne & SignBit) { // New bits are known one.
1248 KnownOne |= HighBits;
Chris Lattner6dce1a72006-02-07 06:56:34 +00001249 }
Chris Lattner255d8912006-02-11 09:31:47 +00001250 }
Chris Lattner6dce1a72006-02-07 06:56:34 +00001251 break;
1252 }
Chris Lattner255d8912006-02-11 09:31:47 +00001253
1254 // If the client is only demanding bits that we know, return the known
1255 // constant.
1256 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask)
1257 return UpdateValueUsesWith(I, GetConstantInType(I->getType(), KnownOne));
Chris Lattner6dce1a72006-02-07 06:56:34 +00001258 return false;
1259}
1260
Chris Lattner867b99f2006-10-05 06:55:50 +00001261
1262/// SimplifyDemandedVectorElts - The specified value producecs a vector with
1263/// 64 or fewer elements. DemandedElts contains the set of elements that are
1264/// actually used by the caller. This method analyzes which elements of the
1265/// operand are undef and returns that information in UndefElts.
1266///
1267/// If the information about demanded elements can be used to simplify the
1268/// operation, the operation is simplified, then the resultant value is
1269/// returned. This returns null if no change was made.
1270Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1271 uint64_t &UndefElts,
1272 unsigned Depth) {
1273 unsigned VWidth = cast<PackedType>(V->getType())->getNumElements();
1274 assert(VWidth <= 64 && "Vector too wide to analyze!");
1275 uint64_t EltMask = ~0ULL >> (64-VWidth);
1276 assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1277 "Invalid DemandedElts!");
1278
1279 if (isa<UndefValue>(V)) {
1280 // If the entire vector is undefined, just return this info.
1281 UndefElts = EltMask;
1282 return 0;
1283 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1284 UndefElts = EltMask;
1285 return UndefValue::get(V->getType());
1286 }
1287
1288 UndefElts = 0;
1289 if (ConstantPacked *CP = dyn_cast<ConstantPacked>(V)) {
1290 const Type *EltTy = cast<PackedType>(V->getType())->getElementType();
1291 Constant *Undef = UndefValue::get(EltTy);
1292
1293 std::vector<Constant*> Elts;
1294 for (unsigned i = 0; i != VWidth; ++i)
1295 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1296 Elts.push_back(Undef);
1297 UndefElts |= (1ULL << i);
1298 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1299 Elts.push_back(Undef);
1300 UndefElts |= (1ULL << i);
1301 } else { // Otherwise, defined.
1302 Elts.push_back(CP->getOperand(i));
1303 }
1304
1305 // If we changed the constant, return it.
1306 Constant *NewCP = ConstantPacked::get(Elts);
1307 return NewCP != CP ? NewCP : 0;
1308 } else if (isa<ConstantAggregateZero>(V)) {
1309 // Simplify the CAZ to a ConstantPacked where the non-demanded elements are
1310 // set to undef.
1311 const Type *EltTy = cast<PackedType>(V->getType())->getElementType();
1312 Constant *Zero = Constant::getNullValue(EltTy);
1313 Constant *Undef = UndefValue::get(EltTy);
1314 std::vector<Constant*> Elts;
1315 for (unsigned i = 0; i != VWidth; ++i)
1316 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1317 UndefElts = DemandedElts ^ EltMask;
1318 return ConstantPacked::get(Elts);
1319 }
1320
1321 if (!V->hasOneUse()) { // Other users may use these bits.
1322 if (Depth != 0) { // Not at the root.
1323 // TODO: Just compute the UndefElts information recursively.
1324 return false;
1325 }
1326 return false;
1327 } else if (Depth == 10) { // Limit search depth.
1328 return false;
1329 }
1330
1331 Instruction *I = dyn_cast<Instruction>(V);
1332 if (!I) return false; // Only analyze instructions.
1333
1334 bool MadeChange = false;
1335 uint64_t UndefElts2;
1336 Value *TmpV;
1337 switch (I->getOpcode()) {
1338 default: break;
1339
1340 case Instruction::InsertElement: {
1341 // If this is a variable index, we don't know which element it overwrites.
1342 // demand exactly the same input as we produce.
Reid Spencerb83eb642006-10-20 07:07:24 +00001343 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner867b99f2006-10-05 06:55:50 +00001344 if (Idx == 0) {
1345 // Note that we can't propagate undef elt info, because we don't know
1346 // which elt is getting updated.
1347 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1348 UndefElts2, Depth+1);
1349 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1350 break;
1351 }
1352
1353 // If this is inserting an element that isn't demanded, remove this
1354 // insertelement.
Reid Spencerb83eb642006-10-20 07:07:24 +00001355 unsigned IdxNo = Idx->getZExtValue();
Chris Lattner867b99f2006-10-05 06:55:50 +00001356 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1357 return AddSoonDeadInstToWorklist(*I, 0);
1358
1359 // Otherwise, the element inserted overwrites whatever was there, so the
1360 // input demanded set is simpler than the output set.
1361 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1362 DemandedElts & ~(1ULL << IdxNo),
1363 UndefElts, Depth+1);
1364 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1365
1366 // The inserted element is defined.
1367 UndefElts |= 1ULL << IdxNo;
1368 break;
1369 }
1370
1371 case Instruction::And:
1372 case Instruction::Or:
1373 case Instruction::Xor:
1374 case Instruction::Add:
1375 case Instruction::Sub:
1376 case Instruction::Mul:
1377 // div/rem demand all inputs, because they don't want divide by zero.
1378 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1379 UndefElts, Depth+1);
1380 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1381 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1382 UndefElts2, Depth+1);
1383 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1384
1385 // Output elements are undefined if both are undefined. Consider things
1386 // like undef&0. The result is known zero, not undef.
1387 UndefElts &= UndefElts2;
1388 break;
1389
1390 case Instruction::Call: {
1391 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1392 if (!II) break;
1393 switch (II->getIntrinsicID()) {
1394 default: break;
1395
1396 // Binary vector operations that work column-wise. A dest element is a
1397 // function of the corresponding input elements from the two inputs.
1398 case Intrinsic::x86_sse_sub_ss:
1399 case Intrinsic::x86_sse_mul_ss:
1400 case Intrinsic::x86_sse_min_ss:
1401 case Intrinsic::x86_sse_max_ss:
1402 case Intrinsic::x86_sse2_sub_sd:
1403 case Intrinsic::x86_sse2_mul_sd:
1404 case Intrinsic::x86_sse2_min_sd:
1405 case Intrinsic::x86_sse2_max_sd:
1406 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1407 UndefElts, Depth+1);
1408 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1409 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1410 UndefElts2, Depth+1);
1411 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1412
1413 // If only the low elt is demanded and this is a scalarizable intrinsic,
1414 // scalarize it now.
1415 if (DemandedElts == 1) {
1416 switch (II->getIntrinsicID()) {
1417 default: break;
1418 case Intrinsic::x86_sse_sub_ss:
1419 case Intrinsic::x86_sse_mul_ss:
1420 case Intrinsic::x86_sse2_sub_sd:
1421 case Intrinsic::x86_sse2_mul_sd:
1422 // TODO: Lower MIN/MAX/ABS/etc
1423 Value *LHS = II->getOperand(1);
1424 Value *RHS = II->getOperand(2);
1425 // Extract the element as scalars.
1426 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1427 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1428
1429 switch (II->getIntrinsicID()) {
1430 default: assert(0 && "Case stmts out of sync!");
1431 case Intrinsic::x86_sse_sub_ss:
1432 case Intrinsic::x86_sse2_sub_sd:
1433 TmpV = InsertNewInstBefore(BinaryOperator::createSub(LHS, RHS,
1434 II->getName()), *II);
1435 break;
1436 case Intrinsic::x86_sse_mul_ss:
1437 case Intrinsic::x86_sse2_mul_sd:
1438 TmpV = InsertNewInstBefore(BinaryOperator::createMul(LHS, RHS,
1439 II->getName()), *II);
1440 break;
1441 }
1442
1443 Instruction *New =
1444 new InsertElementInst(UndefValue::get(II->getType()), TmpV, 0U,
1445 II->getName());
1446 InsertNewInstBefore(New, *II);
1447 AddSoonDeadInstToWorklist(*II, 0);
1448 return New;
1449 }
1450 }
1451
1452 // Output elements are undefined if both are undefined. Consider things
1453 // like undef&0. The result is known zero, not undef.
1454 UndefElts &= UndefElts2;
1455 break;
1456 }
1457 break;
1458 }
1459 }
1460 return MadeChange ? I : 0;
1461}
1462
Reid Spencere4d87aa2006-12-23 06:05:41 +00001463/// @returns true if the specified compare instruction is
1464/// true when both operands are equal...
1465/// @brief Determine if the ICmpInst returns true if both operands are equal
1466static bool isTrueWhenEqual(ICmpInst &ICI) {
1467 ICmpInst::Predicate pred = ICI.getPredicate();
1468 return pred == ICmpInst::ICMP_EQ || pred == ICmpInst::ICMP_UGE ||
1469 pred == ICmpInst::ICMP_SGE || pred == ICmpInst::ICMP_ULE ||
1470 pred == ICmpInst::ICMP_SLE;
1471}
1472
1473/// @returns true if the specified compare instruction is
1474/// true when both operands are equal...
1475/// @brief Determine if the FCmpInst returns true if both operands are equal
1476static bool isTrueWhenEqual(FCmpInst &FCI) {
1477 FCmpInst::Predicate pred = FCI.getPredicate();
1478 return pred == FCmpInst::FCMP_OEQ || pred == FCmpInst::FCMP_UEQ ||
1479 pred == FCmpInst::FCMP_OGE || pred == FCmpInst::FCMP_UGE ||
1480 pred == FCmpInst::FCMP_OLE || pred == FCmpInst::FCMP_ULE;
Chris Lattner955f3312004-09-28 21:48:02 +00001481}
Chris Lattner564a7272003-08-13 19:01:45 +00001482
1483/// AssociativeOpt - Perform an optimization on an associative operator. This
1484/// function is designed to check a chain of associative operators for a
1485/// potential to apply a certain optimization. Since the optimization may be
1486/// applicable if the expression was reassociated, this checks the chain, then
1487/// reassociates the expression as necessary to expose the optimization
1488/// opportunity. This makes use of a special Functor, which must define
1489/// 'shouldApply' and 'apply' methods.
1490///
1491template<typename Functor>
1492Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1493 unsigned Opcode = Root.getOpcode();
1494 Value *LHS = Root.getOperand(0);
1495
1496 // Quick check, see if the immediate LHS matches...
1497 if (F.shouldApply(LHS))
1498 return F.apply(Root);
1499
1500 // Otherwise, if the LHS is not of the same opcode as the root, return.
1501 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +00001502 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +00001503 // Should we apply this transform to the RHS?
1504 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1505
1506 // If not to the RHS, check to see if we should apply to the LHS...
1507 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1508 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1509 ShouldApply = true;
1510 }
1511
1512 // If the functor wants to apply the optimization to the RHS of LHSI,
1513 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1514 if (ShouldApply) {
1515 BasicBlock *BB = Root.getParent();
Misha Brukmanfd939082005-04-21 23:48:37 +00001516
Chris Lattner564a7272003-08-13 19:01:45 +00001517 // Now all of the instructions are in the current basic block, go ahead
1518 // and perform the reassociation.
1519 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1520
1521 // First move the selected RHS to the LHS of the root...
1522 Root.setOperand(0, LHSI->getOperand(1));
1523
1524 // Make what used to be the LHS of the root be the user of the root...
1525 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +00001526 if (&Root == TmpLHSI) {
Chris Lattner15a76c02004-04-05 02:10:19 +00001527 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1528 return 0;
1529 }
Chris Lattner65725312004-04-16 18:08:07 +00001530 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +00001531 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +00001532 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1533 BasicBlock::iterator ARI = &Root; ++ARI;
1534 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
1535 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +00001536
1537 // Now propagate the ExtraOperand down the chain of instructions until we
1538 // get to LHSI.
1539 while (TmpLHSI != LHSI) {
1540 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +00001541 // Move the instruction to immediately before the chain we are
1542 // constructing to avoid breaking dominance properties.
1543 NextLHSI->getParent()->getInstList().remove(NextLHSI);
1544 BB->getInstList().insert(ARI, NextLHSI);
1545 ARI = NextLHSI;
1546
Chris Lattner564a7272003-08-13 19:01:45 +00001547 Value *NextOp = NextLHSI->getOperand(1);
1548 NextLHSI->setOperand(1, ExtraOperand);
1549 TmpLHSI = NextLHSI;
1550 ExtraOperand = NextOp;
1551 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001552
Chris Lattner564a7272003-08-13 19:01:45 +00001553 // Now that the instructions are reassociated, have the functor perform
1554 // the transformation...
1555 return F.apply(Root);
1556 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001557
Chris Lattner564a7272003-08-13 19:01:45 +00001558 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1559 }
1560 return 0;
1561}
1562
1563
1564// AddRHS - Implements: X + X --> X << 1
1565struct AddRHS {
1566 Value *RHS;
1567 AddRHS(Value *rhs) : RHS(rhs) {}
1568 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1569 Instruction *apply(BinaryOperator &Add) const {
1570 return new ShiftInst(Instruction::Shl, Add.getOperand(0),
Reid Spencerc5b206b2006-12-31 05:48:39 +00001571 ConstantInt::get(Type::Int8Ty, 1));
Chris Lattner564a7272003-08-13 19:01:45 +00001572 }
1573};
1574
1575// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1576// iff C1&C2 == 0
1577struct AddMaskingAnd {
1578 Constant *C2;
1579 AddMaskingAnd(Constant *c) : C2(c) {}
1580 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001581 ConstantInt *C1;
Misha Brukmanfd939082005-04-21 23:48:37 +00001582 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001583 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +00001584 }
1585 Instruction *apply(BinaryOperator &Add) const {
Chris Lattner48595f12004-06-10 02:07:29 +00001586 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +00001587 }
1588};
1589
Chris Lattner6e7ba452005-01-01 16:22:27 +00001590static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +00001591 InstCombiner *IC) {
Reid Spencer3da59db2006-11-27 01:05:10 +00001592 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Chris Lattner6e7ba452005-01-01 16:22:27 +00001593 if (Constant *SOC = dyn_cast<Constant>(SO))
Reid Spencer3da59db2006-11-27 01:05:10 +00001594 return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
Misha Brukmanfd939082005-04-21 23:48:37 +00001595
Reid Spencer3da59db2006-11-27 01:05:10 +00001596 return IC->InsertNewInstBefore(CastInst::create(
1597 CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001598 }
1599
Chris Lattner2eefe512004-04-09 19:05:30 +00001600 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +00001601 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1602 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +00001603
Chris Lattner2eefe512004-04-09 19:05:30 +00001604 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1605 if (ConstIsRHS)
Chris Lattner6e7ba452005-01-01 16:22:27 +00001606 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1607 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +00001608 }
1609
1610 Value *Op0 = SO, *Op1 = ConstOperand;
1611 if (!ConstIsRHS)
1612 std::swap(Op0, Op1);
1613 Instruction *New;
Chris Lattner6e7ba452005-01-01 16:22:27 +00001614 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1615 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Reid Spencere4d87aa2006-12-23 06:05:41 +00001616 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1617 New = CmpInst::create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
1618 SO->getName()+".cmp");
Chris Lattner6e7ba452005-01-01 16:22:27 +00001619 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
1620 New = new ShiftInst(SI->getOpcode(), Op0, Op1, SO->getName()+".sh");
Chris Lattner326c0f32004-04-10 19:15:56 +00001621 else {
Chris Lattner2eefe512004-04-09 19:05:30 +00001622 assert(0 && "Unknown binary instruction type!");
Chris Lattner326c0f32004-04-10 19:15:56 +00001623 abort();
1624 }
Chris Lattner6e7ba452005-01-01 16:22:27 +00001625 return IC->InsertNewInstBefore(New, I);
1626}
1627
1628// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1629// constant as the other operand, try to fold the binary operator into the
1630// select arguments. This also works for Cast instructions, which obviously do
1631// not have a second operand.
1632static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1633 InstCombiner *IC) {
1634 // Don't modify shared select instructions
1635 if (!SI->hasOneUse()) return 0;
1636 Value *TV = SI->getOperand(1);
1637 Value *FV = SI->getOperand(2);
1638
1639 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +00001640 // Bool selects with constant operands can be folded to logical ops.
1641 if (SI->getType() == Type::BoolTy) return 0;
1642
Chris Lattner6e7ba452005-01-01 16:22:27 +00001643 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1644 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1645
1646 return new SelectInst(SI->getCondition(), SelectTrueVal,
1647 SelectFalseVal);
1648 }
1649 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +00001650}
1651
Chris Lattner4e998b22004-09-29 05:07:12 +00001652
1653/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1654/// node as operand #0, see if we can fold the instruction into the PHI (which
1655/// is only possible if all operands to the PHI are constants).
1656Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1657 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00001658 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001659 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner4e998b22004-09-29 05:07:12 +00001660
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001661 // Check to see if all of the operands of the PHI are constants. If there is
1662 // one non-constant value, remember the BB it is. If there is more than one
1663 // bail out.
1664 BasicBlock *NonConstBB = 0;
1665 for (unsigned i = 0; i != NumPHIValues; ++i)
1666 if (!isa<Constant>(PN->getIncomingValue(i))) {
1667 if (NonConstBB) return 0; // More than one non-const value.
1668 NonConstBB = PN->getIncomingBlock(i);
1669
1670 // If the incoming non-constant value is in I's block, we have an infinite
1671 // loop.
1672 if (NonConstBB == I.getParent())
1673 return 0;
1674 }
1675
1676 // If there is exactly one non-constant value, we can insert a copy of the
1677 // operation in that block. However, if this is a critical edge, we would be
1678 // inserting the computation one some other paths (e.g. inside a loop). Only
1679 // do this if the pred block is unconditionally branching into the phi block.
1680 if (NonConstBB) {
1681 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1682 if (!BI || !BI->isUnconditional()) return 0;
1683 }
Chris Lattner4e998b22004-09-29 05:07:12 +00001684
1685 // Okay, we can do the transformation: create the new PHI node.
1686 PHINode *NewPN = new PHINode(I.getType(), I.getName());
1687 I.setName("");
Chris Lattner55517062005-01-29 00:39:08 +00001688 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner4e998b22004-09-29 05:07:12 +00001689 InsertNewInstBefore(NewPN, *PN);
1690
1691 // Next, add all of the operands to the PHI.
1692 if (I.getNumOperands() == 2) {
1693 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +00001694 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001695 Value *InV;
1696 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001697 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1698 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1699 else
1700 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001701 } else {
1702 assert(PN->getIncomingBlock(i) == NonConstBB);
1703 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1704 InV = BinaryOperator::create(BO->getOpcode(),
1705 PN->getIncomingValue(i), C, "phitmp",
1706 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +00001707 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1708 InV = CmpInst::create(CI->getOpcode(),
1709 CI->getPredicate(),
1710 PN->getIncomingValue(i), C, "phitmp",
1711 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001712 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
1713 InV = new ShiftInst(SI->getOpcode(),
1714 PN->getIncomingValue(i), C, "phitmp",
1715 NonConstBB->getTerminator());
1716 else
1717 assert(0 && "Unknown binop!");
1718
1719 WorkList.push_back(cast<Instruction>(InV));
1720 }
1721 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00001722 }
Reid Spencer3da59db2006-11-27 01:05:10 +00001723 } else {
1724 CastInst *CI = cast<CastInst>(&I);
1725 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +00001726 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001727 Value *InV;
1728 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00001729 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001730 } else {
1731 assert(PN->getIncomingBlock(i) == NonConstBB);
Reid Spencer3da59db2006-11-27 01:05:10 +00001732 InV = CastInst::create(CI->getOpcode(), PN->getIncomingValue(i),
1733 I.getType(), "phitmp",
1734 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001735 WorkList.push_back(cast<Instruction>(InV));
1736 }
1737 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00001738 }
1739 }
1740 return ReplaceInstUsesWith(I, NewPN);
1741}
1742
Chris Lattner7e708292002-06-25 16:13:24 +00001743Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00001744 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00001745 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +00001746
Chris Lattner66331a42004-04-10 22:01:55 +00001747 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattnere87597f2004-10-16 18:11:37 +00001748 // X + undef -> undef
1749 if (isa<UndefValue>(RHS))
1750 return ReplaceInstUsesWith(I, RHS);
1751
Chris Lattner66331a42004-04-10 22:01:55 +00001752 // X + 0 --> X
Chris Lattner9919e3d2006-12-02 00:13:08 +00001753 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
Chris Lattner5e678e02005-10-17 17:56:38 +00001754 if (RHSC->isNullValue())
1755 return ReplaceInstUsesWith(I, LHS);
Chris Lattner8532cf62005-10-17 20:18:38 +00001756 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1757 if (CFP->isExactlyValue(-0.0))
1758 return ReplaceInstUsesWith(I, LHS);
Chris Lattner5e678e02005-10-17 17:56:38 +00001759 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001760
Chris Lattner66331a42004-04-10 22:01:55 +00001761 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerb4a2f052006-11-09 05:12:27 +00001762 // X + (signbit) --> X ^ signbit
Chris Lattner74c51a02006-02-07 08:05:22 +00001763 uint64_t Val = CI->getZExtValue();
Chris Lattner1a074fc2006-02-07 07:00:41 +00001764 if (Val == (1ULL << (CI->getType()->getPrimitiveSizeInBits()-1)))
Chris Lattner48595f12004-06-10 02:07:29 +00001765 return BinaryOperator::createXor(LHS, RHS);
Chris Lattnerb4a2f052006-11-09 05:12:27 +00001766
1767 // See if SimplifyDemandedBits can simplify this. This handles stuff like
1768 // (X & 254)+1 -> (X&254)|1
1769 uint64_t KnownZero, KnownOne;
1770 if (!isa<PackedType>(I.getType()) &&
1771 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
1772 KnownZero, KnownOne))
1773 return &I;
Chris Lattner66331a42004-04-10 22:01:55 +00001774 }
Chris Lattner4e998b22004-09-29 05:07:12 +00001775
1776 if (isa<PHINode>(LHS))
1777 if (Instruction *NV = FoldOpIntoPhi(I))
1778 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +00001779
Chris Lattner4f637d42006-01-06 17:59:59 +00001780 ConstantInt *XorRHS = 0;
1781 Value *XorLHS = 0;
Chris Lattner5931c542005-09-24 23:43:33 +00001782 if (match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
1783 unsigned TySizeBits = I.getType()->getPrimitiveSizeInBits();
1784 int64_t RHSSExt = cast<ConstantInt>(RHSC)->getSExtValue();
1785 uint64_t RHSZExt = cast<ConstantInt>(RHSC)->getZExtValue();
1786
1787 uint64_t C0080Val = 1ULL << 31;
1788 int64_t CFF80Val = -C0080Val;
1789 unsigned Size = 32;
1790 do {
1791 if (TySizeBits > Size) {
1792 bool Found = false;
1793 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1794 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
1795 if (RHSSExt == CFF80Val) {
1796 if (XorRHS->getZExtValue() == C0080Val)
1797 Found = true;
1798 } else if (RHSZExt == C0080Val) {
1799 if (XorRHS->getSExtValue() == CFF80Val)
1800 Found = true;
1801 }
1802 if (Found) {
1803 // This is a sign extend if the top bits are known zero.
Chris Lattner68d5ff22006-02-09 07:38:58 +00001804 uint64_t Mask = ~0ULL;
Chris Lattner3bedbd92006-02-07 07:27:52 +00001805 Mask <<= 64-(TySizeBits-Size);
Chris Lattner68d5ff22006-02-09 07:38:58 +00001806 Mask &= XorLHS->getType()->getIntegralTypeMask();
Chris Lattner3bedbd92006-02-07 07:27:52 +00001807 if (!MaskedValueIsZero(XorLHS, Mask))
Chris Lattner5931c542005-09-24 23:43:33 +00001808 Size = 0; // Not a sign ext, but can't be any others either.
1809 goto FoundSExt;
1810 }
1811 }
1812 Size >>= 1;
1813 C0080Val >>= Size;
1814 CFF80Val >>= Size;
1815 } while (Size >= 8);
1816
1817FoundSExt:
1818 const Type *MiddleType = 0;
1819 switch (Size) {
1820 default: break;
Reid Spencerc5b206b2006-12-31 05:48:39 +00001821 case 32: MiddleType = Type::Int32Ty; break;
1822 case 16: MiddleType = Type::Int16Ty; break;
1823 case 8: MiddleType = Type::Int8Ty; break;
Chris Lattner5931c542005-09-24 23:43:33 +00001824 }
1825 if (MiddleType) {
Reid Spencerd977d862006-12-12 23:36:14 +00001826 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
Chris Lattner5931c542005-09-24 23:43:33 +00001827 InsertNewInstBefore(NewTrunc, I);
Reid Spencer3da59db2006-11-27 01:05:10 +00001828 return new SExtInst(NewTrunc, I.getType());
Chris Lattner5931c542005-09-24 23:43:33 +00001829 }
1830 }
Chris Lattner66331a42004-04-10 22:01:55 +00001831 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00001832
Chris Lattner564a7272003-08-13 19:01:45 +00001833 // X + X --> X << 1
Robert Bocchino71698282004-07-27 21:02:21 +00001834 if (I.getType()->isInteger()) {
Chris Lattner564a7272003-08-13 19:01:45 +00001835 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +00001836
1837 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
1838 if (RHSI->getOpcode() == Instruction::Sub)
1839 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
1840 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
1841 }
1842 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
1843 if (LHSI->getOpcode() == Instruction::Sub)
1844 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
1845 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
1846 }
Robert Bocchino71698282004-07-27 21:02:21 +00001847 }
Chris Lattnere92d2f42003-08-13 04:18:28 +00001848
Chris Lattner5c4afb92002-05-08 22:46:53 +00001849 // -A + B --> B - A
Chris Lattner8d969642003-03-10 23:06:50 +00001850 if (Value *V = dyn_castNegVal(LHS))
Chris Lattner48595f12004-06-10 02:07:29 +00001851 return BinaryOperator::createSub(RHS, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00001852
1853 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +00001854 if (!isa<Constant>(RHS))
1855 if (Value *V = dyn_castNegVal(RHS))
Chris Lattner48595f12004-06-10 02:07:29 +00001856 return BinaryOperator::createSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001857
Misha Brukmanfd939082005-04-21 23:48:37 +00001858
Chris Lattner50af16a2004-11-13 19:50:12 +00001859 ConstantInt *C2;
1860 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
1861 if (X == RHS) // X*C + X --> X * (C+1)
1862 return BinaryOperator::createMul(RHS, AddOne(C2));
1863
1864 // X*C1 + X*C2 --> X * (C1+C2)
1865 ConstantInt *C1;
1866 if (X == dyn_castFoldableMul(RHS, C1))
1867 return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +00001868 }
1869
1870 // X + X*C --> X * (C+1)
Chris Lattner50af16a2004-11-13 19:50:12 +00001871 if (dyn_castFoldableMul(RHS, C2) == LHS)
1872 return BinaryOperator::createMul(LHS, AddOne(C2));
1873
Chris Lattnere617c9e2007-01-05 02:17:46 +00001874 // X + ~X --> -1 since ~X = -X-1
1875 if (dyn_castNotVal(LHS) == RHS ||
1876 dyn_castNotVal(RHS) == LHS)
1877 return ReplaceInstUsesWith(I, ConstantInt::getAllOnesValue(I.getType()));
1878
Chris Lattnerad3448c2003-02-18 19:57:07 +00001879
Chris Lattner564a7272003-08-13 19:01:45 +00001880 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001881 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnere617c9e2007-01-05 02:17:46 +00001882 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
1883 return R;
Chris Lattnerc8802d22003-03-11 00:12:48 +00001884
Chris Lattner6b032052003-10-02 15:11:26 +00001885 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00001886 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001887 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
1888 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
1889 return BinaryOperator::createSub(C, X);
Chris Lattner6b032052003-10-02 15:11:26 +00001890 }
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001891
Chris Lattnerb99d6b12004-10-08 05:07:56 +00001892 // (X & FF00) + xx00 -> (X+xx00) & FF00
1893 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
1894 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
1895 if (Anded == CRHS) {
1896 // See if all bits from the first bit set in the Add RHS up are included
1897 // in the mask. First, get the rightmost bit.
Reid Spencerb83eb642006-10-20 07:07:24 +00001898 uint64_t AddRHSV = CRHS->getZExtValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00001899
1900 // Form a mask of all bits from the lowest bit added through the top.
1901 uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
Chris Lattner1a074fc2006-02-07 07:00:41 +00001902 AddRHSHighBits &= C2->getType()->getIntegralTypeMask();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00001903
1904 // See if the and mask includes all of these bits.
Reid Spencerb83eb642006-10-20 07:07:24 +00001905 uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getZExtValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00001906
Chris Lattnerb99d6b12004-10-08 05:07:56 +00001907 if (AddRHSHighBits == AddRHSHighBitsAnd) {
1908 // Okay, the xform is safe. Insert the new add pronto.
1909 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
1910 LHS->getName()), I);
1911 return BinaryOperator::createAnd(NewAdd, C2);
1912 }
1913 }
1914 }
1915
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001916 // Try to fold constant add into select arguments.
1917 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +00001918 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001919 return R;
Chris Lattner6b032052003-10-02 15:11:26 +00001920 }
1921
Reid Spencer1628cec2006-10-26 06:15:43 +00001922 // add (cast *A to intptrtype) B ->
1923 // cast (GEP (cast *A to sbyte*) B) ->
1924 // intptrtype
Andrew Lenharth16d79552006-09-19 18:24:51 +00001925 {
Reid Spencer3da59db2006-11-27 01:05:10 +00001926 CastInst *CI = dyn_cast<CastInst>(LHS);
1927 Value *Other = RHS;
Andrew Lenharth16d79552006-09-19 18:24:51 +00001928 if (!CI) {
1929 CI = dyn_cast<CastInst>(RHS);
1930 Other = LHS;
1931 }
Andrew Lenharth45633262006-09-20 15:37:57 +00001932 if (CI && CI->getType()->isSized() &&
1933 (CI->getType()->getPrimitiveSize() ==
1934 TD->getIntPtrType()->getPrimitiveSize())
1935 && isa<PointerType>(CI->getOperand(0)->getType())) {
Reid Spencer17212df2006-12-12 09:18:51 +00001936 Value *I2 = InsertCastBefore(Instruction::BitCast, CI->getOperand(0),
Reid Spencerc5b206b2006-12-31 05:48:39 +00001937 PointerType::get(Type::Int8Ty), I);
Andrew Lenharth45633262006-09-20 15:37:57 +00001938 I2 = InsertNewInstBefore(new GetElementPtrInst(I2, Other, "ctg2"), I);
Reid Spencer3da59db2006-11-27 01:05:10 +00001939 return new PtrToIntInst(I2, CI->getType());
Andrew Lenharth16d79552006-09-19 18:24:51 +00001940 }
1941 }
1942
Chris Lattner7e708292002-06-25 16:13:24 +00001943 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001944}
1945
Chris Lattner1ba5bcd2003-07-22 21:46:59 +00001946// isSignBit - Return true if the value represented by the constant only has the
1947// highest order bit set.
1948static bool isSignBit(ConstantInt *CI) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00001949 unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencerb83eb642006-10-20 07:07:24 +00001950 return (CI->getZExtValue() & (~0ULL >> (64-NumBits))) == (1ULL << (NumBits-1));
Chris Lattner1ba5bcd2003-07-22 21:46:59 +00001951}
1952
Chris Lattnerbfe492b2004-03-13 00:11:49 +00001953/// RemoveNoopCast - Strip off nonconverting casts from the value.
1954///
1955static Value *RemoveNoopCast(Value *V) {
1956 if (CastInst *CI = dyn_cast<CastInst>(V)) {
1957 const Type *CTy = CI->getType();
1958 const Type *OpTy = CI->getOperand(0)->getType();
1959 if (CTy->isInteger() && OpTy->isInteger()) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00001960 if (CTy->getPrimitiveSizeInBits() == OpTy->getPrimitiveSizeInBits())
Chris Lattnerbfe492b2004-03-13 00:11:49 +00001961 return RemoveNoopCast(CI->getOperand(0));
1962 } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
1963 return RemoveNoopCast(CI->getOperand(0));
1964 }
1965 return V;
1966}
1967
Chris Lattner7e708292002-06-25 16:13:24 +00001968Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00001969 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00001970
Chris Lattner233f7dc2002-08-12 21:17:25 +00001971 if (Op0 == Op1) // sub X, X -> 0
1972 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001973
Chris Lattner233f7dc2002-08-12 21:17:25 +00001974 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattner8d969642003-03-10 23:06:50 +00001975 if (Value *V = dyn_castNegVal(Op1))
Chris Lattner48595f12004-06-10 02:07:29 +00001976 return BinaryOperator::createAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00001977
Chris Lattnere87597f2004-10-16 18:11:37 +00001978 if (isa<UndefValue>(Op0))
1979 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
1980 if (isa<UndefValue>(Op1))
1981 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
1982
Chris Lattnerd65460f2003-11-05 01:06:05 +00001983 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
1984 // Replace (-1 - A) with (~A)...
Chris Lattnera2881962003-02-18 19:28:33 +00001985 if (C->isAllOnesValue())
1986 return BinaryOperator::createNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +00001987
Chris Lattnerd65460f2003-11-05 01:06:05 +00001988 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00001989 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001990 if (match(Op1, m_Not(m_Value(X))))
1991 return BinaryOperator::createAdd(X,
Chris Lattner48595f12004-06-10 02:07:29 +00001992 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
Chris Lattner9c290672004-03-12 23:53:13 +00001993 // -((uint)X >> 31) -> ((int)X >> 31)
1994 // -((int)X >> 31) -> ((uint)X >> 31)
Chris Lattnerbfe492b2004-03-13 00:11:49 +00001995 if (C->isNullValue()) {
1996 Value *NoopCastedRHS = RemoveNoopCast(Op1);
1997 if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
Reid Spencer3822ff52006-11-08 06:47:33 +00001998 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00001999 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00002000 // Check to see if we are shifting out everything but the sign bit.
Reid Spencerb83eb642006-10-20 07:07:24 +00002001 if (CU->getZExtValue() ==
2002 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002003 // Ok, the transformation is safe. Insert AShr.
Reid Spencer0f9d82c2006-12-24 00:40:59 +00002004 // FIXME: Once integer types are signless, this cast should be
2005 // removed.
2006 Value *ShiftOp = SI->getOperand(0);
Reid Spencer0f9d82c2006-12-24 00:40:59 +00002007 return new ShiftInst(Instruction::AShr, ShiftOp, CU,
2008 SI->getName());
Chris Lattner9c290672004-03-12 23:53:13 +00002009 }
2010 }
Reid Spencer3822ff52006-11-08 06:47:33 +00002011 }
2012 else if (SI->getOpcode() == Instruction::AShr) {
2013 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2014 // Check to see if we are shifting out everything but the sign bit.
2015 if (CU->getZExtValue() ==
2016 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00002017
2018 // Ok, the transformation is safe. Insert LShr.
2019 return new ShiftInst(Instruction::LShr, SI->getOperand(0), CU,
2020 SI->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00002021 }
2022 }
2023 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00002024 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002025
2026 // Try to fold constant sub into select arguments.
2027 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002028 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002029 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002030
2031 if (isa<PHINode>(Op0))
2032 if (Instruction *NV = FoldOpIntoPhi(I))
2033 return NV;
Chris Lattnerd65460f2003-11-05 01:06:05 +00002034 }
2035
Chris Lattner43d84d62005-04-07 16:15:25 +00002036 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2037 if (Op1I->getOpcode() == Instruction::Add &&
Chris Lattner9919e3d2006-12-02 00:13:08 +00002038 !Op0->getType()->isFPOrFPVector()) {
Chris Lattner08954a22005-04-07 16:28:01 +00002039 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Chris Lattner43d84d62005-04-07 16:15:25 +00002040 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002041 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Chris Lattner43d84d62005-04-07 16:15:25 +00002042 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002043 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2044 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2045 // C1-(X+C2) --> (C1-C2)-X
2046 return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
2047 Op1I->getOperand(0));
2048 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002049 }
2050
Chris Lattnerfd059242003-10-15 16:48:29 +00002051 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002052 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2053 // is not used by anyone else...
2054 //
Chris Lattner0517e722004-02-02 20:09:56 +00002055 if (Op1I->getOpcode() == Instruction::Sub &&
Chris Lattner9919e3d2006-12-02 00:13:08 +00002056 !Op1I->getType()->isFPOrFPVector()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002057 // Swap the two operands of the subexpr...
2058 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2059 Op1I->setOperand(0, IIOp1);
2060 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00002061
Chris Lattnera2881962003-02-18 19:28:33 +00002062 // Create the new top level add instruction...
Chris Lattner48595f12004-06-10 02:07:29 +00002063 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00002064 }
2065
2066 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2067 //
2068 if (Op1I->getOpcode() == Instruction::And &&
2069 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2070 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2071
Chris Lattnerf523d062004-06-09 05:08:07 +00002072 Value *NewNot =
2073 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattner48595f12004-06-10 02:07:29 +00002074 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00002075 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00002076
Reid Spencerac5209e2006-10-16 23:08:08 +00002077 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer1628cec2006-10-26 06:15:43 +00002078 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencerb83eb642006-10-20 07:07:24 +00002079 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Reid Spencer1628cec2006-10-26 06:15:43 +00002080 if (CSI->isNullValue())
Chris Lattner91ccc152004-10-06 15:08:25 +00002081 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Reid Spencer1628cec2006-10-26 06:15:43 +00002082 return BinaryOperator::createSDiv(Op1I->getOperand(0),
Chris Lattner91ccc152004-10-06 15:08:25 +00002083 ConstantExpr::getNeg(DivRHS));
2084
Chris Lattnerad3448c2003-02-18 19:57:07 +00002085 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002086 ConstantInt *C2 = 0;
Chris Lattner50af16a2004-11-13 19:50:12 +00002087 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Misha Brukmanfd939082005-04-21 23:48:37 +00002088 Constant *CP1 =
Chris Lattner50af16a2004-11-13 19:50:12 +00002089 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
Chris Lattner48595f12004-06-10 02:07:29 +00002090 return BinaryOperator::createMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00002091 }
Chris Lattner40371712002-05-09 01:29:19 +00002092 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002093 }
Chris Lattnera2881962003-02-18 19:28:33 +00002094
Chris Lattner9919e3d2006-12-02 00:13:08 +00002095 if (!Op0->getType()->isFPOrFPVector())
Chris Lattner7edc8c22005-04-07 17:14:51 +00002096 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2097 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00002098 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2099 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2100 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2101 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner7edc8c22005-04-07 17:14:51 +00002102 } else if (Op0I->getOpcode() == Instruction::Sub) {
2103 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
2104 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00002105 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002106
Chris Lattner50af16a2004-11-13 19:50:12 +00002107 ConstantInt *C1;
2108 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2109 if (X == Op1) { // X*C - X --> X * (C-1)
2110 Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
2111 return BinaryOperator::createMul(Op1, CP1);
2112 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00002113
Chris Lattner50af16a2004-11-13 19:50:12 +00002114 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2115 if (X == dyn_castFoldableMul(Op1, C2))
2116 return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
2117 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002118 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002119}
2120
Reid Spencere4d87aa2006-12-23 06:05:41 +00002121/// isSignBitCheck - Given an exploded icmp instruction, return true if it
Chris Lattner4cb170c2004-02-23 06:38:22 +00002122/// really just returns true if the most significant (sign) bit is set.
Reid Spencere4d87aa2006-12-23 06:05:41 +00002123static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS) {
2124 switch (pred) {
2125 case ICmpInst::ICMP_SLT:
2126 // True if LHS s< RHS and RHS == 0
2127 return RHS->isNullValue();
2128 case ICmpInst::ICMP_SLE:
2129 // True if LHS s<= RHS and RHS == -1
2130 return RHS->isAllOnesValue();
2131 case ICmpInst::ICMP_UGE:
2132 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2133 return RHS->getZExtValue() == (1ULL <<
2134 (RHS->getType()->getPrimitiveSizeInBits()-1));
2135 case ICmpInst::ICMP_UGT:
2136 // True if LHS u> RHS and RHS == high-bit-mask - 1
2137 return RHS->getZExtValue() ==
Chris Lattner484d3cf2005-04-24 06:59:08 +00002138 (1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1))-1;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002139 default:
2140 return false;
Chris Lattner4cb170c2004-02-23 06:38:22 +00002141 }
Chris Lattner4cb170c2004-02-23 06:38:22 +00002142}
2143
Chris Lattner7e708292002-06-25 16:13:24 +00002144Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002145 bool Changed = SimplifyCommutative(I);
Chris Lattnera2881962003-02-18 19:28:33 +00002146 Value *Op0 = I.getOperand(0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002147
Chris Lattnere87597f2004-10-16 18:11:37 +00002148 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2149 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2150
Chris Lattner233f7dc2002-08-12 21:17:25 +00002151 // Simplify mul instructions with a constant RHS...
Chris Lattnera2881962003-02-18 19:28:33 +00002152 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2153 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00002154
2155 // ((X << C1)*C2) == (X * (C2 << C1))
2156 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
2157 if (SI->getOpcode() == Instruction::Shl)
2158 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattner48595f12004-06-10 02:07:29 +00002159 return BinaryOperator::createMul(SI->getOperand(0),
2160 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00002161
Chris Lattner515c97c2003-09-11 22:24:54 +00002162 if (CI->isNullValue())
2163 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2164 if (CI->equalsInt(1)) // X * 1 == X
2165 return ReplaceInstUsesWith(I, Op0);
2166 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner0af1fab2003-06-25 17:09:20 +00002167 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00002168
Reid Spencerb83eb642006-10-20 07:07:24 +00002169 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getZExtValue();
Chris Lattnerbcd7db52005-08-02 19:16:58 +00002170 if (isPowerOf2_64(Val)) { // Replace X*(2^C) with X << C
2171 uint64_t C = Log2_64(Val);
Chris Lattnera2881962003-02-18 19:28:33 +00002172 return new ShiftInst(Instruction::Shl, Op0,
Reid Spencerc5b206b2006-12-31 05:48:39 +00002173 ConstantInt::get(Type::Int8Ty, C));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00002174 }
Robert Bocchino71698282004-07-27 21:02:21 +00002175 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattnera2881962003-02-18 19:28:33 +00002176 if (Op1F->isNullValue())
2177 return ReplaceInstUsesWith(I, Op1);
Chris Lattner6c1ce212002-04-29 22:24:47 +00002178
Chris Lattnera2881962003-02-18 19:28:33 +00002179 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2180 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2181 if (Op1F->getValue() == 1.0)
2182 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2183 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002184
2185 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2186 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2187 isa<ConstantInt>(Op0I->getOperand(1))) {
2188 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2189 Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
2190 Op1, "tmp");
2191 InsertNewInstBefore(Add, I);
2192 Value *C1C2 = ConstantExpr::getMul(Op1,
2193 cast<Constant>(Op0I->getOperand(1)));
2194 return BinaryOperator::createAdd(Add, C1C2);
2195
2196 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002197
2198 // Try to fold constant mul into select arguments.
2199 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002200 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002201 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002202
2203 if (isa<PHINode>(Op0))
2204 if (Instruction *NV = FoldOpIntoPhi(I))
2205 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002206 }
2207
Chris Lattnera4f445b2003-03-10 23:23:04 +00002208 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2209 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattner48595f12004-06-10 02:07:29 +00002210 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00002211
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002212 // If one of the operands of the multiply is a cast from a boolean value, then
2213 // we know the bool is either zero or one, so this is a 'masking' multiply.
2214 // See if we can simplify things based on how the boolean was originally
2215 // formed.
2216 CastInst *BoolCast = 0;
Reid Spencerc55b2432006-12-13 18:21:21 +00002217 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(0)))
2218 if (CI->getOperand(0)->getType() == Type::BoolTy)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002219 BoolCast = CI;
2220 if (!BoolCast)
Reid Spencerc55b2432006-12-13 18:21:21 +00002221 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2222 if (CI->getOperand(0)->getType() == Type::BoolTy)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002223 BoolCast = CI;
2224 if (BoolCast) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002225 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002226 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2227 const Type *SCOpTy = SCIOp0->getType();
2228
Reid Spencere4d87aa2006-12-23 06:05:41 +00002229 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattner4cb170c2004-02-23 06:38:22 +00002230 // multiply into a shift/and combination.
2231 if (isa<ConstantInt>(SCIOp1) &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00002232 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1))) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002233 // Shift the X value right to turn it into "all signbits".
Reid Spencerc5b206b2006-12-31 05:48:39 +00002234 Constant *Amt = ConstantInt::get(Type::Int8Ty,
Chris Lattner484d3cf2005-04-24 06:59:08 +00002235 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattner4cb170c2004-02-23 06:38:22 +00002236 Value *V =
Reid Spencer3822ff52006-11-08 06:47:33 +00002237 InsertNewInstBefore(new ShiftInst(Instruction::AShr, SCIOp0, Amt,
Chris Lattner4cb170c2004-02-23 06:38:22 +00002238 BoolCast->getOperand(0)->getName()+
2239 ".mask"), I);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002240
2241 // If the multiply type is not the same as the source type, sign extend
2242 // or truncate to the multiply type.
Reid Spencer17212df2006-12-12 09:18:51 +00002243 if (I.getType() != V->getType()) {
2244 unsigned SrcBits = V->getType()->getPrimitiveSizeInBits();
2245 unsigned DstBits = I.getType()->getPrimitiveSizeInBits();
2246 Instruction::CastOps opcode =
2247 (SrcBits == DstBits ? Instruction::BitCast :
2248 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2249 V = InsertCastBefore(opcode, V, I.getType(), I);
2250 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002251
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002252 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattner48595f12004-06-10 02:07:29 +00002253 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002254 }
2255 }
2256 }
2257
Chris Lattner7e708292002-06-25 16:13:24 +00002258 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002259}
2260
Reid Spencer1628cec2006-10-26 06:15:43 +00002261/// This function implements the transforms on div instructions that work
2262/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2263/// used by the visitors to those instructions.
2264/// @brief Transforms common to all three div instructions
Reid Spencer3da59db2006-11-27 01:05:10 +00002265Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002266 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00002267
Reid Spencer1628cec2006-10-26 06:15:43 +00002268 // undef / X -> 0
2269 if (isa<UndefValue>(Op0))
Chris Lattner857e8cd2004-12-12 21:48:58 +00002270 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Reid Spencer1628cec2006-10-26 06:15:43 +00002271
2272 // X / undef -> undef
Chris Lattner857e8cd2004-12-12 21:48:58 +00002273 if (isa<UndefValue>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00002274 return ReplaceInstUsesWith(I, Op1);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002275
Reid Spencer1628cec2006-10-26 06:15:43 +00002276 // Handle cases involving: div X, (select Cond, Y, Z)
Chris Lattner8e49e082006-09-09 20:26:32 +00002277 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2278 // div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in the
Reid Spencer1628cec2006-10-26 06:15:43 +00002279 // same basic block, then we replace the select with Y, and the condition
2280 // of the select with false (if the cond value is in the same BB). If the
Chris Lattner8e49e082006-09-09 20:26:32 +00002281 // select has uses other than the div, this allows them to be simplified
Reid Spencer1628cec2006-10-26 06:15:43 +00002282 // also. Note that div X, Y is just as good as div X, 0 (undef)
Chris Lattner8e49e082006-09-09 20:26:32 +00002283 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2284 if (ST->isNullValue()) {
2285 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2286 if (CondI && CondI->getParent() == I.getParent())
Chris Lattner47811b72006-09-28 23:35:22 +00002287 UpdateValueUsesWith(CondI, ConstantBool::getFalse());
Chris Lattner8e49e082006-09-09 20:26:32 +00002288 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2289 I.setOperand(1, SI->getOperand(2));
2290 else
2291 UpdateValueUsesWith(SI, SI->getOperand(2));
2292 return &I;
2293 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002294
Chris Lattner8e49e082006-09-09 20:26:32 +00002295 // Likewise for: div X, (Cond ? Y : 0) -> div X, Y
2296 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2297 if (ST->isNullValue()) {
2298 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2299 if (CondI && CondI->getParent() == I.getParent())
Chris Lattner47811b72006-09-28 23:35:22 +00002300 UpdateValueUsesWith(CondI, ConstantBool::getTrue());
Chris Lattner8e49e082006-09-09 20:26:32 +00002301 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2302 I.setOperand(1, SI->getOperand(1));
2303 else
2304 UpdateValueUsesWith(SI, SI->getOperand(1));
2305 return &I;
2306 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002307 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002308
Reid Spencer1628cec2006-10-26 06:15:43 +00002309 return 0;
2310}
Misha Brukmanfd939082005-04-21 23:48:37 +00002311
Reid Spencer1628cec2006-10-26 06:15:43 +00002312/// This function implements the transforms common to both integer division
2313/// instructions (udiv and sdiv). It is called by the visitors to those integer
2314/// division instructions.
2315/// @brief Common integer divide transforms
Reid Spencer3da59db2006-11-27 01:05:10 +00002316Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002317 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2318
2319 if (Instruction *Common = commonDivTransforms(I))
2320 return Common;
2321
2322 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2323 // div X, 1 == X
2324 if (RHS->equalsInt(1))
2325 return ReplaceInstUsesWith(I, Op0);
2326
2327 // (X / C1) / C2 -> X / (C1*C2)
2328 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2329 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2330 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2331 return BinaryOperator::create(I.getOpcode(), LHS->getOperand(0),
2332 ConstantExpr::getMul(RHS, LHSRHS));
Chris Lattnerbf70b832005-04-08 04:03:26 +00002333 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002334
2335 if (!RHS->isNullValue()) { // avoid X udiv 0
2336 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2337 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2338 return R;
2339 if (isa<PHINode>(Op0))
2340 if (Instruction *NV = FoldOpIntoPhi(I))
2341 return NV;
2342 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002343 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002344
Chris Lattnera2881962003-02-18 19:28:33 +00002345 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00002346 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00002347 if (LHS->equalsInt(0))
2348 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2349
Reid Spencer1628cec2006-10-26 06:15:43 +00002350 return 0;
2351}
2352
2353Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2354 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2355
2356 // Handle the integer div common cases
2357 if (Instruction *Common = commonIDivTransforms(I))
2358 return Common;
2359
2360 // X udiv C^2 -> X >> C
2361 // Check to see if this is an unsigned division with an exact power of 2,
2362 // if so, convert to a right shift.
2363 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2364 if (uint64_t Val = C->getZExtValue()) // Don't break X / 0
2365 if (isPowerOf2_64(Val)) {
2366 uint64_t ShiftAmt = Log2_64(Val);
Reid Spencer3822ff52006-11-08 06:47:33 +00002367 return new ShiftInst(Instruction::LShr, Op0,
Reid Spencerc5b206b2006-12-31 05:48:39 +00002368 ConstantInt::get(Type::Int8Ty, ShiftAmt));
Reid Spencer1628cec2006-10-26 06:15:43 +00002369 }
2370 }
2371
2372 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
2373 if (ShiftInst *RHSI = dyn_cast<ShiftInst>(I.getOperand(1))) {
2374 if (RHSI->getOpcode() == Instruction::Shl &&
2375 isa<ConstantInt>(RHSI->getOperand(0))) {
2376 uint64_t C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
2377 if (isPowerOf2_64(C1)) {
2378 Value *N = RHSI->getOperand(1);
Reid Spencer3da59db2006-11-27 01:05:10 +00002379 const Type *NTy = N->getType();
Reid Spencer1628cec2006-10-26 06:15:43 +00002380 if (uint64_t C2 = Log2_64(C1)) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002381 Constant *C2V = ConstantInt::get(NTy, C2);
2382 N = InsertNewInstBefore(BinaryOperator::createAdd(N, C2V, "tmp"), I);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002383 }
Reid Spencer3822ff52006-11-08 06:47:33 +00002384 return new ShiftInst(Instruction::LShr, Op0, N);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002385 }
2386 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00002387 }
2388
Reid Spencer1628cec2006-10-26 06:15:43 +00002389 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2390 // where C1&C2 are powers of two.
2391 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2392 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2393 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))
2394 if (!STO->isNullValue() && !STO->isNullValue()) {
2395 uint64_t TVA = STO->getZExtValue(), FVA = SFO->getZExtValue();
2396 if (isPowerOf2_64(TVA) && isPowerOf2_64(FVA)) {
2397 // Compute the shift amounts
2398 unsigned TSA = Log2_64(TVA), FSA = Log2_64(FVA);
Reid Spencer1628cec2006-10-26 06:15:43 +00002399 // Construct the "on true" case of the select
Reid Spencerc5b206b2006-12-31 05:48:39 +00002400 Constant *TC = ConstantInt::get(Type::Int8Ty, TSA);
Reid Spencer1628cec2006-10-26 06:15:43 +00002401 Instruction *TSI =
Reid Spencer3822ff52006-11-08 06:47:33 +00002402 new ShiftInst(Instruction::LShr, Op0, TC, SI->getName()+".t");
Reid Spencer1628cec2006-10-26 06:15:43 +00002403 TSI = InsertNewInstBefore(TSI, I);
2404
2405 // Construct the "on false" case of the select
Reid Spencerc5b206b2006-12-31 05:48:39 +00002406 Constant *FC = ConstantInt::get(Type::Int8Ty, FSA);
Reid Spencer1628cec2006-10-26 06:15:43 +00002407 Instruction *FSI =
Reid Spencer3822ff52006-11-08 06:47:33 +00002408 new ShiftInst(Instruction::LShr, Op0, FC, SI->getName()+".f");
Reid Spencer1628cec2006-10-26 06:15:43 +00002409 FSI = InsertNewInstBefore(FSI, I);
2410
2411 // construct the select instruction and return it.
Reid Spencer3822ff52006-11-08 06:47:33 +00002412 return new SelectInst(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00002413 }
2414 }
2415 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002416 return 0;
2417}
2418
Reid Spencer1628cec2006-10-26 06:15:43 +00002419Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2420 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2421
2422 // Handle the integer div common cases
2423 if (Instruction *Common = commonIDivTransforms(I))
2424 return Common;
2425
2426 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2427 // sdiv X, -1 == -X
2428 if (RHS->isAllOnesValue())
2429 return BinaryOperator::createNeg(Op0);
2430
2431 // -X/C -> X/-C
2432 if (Value *LHSNeg = dyn_castNegVal(Op0))
2433 return BinaryOperator::createSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2434 }
2435
2436 // If the sign bits of both operands are zero (i.e. we can prove they are
2437 // unsigned inputs), turn this into a udiv.
2438 if (I.getType()->isInteger()) {
2439 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2440 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2441 return BinaryOperator::createUDiv(Op0, Op1, I.getName());
2442 }
2443 }
2444
2445 return 0;
2446}
2447
2448Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2449 return commonDivTransforms(I);
2450}
Chris Lattner3f5b8772002-05-06 16:14:14 +00002451
Chris Lattnerdb3f8732006-03-02 06:50:58 +00002452/// GetFactor - If we can prove that the specified value is at least a multiple
2453/// of some factor, return that factor.
2454static Constant *GetFactor(Value *V) {
2455 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2456 return CI;
2457
2458 // Unless we can be tricky, we know this is a multiple of 1.
2459 Constant *Result = ConstantInt::get(V->getType(), 1);
2460
2461 Instruction *I = dyn_cast<Instruction>(V);
2462 if (!I) return Result;
2463
2464 if (I->getOpcode() == Instruction::Mul) {
2465 // Handle multiplies by a constant, etc.
2466 return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
2467 GetFactor(I->getOperand(1)));
2468 } else if (I->getOpcode() == Instruction::Shl) {
2469 // (X<<C) -> X * (1 << C)
2470 if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
2471 ShRHS = ConstantExpr::getShl(Result, ShRHS);
2472 return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
2473 }
2474 } else if (I->getOpcode() == Instruction::And) {
2475 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
2476 // X & 0xFFF0 is known to be a multiple of 16.
2477 unsigned Zeros = CountTrailingZeros_64(RHS->getZExtValue());
2478 if (Zeros != V->getType()->getPrimitiveSizeInBits())
2479 return ConstantExpr::getShl(Result,
Reid Spencerc5b206b2006-12-31 05:48:39 +00002480 ConstantInt::get(Type::Int8Ty, Zeros));
Chris Lattnerdb3f8732006-03-02 06:50:58 +00002481 }
Reid Spencer3da59db2006-11-27 01:05:10 +00002482 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
Chris Lattnerdb3f8732006-03-02 06:50:58 +00002483 // Only handle int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00002484 if (!CI->isIntegerCast())
2485 return Result;
2486 Value *Op = CI->getOperand(0);
2487 return ConstantExpr::getCast(CI->getOpcode(), GetFactor(Op), V->getType());
Chris Lattnerdb3f8732006-03-02 06:50:58 +00002488 }
2489 return Result;
2490}
2491
Reid Spencer0a783f72006-11-02 01:53:59 +00002492/// This function implements the transforms on rem instructions that work
2493/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
2494/// is used by the visitors to those instructions.
2495/// @brief Transforms common to all three rem instructions
2496Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002497 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer0a783f72006-11-02 01:53:59 +00002498
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002499 // 0 % X == 0, we don't need to preserve faults!
2500 if (Constant *LHS = dyn_cast<Constant>(Op0))
2501 if (LHS->isNullValue())
2502 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2503
2504 if (isa<UndefValue>(Op0)) // undef % X -> 0
2505 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2506 if (isa<UndefValue>(Op1))
2507 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer0a783f72006-11-02 01:53:59 +00002508
2509 // Handle cases involving: rem X, (select Cond, Y, Z)
2510 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2511 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
2512 // the same basic block, then we replace the select with Y, and the
2513 // condition of the select with false (if the cond value is in the same
2514 // BB). If the select has uses other than the div, this allows them to be
2515 // simplified also.
2516 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2517 if (ST->isNullValue()) {
2518 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2519 if (CondI && CondI->getParent() == I.getParent())
2520 UpdateValueUsesWith(CondI, ConstantBool::getFalse());
2521 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2522 I.setOperand(1, SI->getOperand(2));
2523 else
2524 UpdateValueUsesWith(SI, SI->getOperand(2));
Chris Lattner5b73c082004-07-06 07:01:22 +00002525 return &I;
2526 }
Reid Spencer0a783f72006-11-02 01:53:59 +00002527 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2528 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2529 if (ST->isNullValue()) {
2530 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2531 if (CondI && CondI->getParent() == I.getParent())
2532 UpdateValueUsesWith(CondI, ConstantBool::getTrue());
2533 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2534 I.setOperand(1, SI->getOperand(1));
2535 else
2536 UpdateValueUsesWith(SI, SI->getOperand(1));
2537 return &I;
2538 }
Chris Lattner11a49f22005-11-05 07:28:37 +00002539 }
Chris Lattner5b73c082004-07-06 07:01:22 +00002540
Reid Spencer0a783f72006-11-02 01:53:59 +00002541 return 0;
2542}
2543
2544/// This function implements the transforms common to both integer remainder
2545/// instructions (urem and srem). It is called by the visitors to those integer
2546/// remainder instructions.
2547/// @brief Common integer remainder transforms
2548Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2549 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2550
2551 if (Instruction *common = commonRemTransforms(I))
2552 return common;
2553
Chris Lattner857e8cd2004-12-12 21:48:58 +00002554 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002555 // X % 0 == undef, we don't need to preserve faults!
2556 if (RHS->equalsInt(0))
2557 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2558
Chris Lattnera2881962003-02-18 19:28:33 +00002559 if (RHS->equalsInt(1)) // X % 1 == 0
2560 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2561
Chris Lattner97943922006-02-28 05:49:21 +00002562 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2563 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2564 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2565 return R;
2566 } else if (isa<PHINode>(Op0I)) {
2567 if (Instruction *NV = FoldOpIntoPhi(I))
2568 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00002569 }
Reid Spencer0a783f72006-11-02 01:53:59 +00002570 // (X * C1) % C2 --> 0 iff C1 % C2 == 0
2571 if (ConstantExpr::getSRem(GetFactor(Op0I), RHS)->isNullValue())
Chris Lattnerdb3f8732006-03-02 06:50:58 +00002572 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner97943922006-02-28 05:49:21 +00002573 }
Chris Lattnera2881962003-02-18 19:28:33 +00002574 }
2575
Reid Spencer0a783f72006-11-02 01:53:59 +00002576 return 0;
2577}
2578
2579Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2580 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2581
2582 if (Instruction *common = commonIRemTransforms(I))
2583 return common;
2584
2585 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2586 // X urem C^2 -> X and C
2587 // Check to see if this is an unsigned remainder with an exact power of 2,
2588 // if so, convert to a bitwise and.
2589 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
2590 if (isPowerOf2_64(C->getZExtValue()))
2591 return BinaryOperator::createAnd(Op0, SubOne(C));
2592 }
2593
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002594 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer0a783f72006-11-02 01:53:59 +00002595 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
2596 if (RHSI->getOpcode() == Instruction::Shl &&
2597 isa<ConstantInt>(RHSI->getOperand(0))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002598 unsigned C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002599 if (isPowerOf2_64(C1)) {
2600 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2601 Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
2602 "tmp"), I);
2603 return BinaryOperator::createAnd(Op0, Add);
2604 }
2605 }
Reid Spencer0a783f72006-11-02 01:53:59 +00002606 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002607
Reid Spencer0a783f72006-11-02 01:53:59 +00002608 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
2609 // where C1&C2 are powers of two.
2610 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2611 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2612 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2613 // STO == 0 and SFO == 0 handled above.
2614 if (isPowerOf2_64(STO->getZExtValue()) &&
2615 isPowerOf2_64(SFO->getZExtValue())) {
2616 Value *TrueAnd = InsertNewInstBefore(
2617 BinaryOperator::createAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
2618 Value *FalseAnd = InsertNewInstBefore(
2619 BinaryOperator::createAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
2620 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
2621 }
2622 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002623 }
2624
Chris Lattner3f5b8772002-05-06 16:14:14 +00002625 return 0;
2626}
2627
Reid Spencer0a783f72006-11-02 01:53:59 +00002628Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
2629 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2630
2631 if (Instruction *common = commonIRemTransforms(I))
2632 return common;
2633
2634 if (Value *RHSNeg = dyn_castNegVal(Op1))
2635 if (!isa<ConstantInt>(RHSNeg) ||
2636 cast<ConstantInt>(RHSNeg)->getSExtValue() > 0) {
2637 // X % -Y -> X % Y
2638 AddUsesToWorkList(I);
2639 I.setOperand(1, RHSNeg);
2640 return &I;
2641 }
2642
2643 // If the top bits of both operands are zero (i.e. we can prove they are
2644 // unsigned inputs), turn this into a urem.
2645 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2646 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2647 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
2648 return BinaryOperator::createURem(Op0, Op1, I.getName());
2649 }
2650
2651 return 0;
2652}
2653
2654Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer0a783f72006-11-02 01:53:59 +00002655 return commonRemTransforms(I);
2656}
2657
Chris Lattner8b170942002-08-09 23:47:40 +00002658// isMaxValueMinusOne - return true if this is Max-1
Reid Spencere4d87aa2006-12-23 06:05:41 +00002659static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
2660 if (isSigned) {
2661 // Calculate 0111111111..11111
2662 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
2663 int64_t Val = INT64_MAX; // All ones
2664 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
2665 return C->getSExtValue() == Val-1;
2666 }
2667 return C->getZExtValue() == C->getType()->getIntegralTypeMask()-1;
Chris Lattner8b170942002-08-09 23:47:40 +00002668}
2669
2670// isMinValuePlusOne - return true if this is Min+1
Reid Spencere4d87aa2006-12-23 06:05:41 +00002671static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
2672 if (isSigned) {
2673 // Calculate 1111111111000000000000
2674 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
2675 int64_t Val = -1; // All ones
2676 Val <<= TypeBits-1; // Shift over to the right spot
2677 return C->getSExtValue() == Val+1;
2678 }
2679 return C->getZExtValue() == 1; // unsigned
Chris Lattner8b170942002-08-09 23:47:40 +00002680}
2681
Chris Lattner457dd822004-06-09 07:59:58 +00002682// isOneBitSet - Return true if there is exactly one bit set in the specified
2683// constant.
2684static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002685 uint64_t V = CI->getZExtValue();
Chris Lattner457dd822004-06-09 07:59:58 +00002686 return V && (V & (V-1)) == 0;
2687}
2688
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00002689#if 0 // Currently unused
2690// isLowOnes - Return true if the constant is of the form 0+1+.
2691static bool isLowOnes(const ConstantInt *CI) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002692 uint64_t V = CI->getZExtValue();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00002693
2694 // There won't be bits set in parts that the type doesn't contain.
Reid Spencerb83eb642006-10-20 07:07:24 +00002695 V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00002696
2697 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2698 return U && V && (U & V) == 0;
2699}
2700#endif
2701
2702// isHighOnes - Return true if the constant is of the form 1+0+.
2703// This is the same as lowones(~X).
2704static bool isHighOnes(const ConstantInt *CI) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002705 uint64_t V = ~CI->getZExtValue();
Chris Lattner2b83af22005-08-07 07:03:10 +00002706 if (~V == 0) return false; // 0's does not match "1+"
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00002707
2708 // There won't be bits set in parts that the type doesn't contain.
Reid Spencerb83eb642006-10-20 07:07:24 +00002709 V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00002710
2711 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2712 return U && V && (U & V) == 0;
2713}
2714
Reid Spencere4d87aa2006-12-23 06:05:41 +00002715/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002716/// are carefully arranged to allow folding of expressions such as:
2717///
2718/// (A < B) | (A > B) --> (A != B)
2719///
Reid Spencere4d87aa2006-12-23 06:05:41 +00002720/// Note that this is only valid if the first and second predicates have the
2721/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002722///
Reid Spencere4d87aa2006-12-23 06:05:41 +00002723/// Three bits are used to represent the condition, as follows:
2724/// 0 A > B
2725/// 1 A == B
2726/// 2 A < B
2727///
2728/// <=> Value Definition
2729/// 000 0 Always false
2730/// 001 1 A > B
2731/// 010 2 A == B
2732/// 011 3 A >= B
2733/// 100 4 A < B
2734/// 101 5 A != B
2735/// 110 6 A <= B
2736/// 111 7 Always true
2737///
2738static unsigned getICmpCode(const ICmpInst *ICI) {
2739 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002740 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00002741 case ICmpInst::ICMP_UGT: return 1; // 001
2742 case ICmpInst::ICMP_SGT: return 1; // 001
2743 case ICmpInst::ICMP_EQ: return 2; // 010
2744 case ICmpInst::ICMP_UGE: return 3; // 011
2745 case ICmpInst::ICMP_SGE: return 3; // 011
2746 case ICmpInst::ICMP_ULT: return 4; // 100
2747 case ICmpInst::ICMP_SLT: return 4; // 100
2748 case ICmpInst::ICMP_NE: return 5; // 101
2749 case ICmpInst::ICMP_ULE: return 6; // 110
2750 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002751 // True -> 7
2752 default:
Reid Spencere4d87aa2006-12-23 06:05:41 +00002753 assert(0 && "Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002754 return 0;
2755 }
2756}
2757
Reid Spencere4d87aa2006-12-23 06:05:41 +00002758/// getICmpValue - This is the complement of getICmpCode, which turns an
2759/// opcode and two operands into either a constant true or false, or a brand
2760/// new /// ICmp instruction. The sign is passed in to determine which kind
2761/// of predicate to use in new icmp instructions.
2762static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
2763 switch (code) {
2764 default: assert(0 && "Illegal ICmp code!");
2765 case 0: return ConstantBool::getFalse();
2766 case 1:
2767 if (sign)
2768 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
2769 else
2770 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
2771 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
2772 case 3:
2773 if (sign)
2774 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
2775 else
2776 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
2777 case 4:
2778 if (sign)
2779 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
2780 else
2781 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
2782 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
2783 case 6:
2784 if (sign)
2785 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
2786 else
2787 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
2788 case 7: return ConstantBool::getTrue();
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002789 }
2790}
2791
Reid Spencere4d87aa2006-12-23 06:05:41 +00002792static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
2793 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
2794 (ICmpInst::isSignedPredicate(p1) &&
2795 (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
2796 (ICmpInst::isSignedPredicate(p2) &&
2797 (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
2798}
2799
2800namespace {
2801// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
2802struct FoldICmpLogical {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002803 InstCombiner &IC;
2804 Value *LHS, *RHS;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002805 ICmpInst::Predicate pred;
2806 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
2807 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
2808 pred(ICI->getPredicate()) {}
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002809 bool shouldApply(Value *V) const {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002810 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
2811 if (PredicatesFoldable(pred, ICI->getPredicate()))
2812 return (ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS ||
2813 ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002814 return false;
2815 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00002816 Instruction *apply(Instruction &Log) const {
2817 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
2818 if (ICI->getOperand(0) != LHS) {
2819 assert(ICI->getOperand(1) == LHS);
2820 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002821 }
2822
Reid Spencere4d87aa2006-12-23 06:05:41 +00002823 unsigned LHSCode = getICmpCode(ICI);
2824 unsigned RHSCode = getICmpCode(cast<ICmpInst>(Log.getOperand(1)));
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002825 unsigned Code;
2826 switch (Log.getOpcode()) {
2827 case Instruction::And: Code = LHSCode & RHSCode; break;
2828 case Instruction::Or: Code = LHSCode | RHSCode; break;
2829 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner021c1902003-09-22 20:33:34 +00002830 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002831 }
2832
Reid Spencere4d87aa2006-12-23 06:05:41 +00002833 Value *RV = getICmpValue(ICmpInst::isSignedPredicate(pred), Code, LHS, RHS);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002834 if (Instruction *I = dyn_cast<Instruction>(RV))
2835 return I;
2836 // Otherwise, it's a constant boolean value...
2837 return IC.ReplaceInstUsesWith(Log, RV);
2838 }
2839};
Chris Lattnerd23b5ba2006-11-15 04:53:24 +00002840} // end anonymous namespace
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002841
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002842// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
2843// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
2844// guaranteed to be either a shift instruction or a binary operator.
2845Instruction *InstCombiner::OptAndOp(Instruction *Op,
2846 ConstantIntegral *OpRHS,
2847 ConstantIntegral *AndRHS,
2848 BinaryOperator &TheAnd) {
2849 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00002850 Constant *Together = 0;
2851 if (!isa<ShiftInst>(Op))
Chris Lattner48595f12004-06-10 02:07:29 +00002852 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00002853
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002854 switch (Op->getOpcode()) {
2855 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00002856 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002857 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
2858 std::string OpName = Op->getName(); Op->setName("");
Chris Lattner48595f12004-06-10 02:07:29 +00002859 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002860 InsertNewInstBefore(And, TheAnd);
Chris Lattner48595f12004-06-10 02:07:29 +00002861 return BinaryOperator::createXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002862 }
2863 break;
2864 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00002865 if (Together == AndRHS) // (X | C) & C --> C
2866 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00002867
Chris Lattner6e7ba452005-01-01 16:22:27 +00002868 if (Op->hasOneUse() && Together != OpRHS) {
2869 // (X | C1) & C2 --> (X | (C1&C2)) & C2
2870 std::string Op0Name = Op->getName(); Op->setName("");
2871 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
2872 InsertNewInstBefore(Or, TheAnd);
2873 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002874 }
2875 break;
2876 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00002877 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002878 // Adding a one to a single bit bit-field should be turned into an XOR
2879 // of the bit. First thing to check is to see if this AND is with a
2880 // single bit constant.
Reid Spencerb83eb642006-10-20 07:07:24 +00002881 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getZExtValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002882
2883 // Clear bits that are not part of the constant.
Chris Lattner1a074fc2006-02-07 07:00:41 +00002884 AndRHSV &= AndRHS->getType()->getIntegralTypeMask();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002885
2886 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00002887 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002888 // Ok, at this point, we know that we are masking the result of the
2889 // ADD down to exactly one bit. If the constant we are adding has
2890 // no bits set below this bit, then we can eliminate the ADD.
Reid Spencerb83eb642006-10-20 07:07:24 +00002891 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getZExtValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00002892
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002893 // Check to see if any bits below the one bit set in AndRHSV are set.
2894 if ((AddRHS & (AndRHSV-1)) == 0) {
2895 // If not, the only thing that can effect the output of the AND is
2896 // the bit specified by AndRHSV. If that bit is set, the effect of
2897 // the XOR is to toggle the bit. If it is clear, then the ADD has
2898 // no effect.
2899 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
2900 TheAnd.setOperand(0, X);
2901 return &TheAnd;
2902 } else {
2903 std::string Name = Op->getName(); Op->setName("");
2904 // Pull the XOR out of the AND.
Chris Lattner48595f12004-06-10 02:07:29 +00002905 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002906 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner48595f12004-06-10 02:07:29 +00002907 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002908 }
2909 }
2910 }
2911 }
2912 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00002913
2914 case Instruction::Shl: {
2915 // We know that the AND will not produce any of the bits shifted in, so if
2916 // the anded constant includes them, clear them now!
2917 //
2918 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner0c967662004-09-24 15:21:34 +00002919 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
2920 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00002921
Chris Lattner0c967662004-09-24 15:21:34 +00002922 if (CI == ShlMask) { // Masking out bits that the shift already masks
2923 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
2924 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00002925 TheAnd.setOperand(1, CI);
2926 return &TheAnd;
2927 }
2928 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00002929 }
Reid Spencer3822ff52006-11-08 06:47:33 +00002930 case Instruction::LShr:
2931 {
Chris Lattner62a355c2003-09-19 19:05:02 +00002932 // We know that the AND will not produce any of the bits shifted in, so if
2933 // the anded constant includes them, clear them now! This only applies to
2934 // unsigned shifts, because a signed shr may bring in set bits!
2935 //
Reid Spencer3822ff52006-11-08 06:47:33 +00002936 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2937 Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
2938 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00002939
Reid Spencer3822ff52006-11-08 06:47:33 +00002940 if (CI == ShrMask) { // Masking out bits that the shift already masks.
2941 return ReplaceInstUsesWith(TheAnd, Op);
2942 } else if (CI != AndRHS) {
2943 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
2944 return &TheAnd;
2945 }
2946 break;
2947 }
2948 case Instruction::AShr:
2949 // Signed shr.
2950 // See if this is shifting in some sign extension, then masking it out
2951 // with an and.
2952 if (Op->hasOneUse()) {
2953 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2954 Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
Reid Spencer7eb76382006-12-13 17:19:09 +00002955 Constant *C = ConstantExpr::getAnd(AndRHS, ShrMask);
2956 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +00002957 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +00002958 // Make the argument unsigned.
2959 Value *ShVal = Op->getOperand(0);
Reid Spencer7eb76382006-12-13 17:19:09 +00002960 ShVal = InsertNewInstBefore(new ShiftInst(Instruction::LShr, ShVal,
2961 OpRHS, Op->getName()), TheAnd);
2962 return BinaryOperator::createAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00002963 }
Chris Lattner62a355c2003-09-19 19:05:02 +00002964 }
2965 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002966 }
2967 return 0;
2968}
2969
Chris Lattner8b170942002-08-09 23:47:40 +00002970
Chris Lattnera96879a2004-09-29 17:40:11 +00002971/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
2972/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +00002973/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
2974/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +00002975/// insert new instructions.
2976Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +00002977 bool isSigned, bool Inside,
2978 Instruction &IB) {
2979 assert(cast<ConstantBool>(ConstantExpr::getICmp((isSigned ?
2980 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +00002981 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00002982
Chris Lattnera96879a2004-09-29 17:40:11 +00002983 if (Inside) {
2984 if (Lo == Hi) // Trivially false.
Reid Spencere4d87aa2006-12-23 06:05:41 +00002985 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +00002986
Reid Spencere4d87aa2006-12-23 06:05:41 +00002987 // V >= Min && V < Hi --> V < Hi
2988 if (cast<ConstantIntegral>(Lo)->isMinValue(isSigned)) {
2989 ICmpInst::Predicate pred = (isSigned ?
2990 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
2991 return new ICmpInst(pred, V, Hi);
2992 }
2993
2994 // Emit V-Lo <u Hi-Lo
2995 Constant *NegLo = ConstantExpr::getNeg(Lo);
2996 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00002997 InsertNewInstBefore(Add, IB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002998 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
2999 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003000 }
3001
3002 if (Lo == Hi) // Trivially true.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003003 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +00003004
Reid Spencere4d87aa2006-12-23 06:05:41 +00003005 // V < Min || V >= Hi ->'V > Hi-1'
Chris Lattnera96879a2004-09-29 17:40:11 +00003006 Hi = SubOne(cast<ConstantInt>(Hi));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003007 if (cast<ConstantIntegral>(Lo)->isMinValue(isSigned)) {
3008 ICmpInst::Predicate pred = (isSigned ?
3009 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3010 return new ICmpInst(pred, V, Hi);
3011 }
Reid Spencerb83eb642006-10-20 07:07:24 +00003012
Reid Spencere4d87aa2006-12-23 06:05:41 +00003013 // Emit V-Lo > Hi-1-Lo
3014 Constant *NegLo = ConstantExpr::getNeg(Lo);
3015 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003016 InsertNewInstBefore(Add, IB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003017 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3018 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003019}
3020
Chris Lattner7203e152005-09-18 07:22:02 +00003021// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3022// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3023// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3024// not, since all 1s are not contiguous.
3025static bool isRunOfOnes(ConstantIntegral *Val, unsigned &MB, unsigned &ME) {
Reid Spencerb83eb642006-10-20 07:07:24 +00003026 uint64_t V = Val->getZExtValue();
Chris Lattner7203e152005-09-18 07:22:02 +00003027 if (!isShiftedMask_64(V)) return false;
3028
3029 // look for the first zero bit after the run of ones
3030 MB = 64-CountLeadingZeros_64((V - 1) ^ V);
3031 // look for the first non-zero bit
3032 ME = 64-CountLeadingZeros_64(V);
3033 return true;
3034}
3035
3036
3037
3038/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3039/// where isSub determines whether the operator is a sub. If we can fold one of
3040/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00003041///
3042/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3043/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3044/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3045///
3046/// return (A +/- B).
3047///
3048Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3049 ConstantIntegral *Mask, bool isSub,
3050 Instruction &I) {
3051 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3052 if (!LHSI || LHSI->getNumOperands() != 2 ||
3053 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3054
3055 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3056
3057 switch (LHSI->getOpcode()) {
3058 default: return 0;
3059 case Instruction::And:
Chris Lattner7203e152005-09-18 07:22:02 +00003060 if (ConstantExpr::getAnd(N, Mask) == Mask) {
3061 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Reid Spencerb83eb642006-10-20 07:07:24 +00003062 if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0)
Chris Lattner7203e152005-09-18 07:22:02 +00003063 break;
3064
3065 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3066 // part, we don't need any explicit masks to take them out of A. If that
3067 // is all N is, ignore it.
3068 unsigned MB, ME;
3069 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Chris Lattner3bedbd92006-02-07 07:27:52 +00003070 uint64_t Mask = RHS->getType()->getIntegralTypeMask();
3071 Mask >>= 64-MB+1;
3072 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00003073 break;
3074 }
3075 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00003076 return 0;
3077 case Instruction::Or:
3078 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00003079 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Reid Spencerb83eb642006-10-20 07:07:24 +00003080 if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0 &&
Chris Lattner7203e152005-09-18 07:22:02 +00003081 ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattnerc8e77562005-09-18 04:24:45 +00003082 break;
3083 return 0;
3084 }
3085
3086 Instruction *New;
3087 if (isSub)
3088 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
3089 else
3090 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
3091 return InsertNewInstBefore(New, I);
3092}
3093
Chris Lattner7e708292002-06-25 16:13:24 +00003094Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003095 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00003096 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003097
Chris Lattnere87597f2004-10-16 18:11:37 +00003098 if (isa<UndefValue>(Op1)) // X & undef -> 0
3099 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3100
Chris Lattner6e7ba452005-01-01 16:22:27 +00003101 // and X, X = X
3102 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00003103 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003104
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003105 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00003106 // purpose is to compute bits we don't care about.
Chris Lattner255d8912006-02-11 09:31:47 +00003107 uint64_t KnownZero, KnownOne;
Chris Lattner98509ef2006-03-25 21:58:26 +00003108 if (!isa<PackedType>(I.getType()) &&
3109 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattner255d8912006-02-11 09:31:47 +00003110 KnownZero, KnownOne))
Chris Lattner9ca96412006-02-08 03:25:32 +00003111 return &I;
3112
Chris Lattner6e7ba452005-01-01 16:22:27 +00003113 if (ConstantIntegral *AndRHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner7560c3a2006-02-08 07:34:50 +00003114 uint64_t AndRHSMask = AndRHS->getZExtValue();
3115 uint64_t TypeMask = Op0->getType()->getIntegralTypeMask();
Chris Lattner7560c3a2006-02-08 07:34:50 +00003116 uint64_t NotAndRHS = AndRHSMask^TypeMask;
Chris Lattner6e7ba452005-01-01 16:22:27 +00003117
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003118 // Optimize a variety of ((val OP C1) & C2) combinations...
3119 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
3120 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003121 Value *Op0LHS = Op0I->getOperand(0);
3122 Value *Op0RHS = Op0I->getOperand(1);
3123 switch (Op0I->getOpcode()) {
3124 case Instruction::Xor:
3125 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00003126 // If the mask is only needed on one incoming arm, push it up.
3127 if (Op0I->hasOneUse()) {
3128 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3129 // Not masking anything out for the LHS, move to RHS.
3130 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
3131 Op0RHS->getName()+".masked");
3132 InsertNewInstBefore(NewRHS, I);
3133 return BinaryOperator::create(
3134 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003135 }
Chris Lattner3bedbd92006-02-07 07:27:52 +00003136 if (!isa<Constant>(Op0RHS) &&
Chris Lattnerad1e3022005-01-23 20:26:55 +00003137 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3138 // Not masking anything out for the RHS, move to LHS.
3139 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
3140 Op0LHS->getName()+".masked");
3141 InsertNewInstBefore(NewLHS, I);
3142 return BinaryOperator::create(
3143 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3144 }
3145 }
3146
Chris Lattner6e7ba452005-01-01 16:22:27 +00003147 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00003148 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00003149 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3150 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3151 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3152 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3153 return BinaryOperator::createAnd(V, AndRHS);
3154 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3155 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00003156 break;
3157
3158 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00003159 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3160 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3161 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3162 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3163 return BinaryOperator::createAnd(V, AndRHS);
Chris Lattnerc8e77562005-09-18 04:24:45 +00003164 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00003165 }
3166
Chris Lattner58403262003-07-23 19:25:52 +00003167 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003168 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003169 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00003170 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00003171 // If this is an integer truncation or change from signed-to-unsigned, and
3172 // if the source is an and/or with immediate, transform it. This
3173 // frequently occurs for bitfield accesses.
3174 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00003175 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00003176 CastOp->getNumOperands() == 2)
Chris Lattner7560c3a2006-02-08 07:34:50 +00003177 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
Chris Lattner2b83af22005-08-07 07:03:10 +00003178 if (CastOp->getOpcode() == Instruction::And) {
3179 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00003180 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
3181 // This will fold the two constants together, which may allow
3182 // other simplifications.
Reid Spencerd977d862006-12-12 23:36:14 +00003183 Instruction *NewCast = CastInst::createTruncOrBitCast(
3184 CastOp->getOperand(0), I.getType(),
3185 CastOp->getName()+".shrunk");
Chris Lattner2b83af22005-08-07 07:03:10 +00003186 NewCast = InsertNewInstBefore(NewCast, I);
Reid Spencer3da59db2006-11-27 01:05:10 +00003187 // trunc_or_bitcast(C1)&C2
Reid Spencerd977d862006-12-12 23:36:14 +00003188 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00003189 C3 = ConstantExpr::getAnd(C3, AndRHS);
Chris Lattner2b83af22005-08-07 07:03:10 +00003190 return BinaryOperator::createAnd(NewCast, C3);
3191 } else if (CastOp->getOpcode() == Instruction::Or) {
3192 // Change: and (cast (or X, C1) to T), C2
3193 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattnerbb4e7b22006-12-12 19:11:20 +00003194 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Chris Lattner2b83af22005-08-07 07:03:10 +00003195 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3196 return ReplaceInstUsesWith(I, AndRHS);
3197 }
3198 }
Chris Lattner06782f82003-07-23 19:36:21 +00003199 }
Chris Lattner2eefe512004-04-09 19:05:30 +00003200
3201 // Try to fold constant and into select arguments.
3202 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003203 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00003204 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00003205 if (isa<PHINode>(Op0))
3206 if (Instruction *NV = FoldOpIntoPhi(I))
3207 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00003208 }
3209
Chris Lattner8d969642003-03-10 23:06:50 +00003210 Value *Op0NotVal = dyn_castNotVal(Op0);
3211 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00003212
Chris Lattner5b62aa72004-06-18 06:07:51 +00003213 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3214 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3215
Misha Brukmancb6267b2004-07-30 12:50:08 +00003216 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00003217 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattner48595f12004-06-10 02:07:29 +00003218 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
3219 I.getName()+".demorgan");
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00003220 InsertNewInstBefore(Or, I);
Chris Lattnera2881962003-02-18 19:28:33 +00003221 return BinaryOperator::createNot(Or);
3222 }
Chris Lattner2082ad92006-02-13 23:07:23 +00003223
3224 {
3225 Value *A = 0, *B = 0;
Chris Lattner2082ad92006-02-13 23:07:23 +00003226 if (match(Op0, m_Or(m_Value(A), m_Value(B))))
3227 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3228 return ReplaceInstUsesWith(I, Op1);
3229 if (match(Op1, m_Or(m_Value(A), m_Value(B))))
3230 if (A == Op0 || B == Op0) // A & (A | ?) --> A
3231 return ReplaceInstUsesWith(I, Op0);
Chris Lattner64daab52006-04-01 08:03:55 +00003232
3233 if (Op0->hasOneUse() &&
3234 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3235 if (A == Op1) { // (A^B)&A -> A&(A^B)
3236 I.swapOperands(); // Simplify below
3237 std::swap(Op0, Op1);
3238 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
3239 cast<BinaryOperator>(Op0)->swapOperands();
3240 I.swapOperands(); // Simplify below
3241 std::swap(Op0, Op1);
3242 }
3243 }
3244 if (Op1->hasOneUse() &&
3245 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3246 if (B == Op0) { // B&(A^B) -> B&(B^A)
3247 cast<BinaryOperator>(Op1)->swapOperands();
3248 std::swap(A, B);
3249 }
3250 if (A == Op0) { // A&(A^B) -> A & ~B
3251 Instruction *NotB = BinaryOperator::createNot(B, "tmp");
3252 InsertNewInstBefore(NotB, I);
3253 return BinaryOperator::createAnd(A, NotB);
3254 }
3255 }
Chris Lattner2082ad92006-02-13 23:07:23 +00003256 }
3257
Reid Spencere4d87aa2006-12-23 06:05:41 +00003258 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3259 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3260 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003261 return R;
3262
Chris Lattner955f3312004-09-28 21:48:02 +00003263 Value *LHSVal, *RHSVal;
3264 ConstantInt *LHSCst, *RHSCst;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003265 ICmpInst::Predicate LHSCC, RHSCC;
3266 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3267 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3268 if (LHSVal == RHSVal && // Found (X icmp C1) & (X icmp C2)
3269 // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3270 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3271 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3272 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3273 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE) {
Chris Lattner955f3312004-09-28 21:48:02 +00003274 // Ensure that the larger constant is on the RHS.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003275 ICmpInst::Predicate GT = ICmpInst::isSignedPredicate(LHSCC) ?
3276 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
3277 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3278 ICmpInst *LHS = cast<ICmpInst>(Op0);
Chris Lattner955f3312004-09-28 21:48:02 +00003279 if (cast<ConstantBool>(Cmp)->getValue()) {
3280 std::swap(LHS, RHS);
3281 std::swap(LHSCst, RHSCst);
3282 std::swap(LHSCC, RHSCC);
3283 }
3284
Reid Spencere4d87aa2006-12-23 06:05:41 +00003285 // At this point, we know we have have two icmp instructions
Chris Lattner955f3312004-09-28 21:48:02 +00003286 // comparing a value against two constants and and'ing the result
3287 // together. Because of the above check, we know that we only have
Reid Spencere4d87aa2006-12-23 06:05:41 +00003288 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3289 // (from the FoldICmpLogical check above), that the two constants
3290 // are not equal and that the larger constant is on the RHS
Chris Lattner955f3312004-09-28 21:48:02 +00003291 assert(LHSCst != RHSCst && "Compares not folded above?");
3292
3293 switch (LHSCC) {
3294 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003295 case ICmpInst::ICMP_EQ:
Chris Lattner955f3312004-09-28 21:48:02 +00003296 switch (RHSCC) {
3297 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003298 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3299 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3300 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Chris Lattner47811b72006-09-28 23:35:22 +00003301 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00003302 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3303 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3304 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
Chris Lattner955f3312004-09-28 21:48:02 +00003305 return ReplaceInstUsesWith(I, LHS);
3306 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003307 case ICmpInst::ICMP_NE:
Chris Lattner955f3312004-09-28 21:48:02 +00003308 switch (RHSCC) {
3309 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003310 case ICmpInst::ICMP_ULT:
3311 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3312 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
3313 break; // (X != 13 & X u< 15) -> no change
3314 case ICmpInst::ICMP_SLT:
3315 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3316 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
3317 break; // (X != 13 & X s< 15) -> no change
3318 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3319 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3320 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
Chris Lattner955f3312004-09-28 21:48:02 +00003321 return ReplaceInstUsesWith(I, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003322 case ICmpInst::ICMP_NE:
3323 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Chris Lattner955f3312004-09-28 21:48:02 +00003324 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3325 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3326 LHSVal->getName()+".off");
3327 InsertNewInstBefore(Add, I);
Reid Spencerc5b206b2006-12-31 05:48:39 +00003328 return new ICmpInst(ICmpInst::ICMP_UGT, Add, AddCST);
Chris Lattner955f3312004-09-28 21:48:02 +00003329 }
3330 break; // (X != 13 & X != 15) -> no change
3331 }
3332 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003333 case ICmpInst::ICMP_ULT:
Chris Lattner955f3312004-09-28 21:48:02 +00003334 switch (RHSCC) {
3335 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003336 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3337 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Chris Lattner47811b72006-09-28 23:35:22 +00003338 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00003339 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3340 break;
3341 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3342 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
Chris Lattner955f3312004-09-28 21:48:02 +00003343 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003344 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3345 break;
Chris Lattner955f3312004-09-28 21:48:02 +00003346 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003347 break;
3348 case ICmpInst::ICMP_SLT:
Chris Lattner955f3312004-09-28 21:48:02 +00003349 switch (RHSCC) {
3350 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003351 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3352 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
3353 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
3354 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3355 break;
3356 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3357 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
Chris Lattner955f3312004-09-28 21:48:02 +00003358 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003359 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3360 break;
Chris Lattner955f3312004-09-28 21:48:02 +00003361 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003362 break;
3363 case ICmpInst::ICMP_UGT:
3364 switch (RHSCC) {
3365 default: assert(0 && "Unknown integer condition code!");
3366 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X > 13
3367 return ReplaceInstUsesWith(I, LHS);
3368 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3369 return ReplaceInstUsesWith(I, RHS);
3370 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3371 break;
3372 case ICmpInst::ICMP_NE:
3373 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3374 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3375 break; // (X u> 13 & X != 15) -> no change
3376 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) ->(X-14) <u 1
3377 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false,
3378 true, I);
3379 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3380 break;
3381 }
3382 break;
3383 case ICmpInst::ICMP_SGT:
3384 switch (RHSCC) {
3385 default: assert(0 && "Unknown integer condition code!");
3386 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X s> 13
3387 return ReplaceInstUsesWith(I, LHS);
3388 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3389 return ReplaceInstUsesWith(I, RHS);
3390 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3391 break;
3392 case ICmpInst::ICMP_NE:
3393 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3394 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3395 break; // (X s> 13 & X != 15) -> no change
3396 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) ->(X-14) s< 1
3397 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true,
3398 true, I);
3399 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3400 break;
3401 }
3402 break;
Chris Lattner955f3312004-09-28 21:48:02 +00003403 }
3404 }
3405 }
3406
Chris Lattner6fc205f2006-05-05 06:39:07 +00003407 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003408 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3409 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3410 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3411 const Type *SrcTy = Op0C->getOperand(0)->getType();
3412 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
3413 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003414 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
3415 I.getType(), TD) &&
3416 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
3417 I.getType(), TD)) {
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003418 Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
3419 Op1C->getOperand(0),
3420 I.getName());
3421 InsertNewInstBefore(NewOp, I);
3422 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3423 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00003424 }
Chris Lattnere511b742006-11-14 07:46:50 +00003425
3426 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
3427 if (ShiftInst *SI1 = dyn_cast<ShiftInst>(Op1)) {
3428 if (ShiftInst *SI0 = dyn_cast<ShiftInst>(Op0))
3429 if (SI0->getOpcode() == SI1->getOpcode() &&
3430 SI0->getOperand(1) == SI1->getOperand(1) &&
3431 (SI0->hasOneUse() || SI1->hasOneUse())) {
3432 Instruction *NewOp =
3433 InsertNewInstBefore(BinaryOperator::createAnd(SI0->getOperand(0),
3434 SI1->getOperand(0),
3435 SI0->getName()), I);
3436 return new ShiftInst(SI1->getOpcode(), NewOp, SI1->getOperand(1));
3437 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00003438 }
3439
Chris Lattner7e708292002-06-25 16:13:24 +00003440 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00003441}
3442
Chris Lattnerafe91a52006-06-15 19:07:26 +00003443/// CollectBSwapParts - Look to see if the specified value defines a single byte
3444/// in the result. If it does, and if the specified byte hasn't been filled in
3445/// yet, fill it in and return false.
3446static bool CollectBSwapParts(Value *V, std::vector<Value*> &ByteValues) {
3447 Instruction *I = dyn_cast<Instruction>(V);
3448 if (I == 0) return true;
3449
3450 // If this is an or instruction, it is an inner node of the bswap.
3451 if (I->getOpcode() == Instruction::Or)
3452 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3453 CollectBSwapParts(I->getOperand(1), ByteValues);
3454
3455 // If this is a shift by a constant int, and it is "24", then its operand
3456 // defines a byte. We only handle unsigned types here.
3457 if (isa<ShiftInst>(I) && isa<ConstantInt>(I->getOperand(1))) {
3458 // Not shifting the entire input by N-1 bytes?
Reid Spencerb83eb642006-10-20 07:07:24 +00003459 if (cast<ConstantInt>(I->getOperand(1))->getZExtValue() !=
Chris Lattnerafe91a52006-06-15 19:07:26 +00003460 8*(ByteValues.size()-1))
3461 return true;
3462
3463 unsigned DestNo;
3464 if (I->getOpcode() == Instruction::Shl) {
3465 // X << 24 defines the top byte with the lowest of the input bytes.
3466 DestNo = ByteValues.size()-1;
3467 } else {
3468 // X >>u 24 defines the low byte with the highest of the input bytes.
3469 DestNo = 0;
3470 }
3471
3472 // If the destination byte value is already defined, the values are or'd
3473 // together, which isn't a bswap (unless it's an or of the same bits).
3474 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3475 return true;
3476 ByteValues[DestNo] = I->getOperand(0);
3477 return false;
3478 }
3479
3480 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
3481 // don't have this.
3482 Value *Shift = 0, *ShiftLHS = 0;
3483 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3484 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3485 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3486 return true;
3487 Instruction *SI = cast<Instruction>(Shift);
3488
3489 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
Reid Spencerb83eb642006-10-20 07:07:24 +00003490 if (ShiftAmt->getZExtValue() & 7 ||
3491 ShiftAmt->getZExtValue() > 8*ByteValues.size())
Chris Lattnerafe91a52006-06-15 19:07:26 +00003492 return true;
3493
3494 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3495 unsigned DestByte;
3496 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
Reid Spencerb83eb642006-10-20 07:07:24 +00003497 if (AndAmt->getZExtValue() == uint64_t(0xFF) << 8*DestByte)
Chris Lattnerafe91a52006-06-15 19:07:26 +00003498 break;
3499 // Unknown mask for bswap.
3500 if (DestByte == ByteValues.size()) return true;
3501
Reid Spencerb83eb642006-10-20 07:07:24 +00003502 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
Chris Lattnerafe91a52006-06-15 19:07:26 +00003503 unsigned SrcByte;
3504 if (SI->getOpcode() == Instruction::Shl)
3505 SrcByte = DestByte - ShiftBytes;
3506 else
3507 SrcByte = DestByte + ShiftBytes;
3508
3509 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3510 if (SrcByte != ByteValues.size()-DestByte-1)
3511 return true;
3512
3513 // If the destination byte value is already defined, the values are or'd
3514 // together, which isn't a bswap (unless it's an or of the same bits).
3515 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3516 return true;
3517 ByteValues[DestByte] = SI->getOperand(0);
3518 return false;
3519}
3520
3521/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3522/// If so, insert the new bswap intrinsic and return it.
3523Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
3524 // We can only handle bswap of unsigned integers, and cannot bswap one byte.
Reid Spencerc5b206b2006-12-31 05:48:39 +00003525 if (I.getType() == Type::Int8Ty)
Chris Lattnerafe91a52006-06-15 19:07:26 +00003526 return 0;
3527
3528 /// ByteValues - For each byte of the result, we keep track of which value
3529 /// defines each byte.
3530 std::vector<Value*> ByteValues;
3531 ByteValues.resize(I.getType()->getPrimitiveSize());
3532
3533 // Try to find all the pieces corresponding to the bswap.
3534 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3535 CollectBSwapParts(I.getOperand(1), ByteValues))
3536 return 0;
3537
3538 // Check to see if all of the bytes come from the same value.
3539 Value *V = ByteValues[0];
3540 if (V == 0) return 0; // Didn't find a byte? Must be zero.
3541
3542 // Check to make sure that all of the bytes come from the same value.
3543 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3544 if (ByteValues[i] != V)
3545 return 0;
3546
3547 // If they do then *success* we can turn this into a bswap. Figure out what
3548 // bswap to make it into.
3549 Module *M = I.getParent()->getParent()->getParent();
Chris Lattnered36b2f2006-07-11 18:31:26 +00003550 const char *FnName = 0;
Reid Spencerc5b206b2006-12-31 05:48:39 +00003551 if (I.getType() == Type::Int16Ty)
Chris Lattnerafe91a52006-06-15 19:07:26 +00003552 FnName = "llvm.bswap.i16";
Reid Spencerc5b206b2006-12-31 05:48:39 +00003553 else if (I.getType() == Type::Int32Ty)
Chris Lattnerafe91a52006-06-15 19:07:26 +00003554 FnName = "llvm.bswap.i32";
Reid Spencerc5b206b2006-12-31 05:48:39 +00003555 else if (I.getType() == Type::Int64Ty)
Chris Lattnerafe91a52006-06-15 19:07:26 +00003556 FnName = "llvm.bswap.i64";
3557 else
3558 assert(0 && "Unknown integer type!");
3559 Function *F = M->getOrInsertFunction(FnName, I.getType(), I.getType(), NULL);
3560
3561 return new CallInst(F, V);
3562}
3563
3564
Chris Lattner7e708292002-06-25 16:13:24 +00003565Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003566 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00003567 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003568
Chris Lattnere87597f2004-10-16 18:11:37 +00003569 if (isa<UndefValue>(Op1))
3570 return ReplaceInstUsesWith(I, // X | undef -> -1
3571 ConstantIntegral::getAllOnesValue(I.getType()));
3572
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003573 // or X, X = X
3574 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00003575 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003576
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003577 // See if we can simplify any instructions used by the instruction whose sole
3578 // purpose is to compute bits we don't care about.
3579 uint64_t KnownZero, KnownOne;
Chris Lattner98509ef2006-03-25 21:58:26 +00003580 if (!isa<PackedType>(I.getType()) &&
3581 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003582 KnownZero, KnownOne))
3583 return &I;
3584
Chris Lattner3f5b8772002-05-06 16:14:14 +00003585 // or X, -1 == -1
Chris Lattnerad44ebf2003-07-23 18:29:44 +00003586 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00003587 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003588 // (X & C1) | C2 --> (X | C2) & (C1|C2)
3589 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattner6e4c6492005-05-09 04:58:36 +00003590 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0->getName());
3591 Op0->setName("");
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003592 InsertNewInstBefore(Or, I);
3593 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
3594 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00003595
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003596 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3597 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3598 std::string Op0Name = Op0->getName(); Op0->setName("");
3599 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
3600 InsertNewInstBefore(Or, I);
3601 return BinaryOperator::createXor(Or,
3602 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00003603 }
Chris Lattner2eefe512004-04-09 19:05:30 +00003604
3605 // Try to fold constant and into select arguments.
3606 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003607 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00003608 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00003609 if (isa<PHINode>(Op0))
3610 if (Instruction *NV = FoldOpIntoPhi(I))
3611 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00003612 }
3613
Chris Lattner4f637d42006-01-06 17:59:59 +00003614 Value *A = 0, *B = 0;
3615 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00003616
3617 if (match(Op0, m_And(m_Value(A), m_Value(B))))
3618 if (A == Op1 || B == Op1) // (A & ?) | A --> A
3619 return ReplaceInstUsesWith(I, Op1);
3620 if (match(Op1, m_And(m_Value(A), m_Value(B))))
3621 if (A == Op0 || B == Op0) // A | (A & ?) --> A
3622 return ReplaceInstUsesWith(I, Op0);
3623
Chris Lattner6423d4c2006-07-10 20:25:24 +00003624 // (A | B) | C and A | (B | C) -> bswap if possible.
3625 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Chris Lattnerafe91a52006-06-15 19:07:26 +00003626 if (match(Op0, m_Or(m_Value(), m_Value())) ||
Chris Lattner6423d4c2006-07-10 20:25:24 +00003627 match(Op1, m_Or(m_Value(), m_Value())) ||
3628 (match(Op0, m_Shift(m_Value(), m_Value())) &&
3629 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00003630 if (Instruction *BSwap = MatchBSwap(I))
3631 return BSwap;
3632 }
3633
Chris Lattner6e4c6492005-05-09 04:58:36 +00003634 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
3635 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattner3bedbd92006-02-07 07:27:52 +00003636 MaskedValueIsZero(Op1, C1->getZExtValue())) {
Chris Lattner6e4c6492005-05-09 04:58:36 +00003637 Instruction *NOr = BinaryOperator::createOr(A, Op1, Op0->getName());
3638 Op0->setName("");
3639 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
3640 }
3641
3642 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
3643 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattner3bedbd92006-02-07 07:27:52 +00003644 MaskedValueIsZero(Op0, C1->getZExtValue())) {
Chris Lattner6e4c6492005-05-09 04:58:36 +00003645 Instruction *NOr = BinaryOperator::createOr(A, Op0, Op1->getName());
3646 Op0->setName("");
3647 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
3648 }
3649
Chris Lattnere9bed7d2005-09-18 03:42:07 +00003650 // (A & C1)|(B & C2)
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003651 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattnere9bed7d2005-09-18 03:42:07 +00003652 match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
3653
3654 if (A == B) // (A & C1)|(A & C2) == A & (C1|C2)
3655 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
3656
3657
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00003658 // If we have: ((V + N) & C1) | (V & C2)
3659 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
3660 // replace with V+N.
3661 if (C1 == ConstantExpr::getNot(C2)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00003662 Value *V1 = 0, *V2 = 0;
Reid Spencerb83eb642006-10-20 07:07:24 +00003663 if ((C2->getZExtValue() & (C2->getZExtValue()+1)) == 0 && // C2 == 0+1+
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00003664 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
3665 // Add commutes, try both ways.
Chris Lattner3bedbd92006-02-07 07:27:52 +00003666 if (V1 == B && MaskedValueIsZero(V2, C2->getZExtValue()))
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00003667 return ReplaceInstUsesWith(I, A);
Chris Lattner3bedbd92006-02-07 07:27:52 +00003668 if (V2 == B && MaskedValueIsZero(V1, C2->getZExtValue()))
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00003669 return ReplaceInstUsesWith(I, A);
3670 }
3671 // Or commutes, try both ways.
Reid Spencerb83eb642006-10-20 07:07:24 +00003672 if ((C1->getZExtValue() & (C1->getZExtValue()+1)) == 0 &&
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00003673 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
3674 // Add commutes, try both ways.
Chris Lattner3bedbd92006-02-07 07:27:52 +00003675 if (V1 == A && MaskedValueIsZero(V2, C1->getZExtValue()))
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00003676 return ReplaceInstUsesWith(I, B);
Chris Lattner3bedbd92006-02-07 07:27:52 +00003677 if (V2 == A && MaskedValueIsZero(V1, C1->getZExtValue()))
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00003678 return ReplaceInstUsesWith(I, B);
Chris Lattnere9bed7d2005-09-18 03:42:07 +00003679 }
3680 }
3681 }
Chris Lattnere511b742006-11-14 07:46:50 +00003682
3683 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
3684 if (ShiftInst *SI1 = dyn_cast<ShiftInst>(Op1)) {
3685 if (ShiftInst *SI0 = dyn_cast<ShiftInst>(Op0))
3686 if (SI0->getOpcode() == SI1->getOpcode() &&
3687 SI0->getOperand(1) == SI1->getOperand(1) &&
3688 (SI0->hasOneUse() || SI1->hasOneUse())) {
3689 Instruction *NewOp =
3690 InsertNewInstBefore(BinaryOperator::createOr(SI0->getOperand(0),
3691 SI1->getOperand(0),
3692 SI0->getName()), I);
3693 return new ShiftInst(SI1->getOpcode(), NewOp, SI1->getOperand(1));
3694 }
3695 }
Chris Lattner67ca7682003-08-12 19:11:07 +00003696
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003697 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
3698 if (A == Op1) // ~A | A == -1
Misha Brukmanfd939082005-04-21 23:48:37 +00003699 return ReplaceInstUsesWith(I,
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003700 ConstantIntegral::getAllOnesValue(I.getType()));
3701 } else {
3702 A = 0;
3703 }
Chris Lattnerf4d4c872005-05-07 23:49:08 +00003704 // Note, A is still live here!
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003705 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
3706 if (Op0 == B)
Misha Brukmanfd939082005-04-21 23:48:37 +00003707 return ReplaceInstUsesWith(I,
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003708 ConstantIntegral::getAllOnesValue(I.getType()));
Chris Lattnera27231a2003-03-10 23:13:59 +00003709
Misha Brukmancb6267b2004-07-30 12:50:08 +00003710 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003711 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3712 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
3713 I.getName()+".demorgan"), I);
3714 return BinaryOperator::createNot(And);
3715 }
Chris Lattnera27231a2003-03-10 23:13:59 +00003716 }
Chris Lattnera2881962003-02-18 19:28:33 +00003717
Reid Spencere4d87aa2006-12-23 06:05:41 +00003718 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
3719 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
3720 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003721 return R;
3722
Chris Lattnerb4f40d22004-09-28 22:33:08 +00003723 Value *LHSVal, *RHSVal;
3724 ConstantInt *LHSCst, *RHSCst;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003725 ICmpInst::Predicate LHSCC, RHSCC;
3726 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3727 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3728 if (LHSVal == RHSVal && // Found (X icmp C1) | (X icmp C2)
3729 // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
3730 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3731 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3732 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3733 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE) {
Chris Lattnerb4f40d22004-09-28 22:33:08 +00003734 // Ensure that the larger constant is on the RHS.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003735 ICmpInst::Predicate GT = ICmpInst::isSignedPredicate(LHSCC) ?
3736 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
3737 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3738 ICmpInst *LHS = cast<ICmpInst>(Op0);
Chris Lattnerb4f40d22004-09-28 22:33:08 +00003739 if (cast<ConstantBool>(Cmp)->getValue()) {
3740 std::swap(LHS, RHS);
3741 std::swap(LHSCst, RHSCst);
3742 std::swap(LHSCC, RHSCC);
3743 }
3744
Reid Spencere4d87aa2006-12-23 06:05:41 +00003745 // At this point, we know we have have two icmp instructions
Chris Lattnerb4f40d22004-09-28 22:33:08 +00003746 // comparing a value against two constants and or'ing the result
3747 // together. Because of the above check, we know that we only have
Reid Spencere4d87aa2006-12-23 06:05:41 +00003748 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
3749 // FoldICmpLogical check above), that the two constants are not
Chris Lattnerb4f40d22004-09-28 22:33:08 +00003750 // equal.
3751 assert(LHSCst != RHSCst && "Compares not folded above?");
3752
3753 switch (LHSCC) {
3754 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003755 case ICmpInst::ICMP_EQ:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00003756 switch (RHSCC) {
3757 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003758 case ICmpInst::ICMP_EQ:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00003759 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
3760 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3761 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3762 LHSVal->getName()+".off");
3763 InsertNewInstBefore(Add, I);
Chris Lattnerb4f40d22004-09-28 22:33:08 +00003764 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003765 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattnerb4f40d22004-09-28 22:33:08 +00003766 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003767 break; // (X == 13 | X == 15) -> no change
3768 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
3769 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
Chris Lattner240d6f42005-04-19 06:04:18 +00003770 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003771 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
3772 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
3773 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
Chris Lattnerb4f40d22004-09-28 22:33:08 +00003774 return ReplaceInstUsesWith(I, RHS);
3775 }
3776 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003777 case ICmpInst::ICMP_NE:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00003778 switch (RHSCC) {
3779 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003780 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
3781 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
3782 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
Chris Lattnerb4f40d22004-09-28 22:33:08 +00003783 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003784 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
3785 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
3786 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Chris Lattner47811b72006-09-28 23:35:22 +00003787 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattnerb4f40d22004-09-28 22:33:08 +00003788 }
3789 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003790 case ICmpInst::ICMP_ULT:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00003791 switch (RHSCC) {
3792 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003793 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
Chris Lattnerb4f40d22004-09-28 22:33:08 +00003794 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003795 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) ->(X-13) u> 2
3796 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false,
3797 false, I);
3798 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
3799 break;
3800 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
3801 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
Chris Lattnerb4f40d22004-09-28 22:33:08 +00003802 return ReplaceInstUsesWith(I, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003803 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
3804 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00003805 }
3806 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003807 case ICmpInst::ICMP_SLT:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00003808 switch (RHSCC) {
3809 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003810 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
3811 break;
3812 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) ->(X-13) s> 2
3813 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true,
3814 false, I);
3815 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
3816 break;
3817 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
3818 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
3819 return ReplaceInstUsesWith(I, RHS);
3820 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
3821 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00003822 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003823 break;
3824 case ICmpInst::ICMP_UGT:
3825 switch (RHSCC) {
3826 default: assert(0 && "Unknown integer condition code!");
3827 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
3828 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
3829 return ReplaceInstUsesWith(I, LHS);
3830 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
3831 break;
3832 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
3833 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
3834 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
3835 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
3836 break;
3837 }
3838 break;
3839 case ICmpInst::ICMP_SGT:
3840 switch (RHSCC) {
3841 default: assert(0 && "Unknown integer condition code!");
3842 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
3843 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
3844 return ReplaceInstUsesWith(I, LHS);
3845 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
3846 break;
3847 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
3848 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
3849 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
3850 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
3851 break;
3852 }
3853 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00003854 }
3855 }
3856 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00003857
3858 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003859 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
Chris Lattner6fc205f2006-05-05 06:39:07 +00003860 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003861 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
3862 const Type *SrcTy = Op0C->getOperand(0)->getType();
3863 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
3864 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003865 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
3866 I.getType(), TD) &&
3867 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
3868 I.getType(), TD)) {
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003869 Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
3870 Op1C->getOperand(0),
3871 I.getName());
3872 InsertNewInstBefore(NewOp, I);
3873 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3874 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00003875 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00003876
Chris Lattnere9bed7d2005-09-18 03:42:07 +00003877
Chris Lattner7e708292002-06-25 16:13:24 +00003878 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00003879}
3880
Chris Lattnerc317d392004-02-16 01:20:27 +00003881// XorSelf - Implements: X ^ X --> 0
3882struct XorSelf {
3883 Value *RHS;
3884 XorSelf(Value *rhs) : RHS(rhs) {}
3885 bool shouldApply(Value *LHS) const { return LHS == RHS; }
3886 Instruction *apply(BinaryOperator &Xor) const {
3887 return &Xor;
3888 }
3889};
Chris Lattner3f5b8772002-05-06 16:14:14 +00003890
3891
Chris Lattner7e708292002-06-25 16:13:24 +00003892Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003893 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00003894 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003895
Chris Lattnere87597f2004-10-16 18:11:37 +00003896 if (isa<UndefValue>(Op1))
3897 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
3898
Chris Lattnerc317d392004-02-16 01:20:27 +00003899 // xor X, X = 0, even if X is nested in a sequence of Xor's.
3900 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
3901 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattner233f7dc2002-08-12 21:17:25 +00003902 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00003903 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003904
3905 // See if we can simplify any instructions used by the instruction whose sole
3906 // purpose is to compute bits we don't care about.
3907 uint64_t KnownZero, KnownOne;
Chris Lattner98509ef2006-03-25 21:58:26 +00003908 if (!isa<PackedType>(I.getType()) &&
3909 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003910 KnownZero, KnownOne))
3911 return &I;
Chris Lattner3f5b8772002-05-06 16:14:14 +00003912
Chris Lattnereca0c5c2003-07-23 21:37:07 +00003913 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003914 // xor (icmp A, B), true = not (icmp A, B) = !icmp A, B
3915 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
3916 if (RHS == ConstantBool::getTrue() && ICI->hasOneUse())
3917 return new ICmpInst(ICI->getInversePredicate(),
3918 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00003919
Reid Spencere4d87aa2006-12-23 06:05:41 +00003920 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00003921 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00003922 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
3923 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattner48595f12004-06-10 02:07:29 +00003924 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
3925 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattner7c4049c2004-01-12 19:35:11 +00003926 ConstantInt::get(I.getType(), 1));
Chris Lattner48595f12004-06-10 02:07:29 +00003927 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00003928 }
Chris Lattner5b62aa72004-06-18 06:07:51 +00003929
3930 // ~(~X & Y) --> (X | ~Y)
3931 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
3932 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
3933 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
3934 Instruction *NotY =
Misha Brukmanfd939082005-04-21 23:48:37 +00003935 BinaryOperator::createNot(Op0I->getOperand(1),
Chris Lattner5b62aa72004-06-18 06:07:51 +00003936 Op0I->getOperand(1)->getName()+".not");
3937 InsertNewInstBefore(NotY, I);
3938 return BinaryOperator::createOr(Op0NotVal, NotY);
3939 }
3940 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003941
Chris Lattnereca0c5c2003-07-23 21:37:07 +00003942 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003943 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00003944 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00003945 if (RHS->isAllOnesValue()) {
Chris Lattner48595f12004-06-10 02:07:29 +00003946 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
3947 return BinaryOperator::createSub(
3948 ConstantExpr::getSub(NegOp0CI,
Chris Lattner7c4049c2004-01-12 19:35:11 +00003949 ConstantInt::get(I.getType(), 1)),
Chris Lattner689d24b2003-11-04 23:37:10 +00003950 Op0I->getOperand(0));
Chris Lattner7c4049c2004-01-12 19:35:11 +00003951 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00003952 } else if (Op0I->getOpcode() == Instruction::Or) {
3953 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
3954 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getZExtValue())) {
3955 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
3956 // Anything in both C1 and C2 is known to be zero, remove it from
3957 // NewRHS.
3958 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
3959 NewRHS = ConstantExpr::getAnd(NewRHS,
3960 ConstantExpr::getNot(CommonBits));
3961 WorkList.push_back(Op0I);
3962 I.setOperand(0, Op0I->getOperand(0));
3963 I.setOperand(1, NewRHS);
3964 return &I;
3965 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00003966 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00003967 }
Chris Lattner2eefe512004-04-09 19:05:30 +00003968
3969 // Try to fold constant and into select arguments.
3970 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003971 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00003972 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00003973 if (isa<PHINode>(Op0))
3974 if (Instruction *NV = FoldOpIntoPhi(I))
3975 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00003976 }
3977
Chris Lattner8d969642003-03-10 23:06:50 +00003978 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00003979 if (X == Op1)
3980 return ReplaceInstUsesWith(I,
3981 ConstantIntegral::getAllOnesValue(I.getType()));
3982
Chris Lattner8d969642003-03-10 23:06:50 +00003983 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00003984 if (X == Op0)
3985 return ReplaceInstUsesWith(I,
3986 ConstantIntegral::getAllOnesValue(I.getType()));
3987
Chris Lattner64daab52006-04-01 08:03:55 +00003988 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
Chris Lattner26ca7e12004-02-16 03:54:20 +00003989 if (Op1I->getOpcode() == Instruction::Or) {
Chris Lattnercb40a372003-03-10 18:24:17 +00003990 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00003991 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00003992 I.swapOperands();
3993 std::swap(Op0, Op1);
3994 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00003995 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00003996 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00003997 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00003998 } else if (Op1I->getOpcode() == Instruction::Xor) {
3999 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
4000 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
4001 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
4002 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
Chris Lattner64daab52006-04-01 08:03:55 +00004003 } else if (Op1I->getOpcode() == Instruction::And && Op1I->hasOneUse()) {
4004 if (Op1I->getOperand(0) == Op0) // A^(A&B) -> A^(B&A)
4005 Op1I->swapOperands();
4006 if (Op0 == Op1I->getOperand(1)) { // A^(B&A) -> (B&A)^A
4007 I.swapOperands(); // Simplified below.
4008 std::swap(Op0, Op1);
4009 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00004010 }
Chris Lattnercb40a372003-03-10 18:24:17 +00004011
Chris Lattner64daab52006-04-01 08:03:55 +00004012 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
Chris Lattnerfd059242003-10-15 16:48:29 +00004013 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
Chris Lattnercb40a372003-03-10 18:24:17 +00004014 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00004015 Op0I->swapOperands();
Chris Lattner4f98c562003-03-10 21:43:22 +00004016 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattner64daab52006-04-01 08:03:55 +00004017 Instruction *NotB = BinaryOperator::createNot(Op1, "tmp");
4018 InsertNewInstBefore(NotB, I);
Chris Lattner48595f12004-06-10 02:07:29 +00004019 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
Chris Lattnercb40a372003-03-10 18:24:17 +00004020 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00004021 } else if (Op0I->getOpcode() == Instruction::Xor) {
4022 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
4023 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
4024 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
4025 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner64daab52006-04-01 08:03:55 +00004026 } else if (Op0I->getOpcode() == Instruction::And && Op0I->hasOneUse()) {
4027 if (Op0I->getOperand(0) == Op1) // (A&B)^A -> (B&A)^A
4028 Op0I->swapOperands();
Chris Lattnerae1ab392006-04-01 22:05:01 +00004029 if (Op0I->getOperand(1) == Op1 && // (B&A)^A == ~B & A
4030 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner64daab52006-04-01 08:03:55 +00004031 Instruction *N = BinaryOperator::createNot(Op0I->getOperand(0), "tmp");
4032 InsertNewInstBefore(N, I);
4033 return BinaryOperator::createAnd(N, Op1);
4034 }
Chris Lattnercb40a372003-03-10 18:24:17 +00004035 }
4036
Reid Spencere4d87aa2006-12-23 06:05:41 +00004037 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4038 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4039 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004040 return R;
4041
Chris Lattner6fc205f2006-05-05 06:39:07 +00004042 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004043 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
Chris Lattner6fc205f2006-05-05 06:39:07 +00004044 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004045 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4046 const Type *SrcTy = Op0C->getOperand(0)->getType();
4047 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
4048 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004049 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4050 I.getType(), TD) &&
4051 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4052 I.getType(), TD)) {
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004053 Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
4054 Op1C->getOperand(0),
4055 I.getName());
4056 InsertNewInstBefore(NewOp, I);
4057 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4058 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004059 }
Chris Lattnere511b742006-11-14 07:46:50 +00004060
4061 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
4062 if (ShiftInst *SI1 = dyn_cast<ShiftInst>(Op1)) {
4063 if (ShiftInst *SI0 = dyn_cast<ShiftInst>(Op0))
4064 if (SI0->getOpcode() == SI1->getOpcode() &&
4065 SI0->getOperand(1) == SI1->getOperand(1) &&
4066 (SI0->hasOneUse() || SI1->hasOneUse())) {
4067 Instruction *NewOp =
4068 InsertNewInstBefore(BinaryOperator::createXor(SI0->getOperand(0),
4069 SI1->getOperand(0),
4070 SI0->getName()), I);
4071 return new ShiftInst(SI1->getOpcode(), NewOp, SI1->getOperand(1));
4072 }
4073 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004074
Chris Lattner7e708292002-06-25 16:13:24 +00004075 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004076}
4077
Chris Lattnera96879a2004-09-29 17:40:11 +00004078static bool isPositive(ConstantInt *C) {
Reid Spencerb83eb642006-10-20 07:07:24 +00004079 return C->getSExtValue() >= 0;
Chris Lattnera96879a2004-09-29 17:40:11 +00004080}
4081
4082/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4083/// overflowed for this type.
4084static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
4085 ConstantInt *In2) {
4086 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
4087
Reid Spencerc5b206b2006-12-31 05:48:39 +00004088 return cast<ConstantInt>(Result)->getZExtValue() <
4089 cast<ConstantInt>(In1)->getZExtValue();
Chris Lattnera96879a2004-09-29 17:40:11 +00004090}
4091
Chris Lattner574da9b2005-01-13 20:14:25 +00004092/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4093/// code necessary to compute the offset from the base pointer (without adding
4094/// in the base pointer). Return the result as a signed integer of intptr size.
4095static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4096 TargetData &TD = IC.getTargetData();
4097 gep_type_iterator GTI = gep_type_begin(GEP);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004098 const Type *IntPtrTy = TD.getIntPtrType();
4099 Value *Result = Constant::getNullValue(IntPtrTy);
Chris Lattner574da9b2005-01-13 20:14:25 +00004100
4101 // Build a mask for high order bits.
Chris Lattner1a074fc2006-02-07 07:00:41 +00004102 uint64_t PtrSizeMask = ~0ULL >> (64-TD.getPointerSize()*8);
Chris Lattner574da9b2005-01-13 20:14:25 +00004103
Chris Lattner574da9b2005-01-13 20:14:25 +00004104 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
4105 Value *Op = GEP->getOperand(i);
Chris Lattner0b84c802005-01-13 23:26:48 +00004106 uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004107 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
Chris Lattner574da9b2005-01-13 20:14:25 +00004108 if (Constant *OpC = dyn_cast<Constant>(Op)) {
4109 if (!OpC->isNullValue()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00004110 OpC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
Chris Lattner574da9b2005-01-13 20:14:25 +00004111 Scale = ConstantExpr::getMul(OpC, Scale);
4112 if (Constant *RC = dyn_cast<Constant>(Result))
4113 Result = ConstantExpr::getAdd(RC, Scale);
4114 else {
4115 // Emit an add instruction.
4116 Result = IC.InsertNewInstBefore(
4117 BinaryOperator::createAdd(Result, Scale,
4118 GEP->getName()+".offs"), I);
4119 }
4120 }
4121 } else {
Chris Lattner6f7f02f2005-01-14 17:17:59 +00004122 // Convert to correct type.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004123 Op = IC.InsertNewInstBefore(CastInst::createSExtOrBitCast(Op, IntPtrTy,
Chris Lattner6f7f02f2005-01-14 17:17:59 +00004124 Op->getName()+".c"), I);
4125 if (Size != 1)
Chris Lattner5bdf04c2005-01-13 20:40:58 +00004126 // We'll let instcombine(mul) convert this to a shl if possible.
4127 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
4128 GEP->getName()+".idx"), I);
Chris Lattner574da9b2005-01-13 20:14:25 +00004129
4130 // Emit an add instruction.
Chris Lattner5bdf04c2005-01-13 20:40:58 +00004131 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
Chris Lattner574da9b2005-01-13 20:14:25 +00004132 GEP->getName()+".offs"), I);
4133 }
4134 }
4135 return Result;
4136}
4137
Reid Spencere4d87aa2006-12-23 06:05:41 +00004138/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner574da9b2005-01-13 20:14:25 +00004139/// else. At this point we know that the GEP is on the LHS of the comparison.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004140Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
4141 ICmpInst::Predicate Cond,
4142 Instruction &I) {
Chris Lattner574da9b2005-01-13 20:14:25 +00004143 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattnere9d782b2005-01-13 22:25:21 +00004144
4145 if (CastInst *CI = dyn_cast<CastInst>(RHS))
4146 if (isa<PointerType>(CI->getOperand(0)->getType()))
4147 RHS = CI->getOperand(0);
4148
Chris Lattner574da9b2005-01-13 20:14:25 +00004149 Value *PtrBase = GEPLHS->getOperand(0);
4150 if (PtrBase == RHS) {
4151 // As an optimization, we don't actually have to compute the actual value of
Reid Spencere4d87aa2006-12-23 06:05:41 +00004152 // OFFSET if this is a icmp_eq or icmp_ne comparison, just return whether
4153 // each index is zero or not.
4154 if (Cond == ICmpInst::ICMP_EQ || Cond == ICmpInst::ICMP_NE) {
Chris Lattnere9d782b2005-01-13 22:25:21 +00004155 Instruction *InVal = 0;
Chris Lattnerad5fec12005-01-28 19:32:01 +00004156 gep_type_iterator GTI = gep_type_begin(GEPLHS);
4157 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattnere9d782b2005-01-13 22:25:21 +00004158 bool EmitIt = true;
4159 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
4160 if (isa<UndefValue>(C)) // undef index -> undef.
4161 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
4162 if (C->isNullValue())
4163 EmitIt = false;
Chris Lattnerad5fec12005-01-28 19:32:01 +00004164 else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
4165 EmitIt = false; // This is indexing into a zero sized array?
Misha Brukmanfd939082005-04-21 23:48:37 +00004166 } else if (isa<ConstantInt>(C))
Chris Lattnere9d782b2005-01-13 22:25:21 +00004167 return ReplaceInstUsesWith(I, // No comparison is needed here.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004168 ConstantBool::get(Cond == ICmpInst::ICMP_NE));
Chris Lattnere9d782b2005-01-13 22:25:21 +00004169 }
4170
4171 if (EmitIt) {
Misha Brukmanfd939082005-04-21 23:48:37 +00004172 Instruction *Comp =
Reid Spencere4d87aa2006-12-23 06:05:41 +00004173 new ICmpInst(Cond, GEPLHS->getOperand(i),
Chris Lattnere9d782b2005-01-13 22:25:21 +00004174 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
4175 if (InVal == 0)
4176 InVal = Comp;
4177 else {
4178 InVal = InsertNewInstBefore(InVal, I);
4179 InsertNewInstBefore(Comp, I);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004180 if (Cond == ICmpInst::ICMP_NE) // True if any are unequal
Chris Lattnere9d782b2005-01-13 22:25:21 +00004181 InVal = BinaryOperator::createOr(InVal, Comp);
4182 else // True if all are equal
4183 InVal = BinaryOperator::createAnd(InVal, Comp);
4184 }
4185 }
4186 }
4187
4188 if (InVal)
4189 return InVal;
4190 else
Reid Spencere4d87aa2006-12-23 06:05:41 +00004191 // No comparison is needed here, all indexes = 0
4192 ReplaceInstUsesWith(I, ConstantBool::get(Cond == ICmpInst::ICMP_EQ));
Chris Lattnere9d782b2005-01-13 22:25:21 +00004193 }
Chris Lattner574da9b2005-01-13 20:14:25 +00004194
Reid Spencere4d87aa2006-12-23 06:05:41 +00004195 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00004196 // the result to fold to a constant!
4197 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
4198 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
4199 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004200 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
4201 Constant::getNullValue(Offset->getType()));
Chris Lattner574da9b2005-01-13 20:14:25 +00004202 }
4203 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00004204 // If the base pointers are different, but the indices are the same, just
4205 // compare the base pointer.
4206 if (PtrBase != GEPRHS->getOperand(0)) {
4207 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00004208 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00004209 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00004210 if (IndicesTheSame)
4211 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4212 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4213 IndicesTheSame = false;
4214 break;
4215 }
4216
4217 // If all indices are the same, just compare the base pointers.
4218 if (IndicesTheSame)
Reid Spencere4d87aa2006-12-23 06:05:41 +00004219 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
4220 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera70b66d2005-04-25 20:17:30 +00004221
4222 // Otherwise, the base pointers are different and the indices are
4223 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00004224 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00004225 }
Chris Lattner574da9b2005-01-13 20:14:25 +00004226
Chris Lattnere9d782b2005-01-13 22:25:21 +00004227 // If one of the GEPs has all zero indices, recurse.
4228 bool AllZeros = true;
4229 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4230 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4231 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4232 AllZeros = false;
4233 break;
4234 }
4235 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00004236 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
4237 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00004238
4239 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00004240 AllZeros = true;
4241 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4242 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4243 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4244 AllZeros = false;
4245 break;
4246 }
4247 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00004248 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattnere9d782b2005-01-13 22:25:21 +00004249
Chris Lattner4401c9c2005-01-14 00:20:05 +00004250 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4251 // If the GEPs only differ by one index, compare it.
4252 unsigned NumDifferences = 0; // Keep track of # differences.
4253 unsigned DiffOperand = 0; // The operand that differs.
4254 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4255 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00004256 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4257 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00004258 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00004259 NumDifferences = 2;
4260 break;
4261 } else {
4262 if (NumDifferences++) break;
4263 DiffOperand = i;
4264 }
4265 }
4266
4267 if (NumDifferences == 0) // SAME GEP?
4268 return ReplaceInstUsesWith(I, // No comparison is needed here.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004269 ConstantBool::get(Cond == ICmpInst::ICMP_EQ));
Chris Lattner4401c9c2005-01-14 00:20:05 +00004270 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00004271 Value *LHSV = GEPLHS->getOperand(DiffOperand);
4272 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004273 // Make sure we do a signed comparison here.
4274 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00004275 }
4276 }
4277
Reid Spencere4d87aa2006-12-23 06:05:41 +00004278 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00004279 // the result to fold to a constant!
4280 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4281 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4282 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
4283 Value *L = EmitGEPOffset(GEPLHS, I, *this);
4284 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004285 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner574da9b2005-01-13 20:14:25 +00004286 }
4287 }
4288 return 0;
4289}
4290
Reid Spencere4d87aa2006-12-23 06:05:41 +00004291Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
4292 bool Changed = SimplifyCompare(I);
Chris Lattner8b170942002-08-09 23:47:40 +00004293 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004294
Reid Spencere4d87aa2006-12-23 06:05:41 +00004295 // fcmp pred X, X
Chris Lattner8b170942002-08-09 23:47:40 +00004296 if (Op0 == Op1)
4297 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
Chris Lattner53a5b572002-05-09 20:11:54 +00004298
Reid Spencere4d87aa2006-12-23 06:05:41 +00004299 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Chris Lattnere87597f2004-10-16 18:11:37 +00004300 return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
4301
Reid Spencere4d87aa2006-12-23 06:05:41 +00004302 // Handle fcmp with constant RHS
4303 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4304 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4305 switch (LHSI->getOpcode()) {
4306 case Instruction::PHI:
4307 if (Instruction *NV = FoldOpIntoPhi(I))
4308 return NV;
4309 break;
4310 case Instruction::Select:
4311 // If either operand of the select is a constant, we can fold the
4312 // comparison into the select arms, which will cause one to be
4313 // constant folded and the select turned into a bitwise or.
4314 Value *Op1 = 0, *Op2 = 0;
4315 if (LHSI->hasOneUse()) {
4316 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4317 // Fold the known value into the constant operand.
4318 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4319 // Insert a new FCmp of the other select operand.
4320 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4321 LHSI->getOperand(2), RHSC,
4322 I.getName()), I);
4323 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4324 // Fold the known value into the constant operand.
4325 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4326 // Insert a new FCmp of the other select operand.
4327 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4328 LHSI->getOperand(1), RHSC,
4329 I.getName()), I);
4330 }
4331 }
4332
4333 if (Op1)
4334 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4335 break;
4336 }
4337 }
4338
4339 return Changed ? &I : 0;
4340}
4341
4342Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
4343 bool Changed = SimplifyCompare(I);
4344 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4345 const Type *Ty = Op0->getType();
4346
4347 // icmp X, X
4348 if (Op0 == Op1)
4349 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
4350
4351 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
4352 return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
4353
4354 // icmp of GlobalValues can never equal each other as long as they aren't
4355 // external weak linkage type.
4356 if (GlobalValue *GV0 = dyn_cast<GlobalValue>(Op0))
4357 if (GlobalValue *GV1 = dyn_cast<GlobalValue>(Op1))
4358 if (!GV0->hasExternalWeakLinkage() || !GV1->hasExternalWeakLinkage())
4359 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
4360
4361 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner711b3402004-11-14 07:33:16 +00004362 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanfd939082005-04-21 23:48:37 +00004363 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
4364 isa<ConstantPointerNull>(Op0)) &&
4365 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner711b3402004-11-14 07:33:16 +00004366 isa<ConstantPointerNull>(Op1)))
Chris Lattner8b170942002-08-09 23:47:40 +00004367 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
4368
Reid Spencere4d87aa2006-12-23 06:05:41 +00004369 // icmp's with boolean values can always be turned into bitwise operations
Chris Lattner8b170942002-08-09 23:47:40 +00004370 if (Ty == Type::BoolTy) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00004371 switch (I.getPredicate()) {
4372 default: assert(0 && "Invalid icmp instruction!");
4373 case ICmpInst::ICMP_EQ: { // icmp eq bool %A, %B -> ~(A^B)
Chris Lattner48595f12004-06-10 02:07:29 +00004374 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner8b170942002-08-09 23:47:40 +00004375 InsertNewInstBefore(Xor, I);
Chris Lattnerde90b762003-11-03 04:25:02 +00004376 return BinaryOperator::createNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00004377 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004378 case ICmpInst::ICMP_NE: // icmp eq bool %A, %B -> A^B
Chris Lattner5dbef222004-08-11 00:50:51 +00004379 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00004380
Reid Spencere4d87aa2006-12-23 06:05:41 +00004381 case ICmpInst::ICMP_UGT:
4382 case ICmpInst::ICMP_SGT:
4383 std::swap(Op0, Op1); // Change icmp gt -> icmp lt
Chris Lattner5dbef222004-08-11 00:50:51 +00004384 // FALL THROUGH
Reid Spencere4d87aa2006-12-23 06:05:41 +00004385 case ICmpInst::ICMP_ULT:
4386 case ICmpInst::ICMP_SLT: { // icmp lt bool A, B -> ~X & Y
Chris Lattner5dbef222004-08-11 00:50:51 +00004387 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4388 InsertNewInstBefore(Not, I);
4389 return BinaryOperator::createAnd(Not, Op1);
4390 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004391 case ICmpInst::ICMP_UGE:
4392 case ICmpInst::ICMP_SGE:
4393 std::swap(Op0, Op1); // Change icmp ge -> icmp le
Chris Lattner5dbef222004-08-11 00:50:51 +00004394 // FALL THROUGH
Reid Spencere4d87aa2006-12-23 06:05:41 +00004395 case ICmpInst::ICMP_ULE:
4396 case ICmpInst::ICMP_SLE: { // icmp le bool %A, %B -> ~A | B
Chris Lattner5dbef222004-08-11 00:50:51 +00004397 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4398 InsertNewInstBefore(Not, I);
4399 return BinaryOperator::createOr(Not, Op1);
4400 }
4401 }
Chris Lattner8b170942002-08-09 23:47:40 +00004402 }
4403
Chris Lattner2be51ae2004-06-09 04:24:29 +00004404 // See if we are doing a comparison between a constant and an instruction that
4405 // can be folded into the comparison.
Chris Lattner8b170942002-08-09 23:47:40 +00004406 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00004407 switch (I.getPredicate()) {
4408 default: break;
4409 case ICmpInst::ICMP_ULT: // A <u MIN -> FALSE
4410 if (CI->isMinValue(false))
Chris Lattner47811b72006-09-28 23:35:22 +00004411 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004412 if (CI->isMaxValue(false)) // A <u MAX -> A != MAX
4413 return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
4414 if (isMinValuePlusOne(CI,false)) // A <u MIN+1 -> A == MIN
4415 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4416 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00004417
Reid Spencere4d87aa2006-12-23 06:05:41 +00004418 case ICmpInst::ICMP_SLT:
4419 if (CI->isMinValue(true)) // A <s MIN -> FALSE
Chris Lattner47811b72006-09-28 23:35:22 +00004420 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004421 if (CI->isMaxValue(true)) // A <s MAX -> A != MAX
4422 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4423 if (isMinValuePlusOne(CI,true)) // A <s MIN+1 -> A == MIN
4424 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4425 break;
4426
4427 case ICmpInst::ICMP_UGT:
4428 if (CI->isMaxValue(false)) // A >u MAX -> FALSE
4429 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4430 if (CI->isMinValue(false)) // A >u MIN -> A != MIN
4431 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4432 if (isMaxValueMinusOne(CI, false)) // A >u MAX-1 -> A == MAX
4433 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4434 break;
4435
4436 case ICmpInst::ICMP_SGT:
4437 if (CI->isMaxValue(true)) // A >s MAX -> FALSE
4438 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4439 if (CI->isMinValue(true)) // A >s MIN -> A != MIN
4440 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4441 if (isMaxValueMinusOne(CI, true)) // A >s MAX-1 -> A == MAX
4442 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4443 break;
4444
4445 case ICmpInst::ICMP_ULE:
4446 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Chris Lattner47811b72006-09-28 23:35:22 +00004447 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004448 if (CI->isMinValue(false)) // A <=u MIN -> A == MIN
4449 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4450 if (isMaxValueMinusOne(CI,false)) // A <=u MAX-1 -> A != MAX
4451 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4452 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00004453
Reid Spencere4d87aa2006-12-23 06:05:41 +00004454 case ICmpInst::ICMP_SLE:
4455 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
4456 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4457 if (CI->isMinValue(true)) // A <=s MIN -> A == MIN
4458 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4459 if (isMaxValueMinusOne(CI,true)) // A <=s MAX-1 -> A != MAX
4460 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4461 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00004462
Reid Spencere4d87aa2006-12-23 06:05:41 +00004463 case ICmpInst::ICMP_UGE:
4464 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
4465 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4466 if (CI->isMaxValue(false)) // A >=u MAX -> A == MAX
4467 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4468 if (isMinValuePlusOne(CI,false)) // A >=u MIN-1 -> A != MIN
4469 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4470 break;
4471
4472 case ICmpInst::ICMP_SGE:
4473 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
4474 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4475 if (CI->isMaxValue(true)) // A >=s MAX -> A == MAX
4476 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4477 if (isMinValuePlusOne(CI,true)) // A >=s MIN-1 -> A != MIN
4478 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4479 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00004480 }
4481
Reid Spencere4d87aa2006-12-23 06:05:41 +00004482 // If we still have a icmp le or icmp ge instruction, turn it into the
4483 // appropriate icmp lt or icmp gt instruction. Since the border cases have
Chris Lattnera96879a2004-09-29 17:40:11 +00004484 // already been handled above, this requires little checking.
4485 //
Reid Spencere4d87aa2006-12-23 06:05:41 +00004486 if (I.getPredicate() == ICmpInst::ICMP_ULE)
4487 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
4488 if (I.getPredicate() == ICmpInst::ICMP_SLE)
4489 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
4490 if (I.getPredicate() == ICmpInst::ICMP_UGE)
4491 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
4492 if (I.getPredicate() == ICmpInst::ICMP_SGE)
4493 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00004494
4495 // See if we can fold the comparison based on bits known to be zero or one
4496 // in the input.
4497 uint64_t KnownZero, KnownOne;
4498 if (SimplifyDemandedBits(Op0, Ty->getIntegralTypeMask(),
4499 KnownZero, KnownOne, 0))
4500 return &I;
4501
4502 // Given the known and unknown bits, compute a range that the LHS could be
4503 // in.
4504 if (KnownOne | KnownZero) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00004505 // Compute the Min, Max and RHS values based on the known bits. For the
4506 // EQ and NE we use unsigned values.
Reid Spencerb3307b22006-12-23 19:17:57 +00004507 uint64_t UMin = 0, UMax = 0, URHSVal = 0;
4508 int64_t SMin = 0, SMax = 0, SRHSVal = 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004509 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
4510 SRHSVal = CI->getSExtValue();
4511 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, SMin,
4512 SMax);
4513 } else {
4514 URHSVal = CI->getZExtValue();
4515 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, UMin,
4516 UMax);
4517 }
4518 switch (I.getPredicate()) { // LE/GE have been folded already.
4519 default: assert(0 && "Unknown icmp opcode!");
4520 case ICmpInst::ICMP_EQ:
4521 if (UMax < URHSVal || UMin > URHSVal)
4522 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4523 break;
4524 case ICmpInst::ICMP_NE:
4525 if (UMax < URHSVal || UMin > URHSVal)
4526 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4527 break;
4528 case ICmpInst::ICMP_ULT:
4529 if (UMax < URHSVal)
4530 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4531 if (UMin > URHSVal)
4532 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4533 break;
4534 case ICmpInst::ICMP_UGT:
4535 if (UMin > URHSVal)
4536 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4537 if (UMax < URHSVal)
4538 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4539 break;
4540 case ICmpInst::ICMP_SLT:
4541 if (SMax < SRHSVal)
4542 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4543 if (SMin > SRHSVal)
4544 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4545 break;
4546 case ICmpInst::ICMP_SGT:
4547 if (SMin > SRHSVal)
4548 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4549 if (SMax < SRHSVal)
4550 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4551 break;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00004552 }
4553 }
4554
Reid Spencere4d87aa2006-12-23 06:05:41 +00004555 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer1628cec2006-10-26 06:15:43 +00004556 // instruction, see if that instruction also has constants so that the
Reid Spencere4d87aa2006-12-23 06:05:41 +00004557 // instruction can be folded into the icmp
Chris Lattner3c6a0d42004-05-25 06:32:08 +00004558 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner648e3bc2004-09-23 21:52:49 +00004559 switch (LHSI->getOpcode()) {
4560 case Instruction::And:
4561 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
4562 LHSI->getOperand(0)->hasOneUse()) {
Chris Lattnere695a3b2006-09-18 05:27:43 +00004563 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
4564
Reid Spencere4d87aa2006-12-23 06:05:41 +00004565 // If the LHS is an AND of a truncating cast, we can widen the
Chris Lattnere695a3b2006-09-18 05:27:43 +00004566 // and/compare to be the input width without changing the value
4567 // produced, eliminating a cast.
4568 if (CastInst *Cast = dyn_cast<CastInst>(LHSI->getOperand(0))) {
4569 // We can do this transformation if either the AND constant does not
4570 // have its sign bit set or if it is an equality comparison.
4571 // Extending a relational comparison when we're checking the sign
4572 // bit would not work.
Reid Spencer3da59db2006-11-27 01:05:10 +00004573 if (Cast->hasOneUse() && isa<TruncInst>(Cast) &&
Chris Lattnere695a3b2006-09-18 05:27:43 +00004574 (I.isEquality() ||
4575 (AndCST->getZExtValue() == (uint64_t)AndCST->getSExtValue()) &&
4576 (CI->getZExtValue() == (uint64_t)CI->getSExtValue()))) {
4577 ConstantInt *NewCST;
4578 ConstantInt *NewCI;
Reid Spencerc5b206b2006-12-31 05:48:39 +00004579 NewCST = ConstantInt::get(Cast->getOperand(0)->getType(),
4580 AndCST->getZExtValue());
4581 NewCI = ConstantInt::get(Cast->getOperand(0)->getType(),
4582 CI->getZExtValue());
Chris Lattnere695a3b2006-09-18 05:27:43 +00004583 Instruction *NewAnd =
4584 BinaryOperator::createAnd(Cast->getOperand(0), NewCST,
4585 LHSI->getName());
4586 InsertNewInstBefore(NewAnd, I);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004587 return new ICmpInst(I.getPredicate(), NewAnd, NewCI);
Chris Lattnere695a3b2006-09-18 05:27:43 +00004588 }
4589 }
4590
Chris Lattner648e3bc2004-09-23 21:52:49 +00004591 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
4592 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
4593 // happens a LOT in code produced by the C front-end, for bitfield
4594 // access.
4595 ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00004596
4597 // Check to see if there is a noop-cast between the shift and the and.
4598 if (!Shift) {
4599 if (CastInst *CI = dyn_cast<CastInst>(LHSI->getOperand(0)))
Reid Spencerc55b2432006-12-13 18:21:21 +00004600 if (CI->getOpcode() == Instruction::BitCast)
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00004601 Shift = dyn_cast<ShiftInst>(CI->getOperand(0));
4602 }
Chris Lattner65b72ba2006-09-18 04:22:48 +00004603
Reid Spencerb83eb642006-10-20 07:07:24 +00004604 ConstantInt *ShAmt;
4605 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00004606 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
4607 const Type *AndTy = AndCST->getType(); // Type of the and.
Misha Brukmanfd939082005-04-21 23:48:37 +00004608
Chris Lattner648e3bc2004-09-23 21:52:49 +00004609 // We can fold this as long as we can't shift unknown bits
4610 // into the mask. This can only happen with signed shift
4611 // rights, as they sign-extend.
4612 if (ShAmt) {
Chris Lattner65b72ba2006-09-18 04:22:48 +00004613 bool CanFold = Shift->isLogicalShift();
Chris Lattner648e3bc2004-09-23 21:52:49 +00004614 if (!CanFold) {
4615 // To test for the bad case of the signed shr, see if any
4616 // of the bits shifted in could be tested after the mask.
Reid Spencerb83eb642006-10-20 07:07:24 +00004617 int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getZExtValue();
Chris Lattnerd7e31cf2005-06-17 01:29:28 +00004618 if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
4619
Reid Spencerc5b206b2006-12-31 05:48:39 +00004620 Constant *OShAmt = ConstantInt::get(Type::Int8Ty, ShAmtVal);
Misha Brukmanfd939082005-04-21 23:48:37 +00004621 Constant *ShVal =
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00004622 ConstantExpr::getShl(ConstantInt::getAllOnesValue(AndTy),
4623 OShAmt);
Chris Lattner648e3bc2004-09-23 21:52:49 +00004624 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
4625 CanFold = true;
4626 }
Misha Brukmanfd939082005-04-21 23:48:37 +00004627
Chris Lattner648e3bc2004-09-23 21:52:49 +00004628 if (CanFold) {
Chris Lattner0cba71b2004-09-28 17:54:07 +00004629 Constant *NewCst;
4630 if (Shift->getOpcode() == Instruction::Shl)
Reid Spencer3822ff52006-11-08 06:47:33 +00004631 NewCst = ConstantExpr::getLShr(CI, ShAmt);
Chris Lattner0cba71b2004-09-28 17:54:07 +00004632 else
4633 NewCst = ConstantExpr::getShl(CI, ShAmt);
Chris Lattner83c4ec02004-09-27 19:29:18 +00004634
Chris Lattner648e3bc2004-09-23 21:52:49 +00004635 // Check to see if we are shifting out any of the bits being
4636 // compared.
4637 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
4638 // If we shifted bits out, the fold is not going to work out.
4639 // As a special case, check to see if this means that the
4640 // result is always true or false now.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004641 if (I.getPredicate() == ICmpInst::ICMP_EQ)
Chris Lattner47811b72006-09-28 23:35:22 +00004642 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004643 if (I.getPredicate() == ICmpInst::ICMP_NE)
Chris Lattner47811b72006-09-28 23:35:22 +00004644 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattner648e3bc2004-09-23 21:52:49 +00004645 } else {
4646 I.setOperand(1, NewCst);
Chris Lattner0cba71b2004-09-28 17:54:07 +00004647 Constant *NewAndCST;
4648 if (Shift->getOpcode() == Instruction::Shl)
Reid Spencer3822ff52006-11-08 06:47:33 +00004649 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
Chris Lattner0cba71b2004-09-28 17:54:07 +00004650 else
4651 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
4652 LHSI->setOperand(1, NewAndCST);
Reid Spencer8c5a53a2007-01-04 05:23:51 +00004653 LHSI->setOperand(0, Shift->getOperand(0));
Chris Lattner648e3bc2004-09-23 21:52:49 +00004654 WorkList.push_back(Shift); // Shift is dead.
4655 AddUsesToWorkList(I);
4656 return &I;
Chris Lattner5eb91942004-07-21 19:50:44 +00004657 }
4658 }
Chris Lattner457dd822004-06-09 07:59:58 +00004659 }
Chris Lattner65b72ba2006-09-18 04:22:48 +00004660
4661 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
4662 // preferable because it allows the C<<Y expression to be hoisted out
4663 // of a loop if Y is invariant and X is not.
4664 if (Shift && Shift->hasOneUse() && CI->isNullValue() &&
Chris Lattner6d7ca922006-09-18 18:27:05 +00004665 I.isEquality() && !Shift->isArithmeticShift() &&
4666 isa<Instruction>(Shift->getOperand(0))) {
Chris Lattner65b72ba2006-09-18 04:22:48 +00004667 // Compute C << Y.
4668 Value *NS;
Reid Spencer3822ff52006-11-08 06:47:33 +00004669 if (Shift->getOpcode() == Instruction::LShr) {
Chris Lattner65b72ba2006-09-18 04:22:48 +00004670 NS = new ShiftInst(Instruction::Shl, AndCST, Shift->getOperand(1),
4671 "tmp");
4672 } else {
Reid Spencer7eb76382006-12-13 17:19:09 +00004673 // Insert a logical shift.
4674 NS = new ShiftInst(Instruction::LShr, AndCST,
Chris Lattnere695a3b2006-09-18 05:27:43 +00004675 Shift->getOperand(1), "tmp");
Chris Lattner65b72ba2006-09-18 04:22:48 +00004676 }
4677 InsertNewInstBefore(cast<Instruction>(NS), I);
4678
Chris Lattner65b72ba2006-09-18 04:22:48 +00004679 // Compute X & (C << Y).
Reid Spencer8c5a53a2007-01-04 05:23:51 +00004680 Instruction *NewAnd = BinaryOperator::createAnd(
4681 Shift->getOperand(0), NS, LHSI->getName());
Chris Lattner65b72ba2006-09-18 04:22:48 +00004682 InsertNewInstBefore(NewAnd, I);
4683
4684 I.setOperand(0, NewAnd);
4685 return &I;
4686 }
Chris Lattner648e3bc2004-09-23 21:52:49 +00004687 }
4688 break;
Chris Lattner83c4ec02004-09-27 19:29:18 +00004689
Reid Spencere4d87aa2006-12-23 06:05:41 +00004690 case Instruction::Shl: // (icmp pred (shl X, ShAmt), CI)
Reid Spencerb83eb642006-10-20 07:07:24 +00004691 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Chris Lattner65b72ba2006-09-18 04:22:48 +00004692 if (I.isEquality()) {
Chris Lattnere17a1282005-06-15 20:53:31 +00004693 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
4694
4695 // Check that the shift amount is in range. If not, don't perform
4696 // undefined shifts. When the shift is visited it will be
4697 // simplified.
Reid Spencerb83eb642006-10-20 07:07:24 +00004698 if (ShAmt->getZExtValue() >= TypeBits)
Chris Lattnere17a1282005-06-15 20:53:31 +00004699 break;
4700
Chris Lattner18d19ca2004-09-28 18:22:15 +00004701 // If we are comparing against bits always shifted out, the
4702 // comparison cannot succeed.
Misha Brukmanfd939082005-04-21 23:48:37 +00004703 Constant *Comp =
Reid Spencer3822ff52006-11-08 06:47:33 +00004704 ConstantExpr::getShl(ConstantExpr::getLShr(CI, ShAmt), ShAmt);
Chris Lattner18d19ca2004-09-28 18:22:15 +00004705 if (Comp != CI) {// Comparing against a bit that we know is zero.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004706 bool IsICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
4707 Constant *Cst = ConstantBool::get(IsICMP_NE);
Chris Lattner18d19ca2004-09-28 18:22:15 +00004708 return ReplaceInstUsesWith(I, Cst);
4709 }
4710
4711 if (LHSI->hasOneUse()) {
4712 // Otherwise strength reduce the shift into an and.
Reid Spencerb83eb642006-10-20 07:07:24 +00004713 unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
Chris Lattner18d19ca2004-09-28 18:22:15 +00004714 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
Reid Spencerc5b206b2006-12-31 05:48:39 +00004715 Constant *Mask = ConstantInt::get(CI->getType(), Val);
Misha Brukmanfd939082005-04-21 23:48:37 +00004716
Chris Lattner18d19ca2004-09-28 18:22:15 +00004717 Instruction *AndI =
4718 BinaryOperator::createAnd(LHSI->getOperand(0),
4719 Mask, LHSI->getName()+".mask");
4720 Value *And = InsertNewInstBefore(AndI, I);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004721 return new ICmpInst(I.getPredicate(), And,
Reid Spencer3822ff52006-11-08 06:47:33 +00004722 ConstantExpr::getLShr(CI, ShAmt));
Chris Lattner18d19ca2004-09-28 18:22:15 +00004723 }
4724 }
Chris Lattner18d19ca2004-09-28 18:22:15 +00004725 }
4726 break;
4727
Reid Spencere4d87aa2006-12-23 06:05:41 +00004728 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Reid Spencer3822ff52006-11-08 06:47:33 +00004729 case Instruction::AShr:
Reid Spencerb83eb642006-10-20 07:07:24 +00004730 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Chris Lattner65b72ba2006-09-18 04:22:48 +00004731 if (I.isEquality()) {
Chris Lattnere17a1282005-06-15 20:53:31 +00004732 // Check that the shift amount is in range. If not, don't perform
4733 // undefined shifts. When the shift is visited it will be
4734 // simplified.
Chris Lattneraa457ac2005-06-16 01:52:07 +00004735 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencerb83eb642006-10-20 07:07:24 +00004736 if (ShAmt->getZExtValue() >= TypeBits)
Chris Lattnere17a1282005-06-15 20:53:31 +00004737 break;
4738
Chris Lattnerf63f6472004-09-27 16:18:50 +00004739 // If we are comparing against bits always shifted out, the
4740 // comparison cannot succeed.
Reid Spencer3822ff52006-11-08 06:47:33 +00004741 Constant *Comp;
Reid Spencerc5b206b2006-12-31 05:48:39 +00004742 if (LHSI->getOpcode() == Instruction::LShr)
Reid Spencer3822ff52006-11-08 06:47:33 +00004743 Comp = ConstantExpr::getLShr(ConstantExpr::getShl(CI, ShAmt),
4744 ShAmt);
4745 else
4746 Comp = ConstantExpr::getAShr(ConstantExpr::getShl(CI, ShAmt),
4747 ShAmt);
Misha Brukmanfd939082005-04-21 23:48:37 +00004748
Chris Lattnerf63f6472004-09-27 16:18:50 +00004749 if (Comp != CI) {// Comparing against a bit that we know is zero.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004750 bool IsICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
4751 Constant *Cst = ConstantBool::get(IsICMP_NE);
Chris Lattnerf63f6472004-09-27 16:18:50 +00004752 return ReplaceInstUsesWith(I, Cst);
4753 }
Misha Brukmanfd939082005-04-21 23:48:37 +00004754
Chris Lattnerf63f6472004-09-27 16:18:50 +00004755 if (LHSI->hasOneUse() || CI->isNullValue()) {
Reid Spencerb83eb642006-10-20 07:07:24 +00004756 unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
Chris Lattner18d19ca2004-09-28 18:22:15 +00004757
Chris Lattnerf63f6472004-09-27 16:18:50 +00004758 // Otherwise strength reduce the shift into an and.
4759 uint64_t Val = ~0ULL; // All ones.
4760 Val <<= ShAmtVal; // Shift over to the right spot.
Reid Spencerc5b206b2006-12-31 05:48:39 +00004761 Val &= ~0ULL >> (64-TypeBits);
4762 Constant *Mask = ConstantInt::get(CI->getType(), Val);
Misha Brukmanfd939082005-04-21 23:48:37 +00004763
Chris Lattnerf63f6472004-09-27 16:18:50 +00004764 Instruction *AndI =
4765 BinaryOperator::createAnd(LHSI->getOperand(0),
4766 Mask, LHSI->getName()+".mask");
4767 Value *And = InsertNewInstBefore(AndI, I);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004768 return new ICmpInst(I.getPredicate(), And,
Chris Lattnerf63f6472004-09-27 16:18:50 +00004769 ConstantExpr::getShl(CI, ShAmt));
4770 }
Chris Lattnerf63f6472004-09-27 16:18:50 +00004771 }
4772 }
4773 break;
Chris Lattner0c967662004-09-24 15:21:34 +00004774
Reid Spencer1628cec2006-10-26 06:15:43 +00004775 case Instruction::SDiv:
4776 case Instruction::UDiv:
Reid Spencere4d87aa2006-12-23 06:05:41 +00004777 // Fold: icmp pred ([us]div X, C1), C2 -> range test
Reid Spencer1628cec2006-10-26 06:15:43 +00004778 // Fold this div into the comparison, producing a range check.
4779 // Determine, based on the divide type, what the range is being
4780 // checked. If there is an overflow on the low or high side, remember
4781 // it, otherwise compute the range [low, hi) bounding the new value.
4782 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattnera96879a2004-09-29 17:40:11 +00004783 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00004784 // FIXME: If the operand types don't match the type of the divide
4785 // then don't attempt this transform. The code below doesn't have the
4786 // logic to deal with a signed divide and an unsigned compare (and
4787 // vice versa). This is because (x /s C1) <s C2 produces different
4788 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
4789 // (x /u C1) <u C2. Simply casting the operands and result won't
4790 // work. :( The if statement below tests that condition and bails
4791 // if it finds it.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004792 bool DivIsSigned = LHSI->getOpcode() == Instruction::SDiv;
4793 if (!I.isEquality() && DivIsSigned != I.isSignedPredicate())
Reid Spencer1628cec2006-10-26 06:15:43 +00004794 break;
4795
4796 // Initialize the variables that will indicate the nature of the
4797 // range check.
4798 bool LoOverflow = false, HiOverflow = false;
Chris Lattnera96879a2004-09-29 17:40:11 +00004799 ConstantInt *LoBound = 0, *HiBound = 0;
4800
Reid Spencer1628cec2006-10-26 06:15:43 +00004801 // Compute Prod = CI * DivRHS. We are essentially solving an equation
4802 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
4803 // C2 (CI). By solving for X we can turn this into a range check
4804 // instead of computing a divide.
4805 ConstantInt *Prod =
4806 cast<ConstantInt>(ConstantExpr::getMul(CI, DivRHS));
Chris Lattnera96879a2004-09-29 17:40:11 +00004807
Reid Spencer1628cec2006-10-26 06:15:43 +00004808 // Determine if the product overflows by seeing if the product is
4809 // not equal to the divide. Make sure we do the same kind of divide
4810 // as in the LHS instruction that we're folding.
4811 bool ProdOV = !DivRHS->isNullValue() &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00004812 (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
Reid Spencer1628cec2006-10-26 06:15:43 +00004813 ConstantExpr::getUDiv(Prod, DivRHS)) != CI;
4814
Reid Spencere4d87aa2006-12-23 06:05:41 +00004815 // Get the ICmp opcode
4816 ICmpInst::Predicate predicate = I.getPredicate();
Chris Lattner6a9fdfa2004-10-11 19:40:04 +00004817
Reid Spencer1628cec2006-10-26 06:15:43 +00004818 if (DivRHS->isNullValue()) {
4819 // Don't hack on divide by zeros!
Reid Spencere4d87aa2006-12-23 06:05:41 +00004820 } else if (!DivIsSigned) { // udiv
Chris Lattnera96879a2004-09-29 17:40:11 +00004821 LoBound = Prod;
4822 LoOverflow = ProdOV;
4823 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
Reid Spencer1628cec2006-10-26 06:15:43 +00004824 } else if (isPositive(DivRHS)) { // Divisor is > 0.
Chris Lattnera96879a2004-09-29 17:40:11 +00004825 if (CI->isNullValue()) { // (X / pos) op 0
4826 // Can't overflow.
4827 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
4828 HiBound = DivRHS;
4829 } else if (isPositive(CI)) { // (X / pos) op pos
4830 LoBound = Prod;
4831 LoOverflow = ProdOV;
4832 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
4833 } else { // (X / pos) op neg
4834 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
4835 LoOverflow = AddWithOverflow(LoBound, Prod,
4836 cast<ConstantInt>(DivRHSH));
4837 HiBound = Prod;
4838 HiOverflow = ProdOV;
4839 }
Reid Spencer1628cec2006-10-26 06:15:43 +00004840 } else { // Divisor is < 0.
Chris Lattnera96879a2004-09-29 17:40:11 +00004841 if (CI->isNullValue()) { // (X / neg) op 0
4842 LoBound = AddOne(DivRHS);
4843 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner56625032005-06-17 02:05:55 +00004844 if (HiBound == DivRHS)
Reid Spencer1628cec2006-10-26 06:15:43 +00004845 LoBound = 0; // - INTMIN = INTMIN
Chris Lattnera96879a2004-09-29 17:40:11 +00004846 } else if (isPositive(CI)) { // (X / neg) op pos
4847 HiOverflow = LoOverflow = ProdOV;
4848 if (!LoOverflow)
4849 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
4850 HiBound = AddOne(Prod);
4851 } else { // (X / neg) op neg
4852 LoBound = Prod;
4853 LoOverflow = HiOverflow = ProdOV;
4854 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
4855 }
Chris Lattner340a05f2004-10-08 19:15:44 +00004856
Chris Lattner6a9fdfa2004-10-11 19:40:04 +00004857 // Dividing by a negate swaps the condition.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004858 predicate = ICmpInst::getSwappedPredicate(predicate);
Chris Lattnera96879a2004-09-29 17:40:11 +00004859 }
4860
4861 if (LoBound) {
4862 Value *X = LHSI->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004863 switch (predicate) {
4864 default: assert(0 && "Unhandled icmp opcode!");
4865 case ICmpInst::ICMP_EQ:
Chris Lattnera96879a2004-09-29 17:40:11 +00004866 if (LoOverflow && HiOverflow)
Chris Lattner47811b72006-09-28 23:35:22 +00004867 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattnera96879a2004-09-29 17:40:11 +00004868 else if (HiOverflow)
Reid Spencere4d87aa2006-12-23 06:05:41 +00004869 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
4870 ICmpInst::ICMP_UGE, X, LoBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00004871 else if (LoOverflow)
Reid Spencere4d87aa2006-12-23 06:05:41 +00004872 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
4873 ICmpInst::ICMP_ULT, X, HiBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00004874 else
Reid Spencere4d87aa2006-12-23 06:05:41 +00004875 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned,
4876 true, I);
4877 case ICmpInst::ICMP_NE:
Chris Lattnera96879a2004-09-29 17:40:11 +00004878 if (LoOverflow && HiOverflow)
Chris Lattner47811b72006-09-28 23:35:22 +00004879 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattnera96879a2004-09-29 17:40:11 +00004880 else if (HiOverflow)
Reid Spencere4d87aa2006-12-23 06:05:41 +00004881 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
4882 ICmpInst::ICMP_ULT, X, LoBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00004883 else if (LoOverflow)
Reid Spencere4d87aa2006-12-23 06:05:41 +00004884 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
4885 ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00004886 else
Reid Spencere4d87aa2006-12-23 06:05:41 +00004887 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned,
4888 false, I);
4889 case ICmpInst::ICMP_ULT:
4890 case ICmpInst::ICMP_SLT:
Chris Lattnera96879a2004-09-29 17:40:11 +00004891 if (LoOverflow)
Chris Lattner47811b72006-09-28 23:35:22 +00004892 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004893 return new ICmpInst(predicate, X, LoBound);
4894 case ICmpInst::ICMP_UGT:
4895 case ICmpInst::ICMP_SGT:
Chris Lattnera96879a2004-09-29 17:40:11 +00004896 if (HiOverflow)
Chris Lattner47811b72006-09-28 23:35:22 +00004897 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004898 if (predicate == ICmpInst::ICMP_UGT)
4899 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
4900 else
4901 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00004902 }
4903 }
4904 }
4905 break;
Chris Lattner648e3bc2004-09-23 21:52:49 +00004906 }
Misha Brukmanfd939082005-04-21 23:48:37 +00004907
Reid Spencere4d87aa2006-12-23 06:05:41 +00004908 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
Chris Lattner65b72ba2006-09-18 04:22:48 +00004909 if (I.isEquality()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00004910 bool isICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
Chris Lattnerbc5d4142003-07-23 17:02:11 +00004911
Reid Spencerb83eb642006-10-20 07:07:24 +00004912 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
4913 // the second operand is a constant, simplify a bit.
Chris Lattner934754b2003-08-13 05:33:12 +00004914 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
4915 switch (BO->getOpcode()) {
Reid Spencerb83eb642006-10-20 07:07:24 +00004916 case Instruction::SRem:
4917 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
4918 if (CI->isNullValue() && isa<ConstantInt>(BO->getOperand(1)) &&
4919 BO->hasOneUse()) {
4920 int64_t V = cast<ConstantInt>(BO->getOperand(1))->getSExtValue();
4921 if (V > 1 && isPowerOf2_64(V)) {
Reid Spencer0a783f72006-11-02 01:53:59 +00004922 Value *NewRem = InsertNewInstBefore(BinaryOperator::createURem(
4923 BO->getOperand(0), BO->getOperand(1), BO->getName()), I);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004924 return new ICmpInst(I.getPredicate(), NewRem,
4925 Constant::getNullValue(BO->getType()));
Chris Lattner3571b722004-07-06 07:38:18 +00004926 }
Chris Lattnerbcd7db52005-08-02 19:16:58 +00004927 }
Misha Brukmanfd939082005-04-21 23:48:37 +00004928 break;
Chris Lattner934754b2003-08-13 05:33:12 +00004929 case Instruction::Add:
Chris Lattner15d58b62004-06-27 22:51:36 +00004930 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
4931 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattner3d834bf2004-09-21 21:35:23 +00004932 if (BO->hasOneUse())
Reid Spencere4d87aa2006-12-23 06:05:41 +00004933 return new ICmpInst(I.getPredicate(), BO->getOperand(0),
4934 ConstantExpr::getSub(CI, BOp1C));
Chris Lattner15d58b62004-06-27 22:51:36 +00004935 } else if (CI->isNullValue()) {
Chris Lattner934754b2003-08-13 05:33:12 +00004936 // Replace ((add A, B) != 0) with (A != -B) if A or B is
4937 // efficiently invertible, or if the add has just this one use.
4938 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Misha Brukmanfd939082005-04-21 23:48:37 +00004939
Chris Lattner934754b2003-08-13 05:33:12 +00004940 if (Value *NegVal = dyn_castNegVal(BOp1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00004941 return new ICmpInst(I.getPredicate(), BOp0, NegVal);
Chris Lattner934754b2003-08-13 05:33:12 +00004942 else if (Value *NegVal = dyn_castNegVal(BOp0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00004943 return new ICmpInst(I.getPredicate(), NegVal, BOp1);
Chris Lattnerfd059242003-10-15 16:48:29 +00004944 else if (BO->hasOneUse()) {
Chris Lattner934754b2003-08-13 05:33:12 +00004945 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
4946 BO->setName("");
4947 InsertNewInstBefore(Neg, I);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004948 return new ICmpInst(I.getPredicate(), BOp0, Neg);
Chris Lattner934754b2003-08-13 05:33:12 +00004949 }
4950 }
4951 break;
4952 case Instruction::Xor:
4953 // For the xor case, we can xor two constants together, eliminating
4954 // the explicit xor.
4955 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
Reid Spencere4d87aa2006-12-23 06:05:41 +00004956 return new ICmpInst(I.getPredicate(), BO->getOperand(0),
4957 ConstantExpr::getXor(CI, BOC));
Chris Lattner934754b2003-08-13 05:33:12 +00004958
4959 // FALLTHROUGH
4960 case Instruction::Sub:
4961 // Replace (([sub|xor] A, B) != 0) with (A != B)
4962 if (CI->isNullValue())
Reid Spencere4d87aa2006-12-23 06:05:41 +00004963 return new ICmpInst(I.getPredicate(), BO->getOperand(0),
4964 BO->getOperand(1));
Chris Lattner934754b2003-08-13 05:33:12 +00004965 break;
4966
4967 case Instruction::Or:
4968 // If bits are being or'd in that are not present in the constant we
4969 // are comparing against, then the comparison could never succeed!
Chris Lattner7c4049c2004-01-12 19:35:11 +00004970 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattner448c3232004-06-10 02:12:35 +00004971 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattner48595f12004-06-10 02:07:29 +00004972 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Reid Spencere4d87aa2006-12-23 06:05:41 +00004973 return ReplaceInstUsesWith(I, ConstantBool::get(isICMP_NE));
Chris Lattner7c4049c2004-01-12 19:35:11 +00004974 }
Chris Lattner934754b2003-08-13 05:33:12 +00004975 break;
4976
4977 case Instruction::And:
4978 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerbc5d4142003-07-23 17:02:11 +00004979 // If bits are being compared against that are and'd out, then the
4980 // comparison can never succeed!
Chris Lattner448c3232004-06-10 02:12:35 +00004981 if (!ConstantExpr::getAnd(CI,
4982 ConstantExpr::getNot(BOC))->isNullValue())
Reid Spencere4d87aa2006-12-23 06:05:41 +00004983 return ReplaceInstUsesWith(I, ConstantBool::get(isICMP_NE));
Chris Lattner934754b2003-08-13 05:33:12 +00004984
Chris Lattner457dd822004-06-09 07:59:58 +00004985 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattner3285a6f2004-06-10 02:33:20 +00004986 if (CI == BOC && isOneBitSet(CI))
Reid Spencere4d87aa2006-12-23 06:05:41 +00004987 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
4988 ICmpInst::ICMP_NE, Op0,
4989 Constant::getNullValue(CI->getType()));
Chris Lattner457dd822004-06-09 07:59:58 +00004990
Reid Spencere4d87aa2006-12-23 06:05:41 +00004991 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattner934754b2003-08-13 05:33:12 +00004992 if (isSignBit(BOC)) {
4993 Value *X = BO->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004994 Constant *Zero = Constant::getNullValue(X->getType());
4995 ICmpInst::Predicate pred = isICMP_NE ?
4996 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
4997 return new ICmpInst(pred, X, Zero);
Chris Lattner934754b2003-08-13 05:33:12 +00004998 }
Misha Brukmanfd939082005-04-21 23:48:37 +00004999
Chris Lattner83c4ec02004-09-27 19:29:18 +00005000 // ((X & ~7) == 0) --> X < 8
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00005001 if (CI->isNullValue() && isHighOnes(BOC)) {
5002 Value *X = BO->getOperand(0);
Chris Lattner83c4ec02004-09-27 19:29:18 +00005003 Constant *NegX = ConstantExpr::getNeg(BOC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005004 ICmpInst::Predicate pred = isICMP_NE ?
5005 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
5006 return new ICmpInst(pred, X, NegX);
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00005007 }
5008
Chris Lattnerbc5d4142003-07-23 17:02:11 +00005009 }
Chris Lattner934754b2003-08-13 05:33:12 +00005010 default: break;
5011 }
Chris Lattner458cf462006-11-29 05:02:16 +00005012 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op0)) {
5013 // Handle set{eq|ne} <intrinsic>, intcst.
5014 switch (II->getIntrinsicID()) {
5015 default: break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005016 case Intrinsic::bswap_i16:
5017 // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
Chris Lattner458cf462006-11-29 05:02:16 +00005018 WorkList.push_back(II); // Dead?
5019 I.setOperand(0, II->getOperand(1));
Reid Spencerc5b206b2006-12-31 05:48:39 +00005020 I.setOperand(1, ConstantInt::get(Type::Int16Ty,
Chris Lattner458cf462006-11-29 05:02:16 +00005021 ByteSwap_16(CI->getZExtValue())));
5022 return &I;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005023 case Intrinsic::bswap_i32:
5024 // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
Chris Lattner458cf462006-11-29 05:02:16 +00005025 WorkList.push_back(II); // Dead?
5026 I.setOperand(0, II->getOperand(1));
Reid Spencerc5b206b2006-12-31 05:48:39 +00005027 I.setOperand(1, ConstantInt::get(Type::Int32Ty,
Chris Lattner458cf462006-11-29 05:02:16 +00005028 ByteSwap_32(CI->getZExtValue())));
5029 return &I;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005030 case Intrinsic::bswap_i64:
5031 // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
Chris Lattner458cf462006-11-29 05:02:16 +00005032 WorkList.push_back(II); // Dead?
5033 I.setOperand(0, II->getOperand(1));
Reid Spencerc5b206b2006-12-31 05:48:39 +00005034 I.setOperand(1, ConstantInt::get(Type::Int64Ty,
Chris Lattner458cf462006-11-29 05:02:16 +00005035 ByteSwap_64(CI->getZExtValue())));
5036 return &I;
5037 }
Chris Lattner934754b2003-08-13 05:33:12 +00005038 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00005039 } else { // Not a ICMP_EQ/ICMP_NE
5040 // If the LHS is a cast from an integral value of the same size, then
5041 // since we know the RHS is a constant, try to simlify.
Chris Lattnerc5943fb2004-02-23 07:16:20 +00005042 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
5043 Value *CastOp = Cast->getOperand(0);
5044 const Type *SrcTy = CastOp->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00005045 unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
Reid Spencere4d87aa2006-12-23 06:05:41 +00005046 if (SrcTy->isInteger() &&
Chris Lattner484d3cf2005-04-24 06:59:08 +00005047 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005048 // If this is an unsigned comparison, try to make the comparison use
5049 // smaller constant values.
5050 switch (I.getPredicate()) {
5051 default: break;
5052 case ICmpInst::ICMP_ULT: { // X u< 128 => X s> -1
5053 ConstantInt *CUI = cast<ConstantInt>(CI);
5054 if (CUI->getZExtValue() == 1ULL << (SrcTySize-1))
5055 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp,
5056 ConstantInt::get(SrcTy, -1));
5057 break;
5058 }
5059 case ICmpInst::ICMP_UGT: { // X u> 127 => X s< 0
5060 ConstantInt *CUI = cast<ConstantInt>(CI);
5061 if (CUI->getZExtValue() == (1ULL << (SrcTySize-1))-1)
5062 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp,
5063 Constant::getNullValue(SrcTy));
5064 break;
5065 }
Chris Lattnerc5943fb2004-02-23 07:16:20 +00005066 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00005067
Chris Lattnerc5943fb2004-02-23 07:16:20 +00005068 }
5069 }
Chris Lattner40f5d702003-06-04 05:10:11 +00005070 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00005071 }
5072
Reid Spencere4d87aa2006-12-23 06:05:41 +00005073 // Handle icmp with constant RHS
Chris Lattner6970b662005-04-23 15:31:55 +00005074 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5075 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5076 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00005077 case Instruction::GetElementPtr:
5078 if (RHSC->isNullValue()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005079 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattner9fb25db2005-05-01 04:42:15 +00005080 bool isAllZeros = true;
5081 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5082 if (!isa<Constant>(LHSI->getOperand(i)) ||
5083 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5084 isAllZeros = false;
5085 break;
5086 }
5087 if (isAllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005088 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Chris Lattner9fb25db2005-05-01 04:42:15 +00005089 Constant::getNullValue(LHSI->getOperand(0)->getType()));
5090 }
5091 break;
5092
Chris Lattner6970b662005-04-23 15:31:55 +00005093 case Instruction::PHI:
5094 if (Instruction *NV = FoldOpIntoPhi(I))
5095 return NV;
5096 break;
5097 case Instruction::Select:
5098 // If either operand of the select is a constant, we can fold the
5099 // comparison into the select arms, which will cause one to be
5100 // constant folded and the select turned into a bitwise or.
5101 Value *Op1 = 0, *Op2 = 0;
5102 if (LHSI->hasOneUse()) {
5103 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5104 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005105 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5106 // Insert a new ICmp of the other select operand.
5107 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5108 LHSI->getOperand(2), RHSC,
5109 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00005110 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5111 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005112 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5113 // Insert a new ICmp of the other select operand.
5114 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5115 LHSI->getOperand(1), RHSC,
5116 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00005117 }
5118 }
Jeff Cohen9d809302005-04-23 21:38:35 +00005119
Chris Lattner6970b662005-04-23 15:31:55 +00005120 if (Op1)
5121 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
5122 break;
5123 }
5124 }
5125
Reid Spencere4d87aa2006-12-23 06:05:41 +00005126 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Chris Lattner574da9b2005-01-13 20:14:25 +00005127 if (User *GEP = dyn_castGetElementPtr(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005128 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00005129 return NI;
5130 if (User *GEP = dyn_castGetElementPtr(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005131 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5132 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00005133 return NI;
5134
Reid Spencere4d87aa2006-12-23 06:05:41 +00005135 // Test to see if the operands of the icmp are casted versions of other
Chris Lattnerde90b762003-11-03 04:25:02 +00005136 // values. If the cast can be stripped off both arguments, we do so now.
Chris Lattner68708052003-11-03 05:17:03 +00005137 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
5138 Value *CastOp0 = CI->getOperand(0);
Reid Spencer3da59db2006-11-27 01:05:10 +00005139 if (CI->isLosslessCast() && I.isEquality() &&
5140 (isa<Constant>(Op1) || isa<CastInst>(Op1))) {
Chris Lattnerde90b762003-11-03 04:25:02 +00005141 // We keep moving the cast from the left operand over to the right
5142 // operand, where it can often be eliminated completely.
Chris Lattner68708052003-11-03 05:17:03 +00005143 Op0 = CastOp0;
Misha Brukmanfd939082005-04-21 23:48:37 +00005144
Chris Lattnerde90b762003-11-03 04:25:02 +00005145 // If operand #1 is a cast instruction, see if we can eliminate it as
5146 // well.
Reid Spencer3da59db2006-11-27 01:05:10 +00005147 if (CastInst *CI2 = dyn_cast<CastInst>(Op1)) {
5148 Value *CI2Op0 = CI2->getOperand(0);
5149 if (CI2Op0->getType()->canLosslesslyBitCastTo(Op0->getType()))
5150 Op1 = CI2Op0;
5151 }
Misha Brukmanfd939082005-04-21 23:48:37 +00005152
Chris Lattnerde90b762003-11-03 04:25:02 +00005153 // If Op1 is a constant, we can fold the cast into the constant.
5154 if (Op1->getType() != Op0->getType())
5155 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Reid Spencerd977d862006-12-12 23:36:14 +00005156 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00005157 } else {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005158 // Otherwise, cast the RHS right before the icmp
Reid Spencer17212df2006-12-12 09:18:51 +00005159 Op1 = InsertCastBefore(Instruction::BitCast, Op1, Op0->getType(), I);
Chris Lattnerde90b762003-11-03 04:25:02 +00005160 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00005161 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattnerde90b762003-11-03 04:25:02 +00005162 }
5163
Reid Spencere4d87aa2006-12-23 06:05:41 +00005164 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner68708052003-11-03 05:17:03 +00005165 // This comes up when you have code like
5166 // int X = A < B;
5167 // if (X) ...
5168 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00005169 // with a constant or another cast from the same type.
5170 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005171 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattner484d3cf2005-04-24 06:59:08 +00005172 return R;
Chris Lattner68708052003-11-03 05:17:03 +00005173 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00005174
Chris Lattner65b72ba2006-09-18 04:22:48 +00005175 if (I.isEquality()) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005176 Value *A, *B, *C, *D;
5177 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
5178 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
5179 Value *OtherVal = A == Op1 ? B : A;
5180 return new ICmpInst(I.getPredicate(), OtherVal,
5181 Constant::getNullValue(A->getType()));
5182 }
5183
5184 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5185 // A^c1 == C^c2 --> A == C^(c1^c2)
5186 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
5187 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
5188 if (Op1->hasOneUse()) {
5189 Constant *NC = ConstantExpr::getXor(C1, C2);
5190 Instruction *Xor = BinaryOperator::createXor(C, NC, "tmp");
5191 return new ICmpInst(I.getPredicate(), A,
5192 InsertNewInstBefore(Xor, I));
5193 }
5194
5195 // A^B == A^D -> B == D
5196 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
5197 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
5198 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
5199 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
5200 }
5201 }
5202
5203 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5204 (A == Op0 || B == Op0)) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00005205 // A == (A^B) -> B == 0
5206 Value *OtherVal = A == Op0 ? B : A;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005207 return new ICmpInst(I.getPredicate(), OtherVal,
5208 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005209 }
5210 if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00005211 // (A-B) == A -> B == 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00005212 return new ICmpInst(I.getPredicate(), B,
5213 Constant::getNullValue(B->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005214 }
5215 if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00005216 // A == (A-B) -> B == 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00005217 return new ICmpInst(I.getPredicate(), B,
5218 Constant::getNullValue(B->getType()));
Chris Lattner26ab9a92006-02-27 01:44:11 +00005219 }
Chris Lattner9c2328e2006-11-14 06:06:06 +00005220
Chris Lattner9c2328e2006-11-14 06:06:06 +00005221 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5222 if (Op0->hasOneUse() && Op1->hasOneUse() &&
5223 match(Op0, m_And(m_Value(A), m_Value(B))) &&
5224 match(Op1, m_And(m_Value(C), m_Value(D)))) {
5225 Value *X = 0, *Y = 0, *Z = 0;
5226
5227 if (A == C) {
5228 X = B; Y = D; Z = A;
5229 } else if (A == D) {
5230 X = B; Y = C; Z = A;
5231 } else if (B == C) {
5232 X = A; Y = D; Z = B;
5233 } else if (B == D) {
5234 X = A; Y = C; Z = B;
5235 }
5236
5237 if (X) { // Build (X^Y) & Z
5238 Op1 = InsertNewInstBefore(BinaryOperator::createXor(X, Y, "tmp"), I);
5239 Op1 = InsertNewInstBefore(BinaryOperator::createAnd(Op1, Z, "tmp"), I);
5240 I.setOperand(0, Op1);
5241 I.setOperand(1, Constant::getNullValue(Op1->getType()));
5242 return &I;
5243 }
5244 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00005245 }
Chris Lattner7e708292002-06-25 16:13:24 +00005246 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005247}
5248
Reid Spencere4d87aa2006-12-23 06:05:41 +00005249// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
Chris Lattner484d3cf2005-04-24 06:59:08 +00005250// We only handle extending casts so far.
5251//
Reid Spencere4d87aa2006-12-23 06:05:41 +00005252Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
5253 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +00005254 Value *LHSCIOp = LHSCI->getOperand(0);
5255 const Type *SrcTy = LHSCIOp->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00005256 const Type *DestTy = LHSCI->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00005257 Value *RHSCIOp;
5258
Reid Spencere4d87aa2006-12-23 06:05:41 +00005259 // We only handle extension cast instructions, so far. Enforce this.
5260 if (LHSCI->getOpcode() != Instruction::ZExt &&
5261 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattnerb352fa52005-01-17 03:20:02 +00005262 return 0;
5263
Reid Spencere4d87aa2006-12-23 06:05:41 +00005264 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
5265 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattner484d3cf2005-04-24 06:59:08 +00005266
Reid Spencere4d87aa2006-12-23 06:05:41 +00005267 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00005268 // Not an extension from the same type?
5269 RHSCIOp = CI->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005270 if (RHSCIOp->getType() != LHSCIOp->getType())
5271 return 0;
5272 else
5273 // Okay, just insert a compare of the reduced operands now!
5274 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer6731d5c2004-11-28 21:31:15 +00005275 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00005276
Reid Spencere4d87aa2006-12-23 06:05:41 +00005277 // If we aren't dealing with a constant on the RHS, exit early
5278 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
5279 if (!CI)
5280 return 0;
5281
5282 // Compute the constant that would happen if we truncated to SrcTy then
5283 // reextended to DestTy.
5284 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
5285 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
5286
5287 // If the re-extended constant didn't change...
5288 if (Res2 == CI) {
5289 // Make sure that sign of the Cmp and the sign of the Cast are the same.
5290 // For example, we might have:
5291 // %A = sext short %X to uint
5292 // %B = icmp ugt uint %A, 1330
5293 // It is incorrect to transform this into
5294 // %B = icmp ugt short %X, 1330
5295 // because %A may have negative value.
5296 //
5297 // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
5298 // OR operation is EQ/NE.
5299 if (isSignedExt == isSignedCmp || SrcTy == Type::BoolTy || ICI.isEquality())
5300 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
5301 else
5302 return 0;
5303 }
5304
5305 // The re-extended constant changed so the constant cannot be represented
5306 // in the shorter type. Consequently, we cannot emit a simple comparison.
5307
5308 // First, handle some easy cases. We know the result cannot be equal at this
5309 // point so handle the ICI.isEquality() cases
5310 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
5311 return ReplaceInstUsesWith(ICI, ConstantBool::getFalse());
5312 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
5313 return ReplaceInstUsesWith(ICI, ConstantBool::getTrue());
5314
5315 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
5316 // should have been folded away previously and not enter in here.
5317 Value *Result;
5318 if (isSignedCmp) {
5319 // We're performing a signed comparison.
5320 if (cast<ConstantInt>(CI)->getSExtValue() < 0)
5321 Result = ConstantBool::getFalse(); // X < (small) --> false
5322 else
5323 Result = ConstantBool::getTrue(); // X < (large) --> true
5324 } else {
5325 // We're performing an unsigned comparison.
5326 if (isSignedExt) {
5327 // We're performing an unsigned comp with a sign extended value.
5328 // This is true if the input is >= 0. [aka >s -1]
5329 Constant *NegOne = ConstantIntegral::getAllOnesValue(SrcTy);
5330 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
5331 NegOne, ICI.getName()), ICI);
5332 } else {
5333 // Unsigned extend & unsigned compare -> always true.
5334 Result = ConstantBool::getTrue();
5335 }
5336 }
5337
5338 // Finally, return the value computed.
5339 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
5340 ICI.getPredicate() == ICmpInst::ICMP_SLT) {
5341 return ReplaceInstUsesWith(ICI, Result);
5342 } else {
5343 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
5344 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
5345 "ICmp should be folded!");
5346 if (Constant *CI = dyn_cast<Constant>(Result))
5347 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
5348 else
5349 return BinaryOperator::createNot(Result);
5350 }
Chris Lattner484d3cf2005-04-24 06:59:08 +00005351}
Chris Lattner3f5b8772002-05-06 16:14:14 +00005352
Chris Lattnerea340052003-03-10 19:16:08 +00005353Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00005354 assert(I.getOperand(1)->getType() == Type::Int8Ty);
Chris Lattner7e708292002-06-25 16:13:24 +00005355 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005356
5357 // shl X, 0 == X and shr X, 0 == X
5358 // shl 0, X == 0 and shr 0, X == 0
Reid Spencerc5b206b2006-12-31 05:48:39 +00005359 if (Op1 == Constant::getNullValue(Type::Int8Ty) ||
Chris Lattner233f7dc2002-08-12 21:17:25 +00005360 Op0 == Constant::getNullValue(Op0->getType()))
5361 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00005362
Reid Spencere4d87aa2006-12-23 06:05:41 +00005363 if (isa<UndefValue>(Op0)) {
5364 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00005365 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005366 else // undef << X -> 0, undef >>u X -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00005367 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5368 }
5369 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005370 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
5371 return ReplaceInstUsesWith(I, Op0);
5372 else // X << undef, X >>u undef -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00005373 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00005374 }
5375
Chris Lattnerde2b6602006-11-10 23:38:52 +00005376 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
5377 if (I.getOpcode() == Instruction::AShr)
Reid Spencerb83eb642006-10-20 07:07:24 +00005378 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Chris Lattnerde2b6602006-11-10 23:38:52 +00005379 if (CSI->isAllOnesValue())
Chris Lattnerdf17af12003-08-12 21:53:41 +00005380 return ReplaceInstUsesWith(I, CSI);
5381
Chris Lattner2eefe512004-04-09 19:05:30 +00005382 // Try to fold constant and into select arguments.
5383 if (isa<Constant>(Op0))
5384 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00005385 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00005386 return R;
5387
Chris Lattner120347e2005-05-08 17:34:56 +00005388 // See if we can turn a signed shr into an unsigned shr.
Chris Lattner65b72ba2006-09-18 04:22:48 +00005389 if (I.isArithmeticShift()) {
Chris Lattner3bedbd92006-02-07 07:27:52 +00005390 if (MaskedValueIsZero(Op0,
5391 1ULL << (I.getType()->getPrimitiveSizeInBits()-1))) {
Reid Spencer3822ff52006-11-08 06:47:33 +00005392 return new ShiftInst(Instruction::LShr, Op0, Op1, I.getName());
Chris Lattner120347e2005-05-08 17:34:56 +00005393 }
5394 }
Jeff Cohen00b168892005-07-27 06:12:32 +00005395
Reid Spencerb83eb642006-10-20 07:07:24 +00005396 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00005397 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
5398 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00005399 return 0;
5400}
5401
Reid Spencerb83eb642006-10-20 07:07:24 +00005402Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Chris Lattner4d5542c2006-01-06 07:12:35 +00005403 ShiftInst &I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005404 bool isLeftShift = I.getOpcode() == Instruction::Shl;
5405 bool isSignedShift = I.getOpcode() == Instruction::AShr;
Chris Lattner830ed032006-01-06 07:22:22 +00005406 bool isUnsignedShift = !isSignedShift;
Chris Lattner4d5542c2006-01-06 07:12:35 +00005407
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00005408 // See if we can simplify any instructions used by the instruction whose sole
5409 // purpose is to compute bits we don't care about.
5410 uint64_t KnownZero, KnownOne;
5411 if (SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
5412 KnownZero, KnownOne))
5413 return &I;
5414
Chris Lattner4d5542c2006-01-06 07:12:35 +00005415 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
5416 // of a signed value.
5417 //
5418 unsigned TypeBits = Op0->getType()->getPrimitiveSizeInBits();
Reid Spencerb83eb642006-10-20 07:07:24 +00005419 if (Op1->getZExtValue() >= TypeBits) {
Chris Lattner830ed032006-01-06 07:22:22 +00005420 if (isUnsignedShift || isLeftShift)
Chris Lattner4d5542c2006-01-06 07:12:35 +00005421 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
5422 else {
Reid Spencerc5b206b2006-12-31 05:48:39 +00005423 I.setOperand(1, ConstantInt::get(Type::Int8Ty, TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00005424 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00005425 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00005426 }
5427
5428 // ((X*C1) << C2) == (X * (C1 << C2))
5429 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
5430 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
5431 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
5432 return BinaryOperator::createMul(BO->getOperand(0),
5433 ConstantExpr::getShl(BOOp, Op1));
5434
5435 // Try to fold constant and into select arguments.
5436 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5437 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5438 return R;
5439 if (isa<PHINode>(Op0))
5440 if (Instruction *NV = FoldOpIntoPhi(I))
5441 return NV;
5442
5443 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00005444 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
5445 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
5446 Value *V1, *V2;
5447 ConstantInt *CC;
5448 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00005449 default: break;
5450 case Instruction::Add:
5451 case Instruction::And:
5452 case Instruction::Or:
5453 case Instruction::Xor:
5454 // These operators commute.
5455 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00005456 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
5457 match(Op0BO->getOperand(1),
Chris Lattner4d5542c2006-01-06 07:12:35 +00005458 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Chris Lattner150f12a2005-09-18 06:30:59 +00005459 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner4d5542c2006-01-06 07:12:35 +00005460 Op0BO->getOperand(0), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00005461 Op0BO->getName());
5462 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00005463 Instruction *X =
5464 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
5465 Op0BO->getOperand(1)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00005466 InsertNewInstBefore(X, I); // (X + (Y << C))
5467 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner4d5542c2006-01-06 07:12:35 +00005468 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner150f12a2005-09-18 06:30:59 +00005469 return BinaryOperator::createAnd(X, C2);
5470 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00005471
Chris Lattner150f12a2005-09-18 06:30:59 +00005472 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
5473 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
5474 match(Op0BO->getOperand(1),
5475 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner4d5542c2006-01-06 07:12:35 +00005476 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00005477 cast<BinaryOperator>(Op0BO->getOperand(1))->getOperand(0)->hasOneUse()) {
Chris Lattner150f12a2005-09-18 06:30:59 +00005478 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner4d5542c2006-01-06 07:12:35 +00005479 Op0BO->getOperand(0), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00005480 Op0BO->getName());
5481 InsertNewInstBefore(YS, I); // (Y << C)
5482 Instruction *XM =
Chris Lattner4d5542c2006-01-06 07:12:35 +00005483 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00005484 V1->getName()+".mask");
5485 InsertNewInstBefore(XM, I); // X & (CC << C)
5486
5487 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
5488 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00005489
Chris Lattner150f12a2005-09-18 06:30:59 +00005490 // FALL THROUGH.
Chris Lattner11021cb2005-09-18 05:12:10 +00005491 case Instruction::Sub:
5492 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00005493 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5494 match(Op0BO->getOperand(0),
Chris Lattner4d5542c2006-01-06 07:12:35 +00005495 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Chris Lattner150f12a2005-09-18 06:30:59 +00005496 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner4d5542c2006-01-06 07:12:35 +00005497 Op0BO->getOperand(1), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00005498 Op0BO->getName());
5499 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00005500 Instruction *X =
Chris Lattner13d4ab42006-05-31 21:14:00 +00005501 BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00005502 Op0BO->getOperand(0)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00005503 InsertNewInstBefore(X, I); // (X + (Y << C))
5504 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner4d5542c2006-01-06 07:12:35 +00005505 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner150f12a2005-09-18 06:30:59 +00005506 return BinaryOperator::createAnd(X, C2);
5507 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00005508
Chris Lattner13d4ab42006-05-31 21:14:00 +00005509 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00005510 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5511 match(Op0BO->getOperand(0),
5512 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner4d5542c2006-01-06 07:12:35 +00005513 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00005514 cast<BinaryOperator>(Op0BO->getOperand(0))
5515 ->getOperand(0)->hasOneUse()) {
Chris Lattner150f12a2005-09-18 06:30:59 +00005516 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner4d5542c2006-01-06 07:12:35 +00005517 Op0BO->getOperand(1), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00005518 Op0BO->getName());
5519 InsertNewInstBefore(YS, I); // (Y << C)
5520 Instruction *XM =
Chris Lattner4d5542c2006-01-06 07:12:35 +00005521 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00005522 V1->getName()+".mask");
5523 InsertNewInstBefore(XM, I); // X & (CC << C)
5524
Chris Lattner13d4ab42006-05-31 21:14:00 +00005525 return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00005526 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00005527
Chris Lattner11021cb2005-09-18 05:12:10 +00005528 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00005529 }
5530
5531
5532 // If the operand is an bitwise operator with a constant RHS, and the
5533 // shift is the only use, we can pull it out of the shift.
5534 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
5535 bool isValid = true; // Valid only for And, Or, Xor
5536 bool highBitSet = false; // Transform if high bit of constant set?
5537
5538 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00005539 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00005540 case Instruction::Add:
5541 isValid = isLeftShift;
5542 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00005543 case Instruction::Or:
5544 case Instruction::Xor:
5545 highBitSet = false;
5546 break;
5547 case Instruction::And:
5548 highBitSet = true;
5549 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00005550 }
5551
5552 // If this is a signed shift right, and the high bit is modified
5553 // by the logical operation, do not perform the transformation.
5554 // The highBitSet boolean indicates the value of the high bit of
5555 // the constant which would cause it to be modified for this
5556 // operation.
5557 //
Chris Lattner830ed032006-01-06 07:22:22 +00005558 if (isValid && !isLeftShift && isSignedShift) {
Reid Spencerb83eb642006-10-20 07:07:24 +00005559 uint64_t Val = Op0C->getZExtValue();
Chris Lattner4d5542c2006-01-06 07:12:35 +00005560 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
5561 }
5562
5563 if (isValid) {
5564 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
5565
5566 Instruction *NewShift =
5567 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), Op1,
5568 Op0BO->getName());
5569 Op0BO->setName("");
5570 InsertNewInstBefore(NewShift, I);
5571
5572 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
5573 NewRHS);
5574 }
5575 }
5576 }
5577 }
5578
Chris Lattnerad0124c2006-01-06 07:52:12 +00005579 // Find out if this is a shift of a shift by a constant.
5580 ShiftInst *ShiftOp = 0;
Chris Lattner4d5542c2006-01-06 07:12:35 +00005581 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
Chris Lattnerad0124c2006-01-06 07:52:12 +00005582 ShiftOp = Op0SI;
Reid Spencer3da59db2006-11-27 01:05:10 +00005583 else if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5584 // If this is a noop-integer cast of a shift instruction, use the shift.
5585 if (isa<ShiftInst>(CI->getOperand(0))) {
Chris Lattnerad0124c2006-01-06 07:52:12 +00005586 ShiftOp = cast<ShiftInst>(CI->getOperand(0));
5587 }
5588 }
5589
Reid Spencerb83eb642006-10-20 07:07:24 +00005590 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Chris Lattnerad0124c2006-01-06 07:52:12 +00005591 // Find the operands and properties of the input shift. Note that the
5592 // signedness of the input shift may differ from the current shift if there
5593 // is a noop cast between the two.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005594 bool isShiftOfLeftShift = ShiftOp->getOpcode() == Instruction::Shl;
5595 bool isShiftOfSignedShift = ShiftOp->getOpcode() == Instruction::AShr;
Chris Lattnere8d56c52006-01-07 01:32:28 +00005596 bool isShiftOfUnsignedShift = !isShiftOfSignedShift;
Chris Lattnerad0124c2006-01-06 07:52:12 +00005597
Reid Spencerb83eb642006-10-20 07:07:24 +00005598 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Chris Lattnerad0124c2006-01-06 07:52:12 +00005599
Reid Spencerb83eb642006-10-20 07:07:24 +00005600 unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getZExtValue();
5601 unsigned ShiftAmt2 = (unsigned)Op1->getZExtValue();
Chris Lattnerad0124c2006-01-06 07:52:12 +00005602
5603 // Check for (A << c1) << c2 and (A >> c1) >> c2.
5604 if (isLeftShift == isShiftOfLeftShift) {
5605 // Do not fold these shifts if the first one is signed and the second one
5606 // is unsigned and this is a right shift. Further, don't do any folding
5607 // on them.
5608 if (isShiftOfSignedShift && isUnsignedShift && !isLeftShift)
5609 return 0;
Chris Lattner4d5542c2006-01-06 07:12:35 +00005610
Chris Lattnerad0124c2006-01-06 07:52:12 +00005611 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
5612 if (Amt > Op0->getType()->getPrimitiveSizeInBits())
5613 Amt = Op0->getType()->getPrimitiveSizeInBits();
Chris Lattner4d5542c2006-01-06 07:12:35 +00005614
Chris Lattnerad0124c2006-01-06 07:52:12 +00005615 Value *Op = ShiftOp->getOperand(0);
Reid Spencer3da59db2006-11-27 01:05:10 +00005616 ShiftInst *ShiftResult = new ShiftInst(I.getOpcode(), Op,
Reid Spencerc5b206b2006-12-31 05:48:39 +00005617 ConstantInt::get(Type::Int8Ty, Amt));
Reid Spencer3822ff52006-11-08 06:47:33 +00005618 if (I.getType() == ShiftResult->getType())
5619 return ShiftResult;
5620 InsertNewInstBefore(ShiftResult, I);
Reid Spencer3da59db2006-11-27 01:05:10 +00005621 return CastInst::create(Instruction::BitCast, ShiftResult, I.getType());
Chris Lattnerad0124c2006-01-06 07:52:12 +00005622 }
5623
5624 // Check for (A << c1) >> c2 or (A >> c1) << c2. If we are dealing with
5625 // signed types, we can only support the (A >> c1) << c2 configuration,
5626 // because it can not turn an arbitrary bit of A into a sign bit.
5627 if (isUnsignedShift || isLeftShift) {
5628 // Calculate bitmask for what gets shifted off the edge.
5629 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
5630 if (isLeftShift)
5631 C = ConstantExpr::getShl(C, ShiftAmt1C);
5632 else
Reid Spencer3822ff52006-11-08 06:47:33 +00005633 C = ConstantExpr::getLShr(C, ShiftAmt1C);
Chris Lattnerad0124c2006-01-06 07:52:12 +00005634
5635 Value *Op = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00005636
5637 Instruction *Mask =
5638 BinaryOperator::createAnd(Op, C, Op->getName()+".mask");
5639 InsertNewInstBefore(Mask, I);
5640
5641 // Figure out what flavor of shift we should use...
Chris Lattnere8d56c52006-01-07 01:32:28 +00005642 if (ShiftAmt1 == ShiftAmt2) {
Chris Lattnerad0124c2006-01-06 07:52:12 +00005643 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
Chris Lattnere8d56c52006-01-07 01:32:28 +00005644 } else if (ShiftAmt1 < ShiftAmt2) {
Chris Lattnerad0124c2006-01-06 07:52:12 +00005645 return new ShiftInst(I.getOpcode(), Mask,
Reid Spencerc5b206b2006-12-31 05:48:39 +00005646 ConstantInt::get(Type::Int8Ty, ShiftAmt2-ShiftAmt1));
Chris Lattnere8d56c52006-01-07 01:32:28 +00005647 } else if (isShiftOfUnsignedShift || isShiftOfLeftShift) {
5648 if (isShiftOfUnsignedShift && !isShiftOfLeftShift && isSignedShift) {
Reid Spencer3822ff52006-11-08 06:47:33 +00005649 return new ShiftInst(Instruction::LShr, Mask,
Reid Spencerc5b206b2006-12-31 05:48:39 +00005650 ConstantInt::get(Type::Int8Ty, ShiftAmt1-ShiftAmt2));
Chris Lattnere8d56c52006-01-07 01:32:28 +00005651 } else {
5652 return new ShiftInst(ShiftOp->getOpcode(), Mask,
Reid Spencerc5b206b2006-12-31 05:48:39 +00005653 ConstantInt::get(Type::Int8Ty, ShiftAmt1-ShiftAmt2));
Chris Lattnere8d56c52006-01-07 01:32:28 +00005654 }
5655 } else {
5656 // (X >>s C1) << C2 where C1 > C2 === (X >>s (C1-C2)) & mask
Chris Lattnere8d56c52006-01-07 01:32:28 +00005657 Instruction *Shift =
Reid Spencer7eb76382006-12-13 17:19:09 +00005658 new ShiftInst(ShiftOp->getOpcode(), Mask,
Reid Spencerc5b206b2006-12-31 05:48:39 +00005659 ConstantInt::get(Type::Int8Ty, ShiftAmt1-ShiftAmt2));
Chris Lattnere8d56c52006-01-07 01:32:28 +00005660 InsertNewInstBefore(Shift, I);
5661
5662 C = ConstantIntegral::getAllOnesValue(Shift->getType());
5663 C = ConstantExpr::getShl(C, Op1);
Reid Spencer7eb76382006-12-13 17:19:09 +00005664 return BinaryOperator::createAnd(Shift, C, Op->getName()+".mask");
Chris Lattnerad0124c2006-01-06 07:52:12 +00005665 }
5666 } else {
Chris Lattnere8d56c52006-01-07 01:32:28 +00005667 // We can handle signed (X << C1) >>s C2 if it's a sign extend. In
Chris Lattnerad0124c2006-01-06 07:52:12 +00005668 // this case, C1 == C2 and C1 is 8, 16, or 32.
5669 if (ShiftAmt1 == ShiftAmt2) {
5670 const Type *SExtType = 0;
Chris Lattner94046b42006-04-28 22:21:41 +00005671 switch (Op0->getType()->getPrimitiveSizeInBits() - ShiftAmt1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00005672 case 8 : SExtType = Type::Int8Ty; break;
5673 case 16: SExtType = Type::Int16Ty; break;
5674 case 32: SExtType = Type::Int32Ty; break;
Chris Lattnerad0124c2006-01-06 07:52:12 +00005675 }
5676
5677 if (SExtType) {
Reid Spencer3da59db2006-11-27 01:05:10 +00005678 Instruction *NewTrunc =
5679 new TruncInst(ShiftOp->getOperand(0), SExtType, "sext");
Chris Lattnerad0124c2006-01-06 07:52:12 +00005680 InsertNewInstBefore(NewTrunc, I);
Reid Spencer3da59db2006-11-27 01:05:10 +00005681 return new SExtInst(NewTrunc, I.getType());
Chris Lattnerdf17af12003-08-12 21:53:41 +00005682 }
Chris Lattner11021cb2005-09-18 05:12:10 +00005683 }
Chris Lattner6e7ba452005-01-01 16:22:27 +00005684 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00005685 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00005686 return 0;
5687}
5688
Chris Lattnera1be5662002-05-02 17:06:02 +00005689
Chris Lattnercfd65102005-10-29 04:36:15 +00005690/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
5691/// expression. If so, decompose it, returning some value X, such that Val is
5692/// X*Scale+Offset.
5693///
5694static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
5695 unsigned &Offset) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00005696 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00005697 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00005698 Offset = CI->getZExtValue();
5699 Scale = 1;
5700 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattnercfd65102005-10-29 04:36:15 +00005701 } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
5702 if (I->getNumOperands() == 2) {
Reid Spencerb83eb642006-10-20 07:07:24 +00005703 if (ConstantInt *CUI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00005704 if (I->getOpcode() == Instruction::Shl) {
5705 // This is a value scaled by '1 << the shift amt'.
5706 Scale = 1U << CUI->getZExtValue();
5707 Offset = 0;
5708 return I->getOperand(0);
5709 } else if (I->getOpcode() == Instruction::Mul) {
5710 // This value is scaled by 'CUI'.
5711 Scale = CUI->getZExtValue();
5712 Offset = 0;
5713 return I->getOperand(0);
5714 } else if (I->getOpcode() == Instruction::Add) {
5715 // We have X+C. Check to see if we really have (X*C2)+C1,
5716 // where C1 is divisible by C2.
5717 unsigned SubScale;
5718 Value *SubVal =
5719 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
5720 Offset += CUI->getZExtValue();
5721 if (SubScale > 1 && (Offset % SubScale == 0)) {
5722 Scale = SubScale;
5723 return SubVal;
Chris Lattnercfd65102005-10-29 04:36:15 +00005724 }
5725 }
5726 }
5727 }
5728 }
5729
5730 // Otherwise, we can't look past this.
5731 Scale = 1;
5732 Offset = 0;
5733 return Val;
5734}
5735
5736
Chris Lattnerb3f83972005-10-24 06:03:58 +00005737/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
5738/// try to eliminate the cast by moving the type information into the alloc.
5739Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
5740 AllocationInst &AI) {
5741 const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
Chris Lattner0ddac2a2005-10-27 05:53:56 +00005742 if (!PTy) return 0; // Not casting the allocation to a pointer type.
Chris Lattnerb3f83972005-10-24 06:03:58 +00005743
Chris Lattnerb53c2382005-10-24 06:22:12 +00005744 // Remove any uses of AI that are dead.
5745 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
5746 std::vector<Instruction*> DeadUsers;
5747 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
5748 Instruction *User = cast<Instruction>(*UI++);
5749 if (isInstructionTriviallyDead(User)) {
5750 while (UI != E && *UI == User)
5751 ++UI; // If this instruction uses AI more than once, don't break UI.
5752
5753 // Add operands to the worklist.
5754 AddUsesToWorkList(*User);
5755 ++NumDeadInst;
Bill Wendlingb7427032006-11-26 09:46:52 +00005756 DOUT << "IC: DCE: " << *User;
Chris Lattnerb53c2382005-10-24 06:22:12 +00005757
5758 User->eraseFromParent();
5759 removeFromWorkList(User);
5760 }
5761 }
5762
Chris Lattnerb3f83972005-10-24 06:03:58 +00005763 // Get the type really allocated and the type casted to.
5764 const Type *AllocElTy = AI.getAllocatedType();
5765 const Type *CastElTy = PTy->getElementType();
5766 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00005767
Chris Lattnere831b9a2006-10-01 19:40:58 +00005768 unsigned AllocElTyAlign = TD->getTypeAlignment(AllocElTy);
5769 unsigned CastElTyAlign = TD->getTypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00005770 if (CastElTyAlign < AllocElTyAlign) return 0;
5771
Chris Lattner39387a52005-10-24 06:35:18 +00005772 // If the allocation has multiple uses, only promote it if we are strictly
5773 // increasing the alignment of the resultant allocation. If we keep it the
5774 // same, we open the door to infinite loops of various kinds.
5775 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
5776
Chris Lattnerb3f83972005-10-24 06:03:58 +00005777 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
5778 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00005779 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00005780
Chris Lattner455fcc82005-10-29 03:19:53 +00005781 // See if we can satisfy the modulus by pulling a scale out of the array
5782 // size argument.
Chris Lattnercfd65102005-10-29 04:36:15 +00005783 unsigned ArraySizeScale, ArrayOffset;
5784 Value *NumElements = // See if the array size is a decomposable linear expr.
5785 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
5786
Chris Lattner455fcc82005-10-29 03:19:53 +00005787 // If we can now satisfy the modulus, by using a non-1 scale, we really can
5788 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00005789 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
5790 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00005791
Chris Lattner455fcc82005-10-29 03:19:53 +00005792 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
5793 Value *Amt = 0;
5794 if (Scale == 1) {
5795 Amt = NumElements;
5796 } else {
Reid Spencerb83eb642006-10-20 07:07:24 +00005797 // If the allocation size is constant, form a constant mul expression
Reid Spencerc5b206b2006-12-31 05:48:39 +00005798 Amt = ConstantInt::get(Type::Int32Ty, Scale);
5799 if (isa<ConstantInt>(NumElements))
Reid Spencerb83eb642006-10-20 07:07:24 +00005800 Amt = ConstantExpr::getMul(
5801 cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
5802 // otherwise multiply the amount and the number of elements
Chris Lattner455fcc82005-10-29 03:19:53 +00005803 else if (Scale != 1) {
5804 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
5805 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattner8142b0a2005-10-27 06:12:00 +00005806 }
Chris Lattner0ddac2a2005-10-27 05:53:56 +00005807 }
5808
Chris Lattnercfd65102005-10-29 04:36:15 +00005809 if (unsigned Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00005810 Value *Off = ConstantInt::get(Type::Int32Ty, Offset);
Chris Lattnercfd65102005-10-29 04:36:15 +00005811 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
5812 Amt = InsertNewInstBefore(Tmp, AI);
5813 }
5814
Chris Lattnerb3f83972005-10-24 06:03:58 +00005815 std::string Name = AI.getName(); AI.setName("");
5816 AllocationInst *New;
5817 if (isa<MallocInst>(AI))
Nate Begeman14b05292005-11-05 09:21:28 +00005818 New = new MallocInst(CastElTy, Amt, AI.getAlignment(), Name);
Chris Lattnerb3f83972005-10-24 06:03:58 +00005819 else
Nate Begeman14b05292005-11-05 09:21:28 +00005820 New = new AllocaInst(CastElTy, Amt, AI.getAlignment(), Name);
Chris Lattnerb3f83972005-10-24 06:03:58 +00005821 InsertNewInstBefore(New, AI);
Chris Lattner39387a52005-10-24 06:35:18 +00005822
5823 // If the allocation has multiple uses, insert a cast and change all things
5824 // that used it to use the new cast. This will also hack on CI, but it will
5825 // die soon.
5826 if (!AI.hasOneUse()) {
5827 AddUsesToWorkList(AI);
Reid Spencer3da59db2006-11-27 01:05:10 +00005828 // New is the allocation instruction, pointer typed. AI is the original
5829 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
5830 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner39387a52005-10-24 06:35:18 +00005831 InsertNewInstBefore(NewCast, AI);
5832 AI.replaceAllUsesWith(NewCast);
5833 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00005834 return ReplaceInstUsesWith(CI, New);
5835}
5836
Chris Lattner70074e02006-05-13 02:06:03 +00005837/// CanEvaluateInDifferentType - Return true if we can take the specified value
5838/// and return it without inserting any new casts. This is used by code that
5839/// tries to decide whether promoting or shrinking integer operations to wider
5840/// or smaller types will allow us to eliminate a truncate or extend.
5841static bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
5842 int &NumCastsRemoved) {
5843 if (isa<Constant>(V)) return true;
5844
5845 Instruction *I = dyn_cast<Instruction>(V);
5846 if (!I || !I->hasOneUse()) return false;
5847
5848 switch (I->getOpcode()) {
5849 case Instruction::And:
5850 case Instruction::Or:
5851 case Instruction::Xor:
5852 // These operators can all arbitrarily be extended or truncated.
5853 return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved) &&
5854 CanEvaluateInDifferentType(I->getOperand(1), Ty, NumCastsRemoved);
Chris Lattner46b96052006-11-29 07:18:39 +00005855 case Instruction::AShr:
5856 case Instruction::LShr:
5857 case Instruction::Shl:
5858 // If this is just a bitcast changing the sign of the operation, we can
5859 // convert if the operand can be converted.
5860 if (V->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
5861 return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved);
5862 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00005863 case Instruction::Trunc:
5864 case Instruction::ZExt:
5865 case Instruction::SExt:
5866 case Instruction::BitCast:
Chris Lattner70074e02006-05-13 02:06:03 +00005867 // If this is a cast from the destination type, we can trivially eliminate
5868 // it, and this will remove a cast overall.
5869 if (I->getOperand(0)->getType() == Ty) {
Chris Lattnerd2280182006-06-28 17:34:50 +00005870 // If the first operand is itself a cast, and is eliminable, do not count
5871 // this as an eliminable cast. We would prefer to eliminate those two
5872 // casts first.
Reid Spencer3ed469c2006-11-02 20:25:50 +00005873 if (isa<CastInst>(I->getOperand(0)))
Chris Lattnerd2280182006-06-28 17:34:50 +00005874 return true;
5875
Chris Lattner70074e02006-05-13 02:06:03 +00005876 ++NumCastsRemoved;
5877 return true;
5878 }
Reid Spencer3da59db2006-11-27 01:05:10 +00005879 break;
5880 default:
Chris Lattner70074e02006-05-13 02:06:03 +00005881 // TODO: Can handle more cases here.
5882 break;
5883 }
5884
5885 return false;
5886}
5887
5888/// EvaluateInDifferentType - Given an expression that
5889/// CanEvaluateInDifferentType returns true for, actually insert the code to
5890/// evaluate the expression.
Reid Spencerc55b2432006-12-13 18:21:21 +00005891Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
5892 bool isSigned ) {
Chris Lattner70074e02006-05-13 02:06:03 +00005893 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencerc55b2432006-12-13 18:21:21 +00005894 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Chris Lattner70074e02006-05-13 02:06:03 +00005895
5896 // Otherwise, it must be an instruction.
5897 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00005898 Instruction *Res = 0;
Chris Lattner70074e02006-05-13 02:06:03 +00005899 switch (I->getOpcode()) {
5900 case Instruction::And:
5901 case Instruction::Or:
5902 case Instruction::Xor: {
Reid Spencerc55b2432006-12-13 18:21:21 +00005903 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
5904 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Chris Lattner70074e02006-05-13 02:06:03 +00005905 Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
5906 LHS, RHS, I->getName());
5907 break;
5908 }
Chris Lattner46b96052006-11-29 07:18:39 +00005909 case Instruction::AShr:
5910 case Instruction::LShr:
5911 case Instruction::Shl: {
Reid Spencerc55b2432006-12-13 18:21:21 +00005912 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattner46b96052006-11-29 07:18:39 +00005913 Res = new ShiftInst((Instruction::OtherOps)I->getOpcode(), LHS,
5914 I->getOperand(1), I->getName());
5915 break;
5916 }
Reid Spencer3da59db2006-11-27 01:05:10 +00005917 case Instruction::Trunc:
5918 case Instruction::ZExt:
5919 case Instruction::SExt:
5920 case Instruction::BitCast:
5921 // If the source type of the cast is the type we're trying for then we can
5922 // just return the source. There's no need to insert it because its not new.
Chris Lattner70074e02006-05-13 02:06:03 +00005923 if (I->getOperand(0)->getType() == Ty)
5924 return I->getOperand(0);
5925
Reid Spencer3da59db2006-11-27 01:05:10 +00005926 // Some other kind of cast, which shouldn't happen, so just ..
5927 // FALL THROUGH
5928 default:
Chris Lattner70074e02006-05-13 02:06:03 +00005929 // TODO: Can handle more cases here.
5930 assert(0 && "Unreachable!");
5931 break;
5932 }
5933
5934 return InsertNewInstBefore(Res, *I);
5935}
5936
Reid Spencer3da59db2006-11-27 01:05:10 +00005937/// @brief Implement the transforms common to all CastInst visitors.
5938Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00005939 Value *Src = CI.getOperand(0);
5940
Reid Spencer3da59db2006-11-27 01:05:10 +00005941 // Casting undef to anything results in undef so might as just replace it and
5942 // get rid of the cast.
Chris Lattnere87597f2004-10-16 18:11:37 +00005943 if (isa<UndefValue>(Src)) // cast undef -> undef
5944 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
5945
Reid Spencer3da59db2006-11-27 01:05:10 +00005946 // Many cases of "cast of a cast" are eliminable. If its eliminable we just
5947 // eliminate it now.
Chris Lattner6e7ba452005-01-01 16:22:27 +00005948 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00005949 if (Instruction::CastOps opc =
5950 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
5951 // The first cast (CSrc) is eliminable so we need to fix up or replace
5952 // the second cast (CI). CSrc will then have a good chance of being dead.
5953 return CastInst::create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner8fd217c2002-08-02 20:00:25 +00005954 }
5955 }
Chris Lattnera710ddc2004-05-25 04:29:21 +00005956
Chris Lattner797249b2003-06-21 23:12:02 +00005957 // If casting the result of a getelementptr instruction with no offset, turn
5958 // this into a cast of the original pointer!
5959 //
Chris Lattner79d35b32003-06-23 21:59:52 +00005960 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner797249b2003-06-21 23:12:02 +00005961 bool AllZeroOperands = true;
5962 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
5963 if (!isa<Constant>(GEP->getOperand(i)) ||
5964 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
5965 AllZeroOperands = false;
5966 break;
5967 }
5968 if (AllZeroOperands) {
Reid Spencer3da59db2006-11-27 01:05:10 +00005969 // Changing the cast operand is usually not a good idea but it is safe
5970 // here because the pointer operand is being replaced with another
5971 // pointer operand so the opcode doesn't need to change.
Chris Lattner797249b2003-06-21 23:12:02 +00005972 CI.setOperand(0, GEP->getOperand(0));
5973 return &CI;
5974 }
5975 }
Chris Lattner13c654a2006-11-21 17:05:13 +00005976
Chris Lattnerbc61e662003-11-02 05:57:39 +00005977 // If we are casting a malloc or alloca to a pointer to a type of the same
5978 // size, rewrite the allocation instruction to allocate the "right" type.
Chris Lattnerbc61e662003-11-02 05:57:39 +00005979 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattnerb3f83972005-10-24 06:03:58 +00005980 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
5981 return V;
Chris Lattnerbc61e662003-11-02 05:57:39 +00005982
Reid Spencer3da59db2006-11-27 01:05:10 +00005983 // If we are casting a select then fold the cast into the select
Chris Lattner6e7ba452005-01-01 16:22:27 +00005984 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
5985 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
5986 return NV;
Reid Spencer3da59db2006-11-27 01:05:10 +00005987
5988 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner4e998b22004-09-29 05:07:12 +00005989 if (isa<PHINode>(Src))
5990 if (Instruction *NV = FoldOpIntoPhi(CI))
5991 return NV;
Chris Lattner9fb92132006-04-12 18:09:35 +00005992
Reid Spencer3da59db2006-11-27 01:05:10 +00005993 return 0;
5994}
5995
5996/// Only the TRUNC, ZEXT, SEXT, and BITCONVERT can have both operands as
5997/// integers. This function implements the common transforms for all those
5998/// cases.
5999/// @brief Implement the transforms common to CastInst with integer operands
6000Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
6001 if (Instruction *Result = commonCastTransforms(CI))
6002 return Result;
6003
6004 Value *Src = CI.getOperand(0);
6005 const Type *SrcTy = Src->getType();
6006 const Type *DestTy = CI.getType();
6007 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
6008 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
6009
Reid Spencer3da59db2006-11-27 01:05:10 +00006010 // See if we can simplify any instructions used by the LHS whose sole
6011 // purpose is to compute bits we don't care about.
6012 uint64_t KnownZero = 0, KnownOne = 0;
6013 if (SimplifyDemandedBits(&CI, DestTy->getIntegralTypeMask(),
6014 KnownZero, KnownOne))
6015 return &CI;
6016
6017 // If the source isn't an instruction or has more than one use then we
6018 // can't do anything more.
Reid Spencere4d87aa2006-12-23 06:05:41 +00006019 Instruction *SrcI = dyn_cast<Instruction>(Src);
6020 if (!SrcI || !Src->hasOneUse())
Reid Spencer3da59db2006-11-27 01:05:10 +00006021 return 0;
6022
6023 // Attempt to propagate the cast into the instruction.
Reid Spencer3da59db2006-11-27 01:05:10 +00006024 int NumCastsRemoved = 0;
6025 if (CanEvaluateInDifferentType(SrcI, DestTy, NumCastsRemoved)) {
6026 // If this cast is a truncate, evaluting in a different type always
6027 // eliminates the cast, so it is always a win. If this is a noop-cast
6028 // this just removes a noop cast which isn't pointful, but simplifies
6029 // the code. If this is a zero-extension, we need to do an AND to
6030 // maintain the clear top-part of the computation, so we require that
6031 // the input have eliminated at least one cast. If this is a sign
6032 // extension, we insert two new casts (to do the extension) so we
6033 // require that two casts have been eliminated.
6034 bool DoXForm = CI.isNoopCast(TD->getIntPtrType());
6035 if (!DoXForm) {
6036 switch (CI.getOpcode()) {
6037 case Instruction::Trunc:
6038 DoXForm = true;
6039 break;
6040 case Instruction::ZExt:
6041 DoXForm = NumCastsRemoved >= 1;
6042 break;
6043 case Instruction::SExt:
6044 DoXForm = NumCastsRemoved >= 2;
6045 break;
6046 case Instruction::BitCast:
6047 DoXForm = false;
6048 break;
6049 default:
6050 // All the others use floating point so we shouldn't actually
6051 // get here because of the check above.
6052 assert(!"Unknown cast type .. unreachable");
6053 break;
6054 }
6055 }
6056
6057 if (DoXForm) {
Reid Spencerc55b2432006-12-13 18:21:21 +00006058 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
6059 CI.getOpcode() == Instruction::SExt);
Reid Spencer3da59db2006-11-27 01:05:10 +00006060 assert(Res->getType() == DestTy);
6061 switch (CI.getOpcode()) {
6062 default: assert(0 && "Unknown cast type!");
6063 case Instruction::Trunc:
6064 case Instruction::BitCast:
6065 // Just replace this cast with the result.
6066 return ReplaceInstUsesWith(CI, Res);
6067 case Instruction::ZExt: {
6068 // We need to emit an AND to clear the high bits.
6069 assert(SrcBitSize < DestBitSize && "Not a zext?");
6070 Constant *C =
Reid Spencerc5b206b2006-12-31 05:48:39 +00006071 ConstantInt::get(Type::Int64Ty, (1ULL << SrcBitSize)-1);
Reid Spencer3da59db2006-11-27 01:05:10 +00006072 if (DestBitSize < 64)
6073 C = ConstantExpr::getTrunc(C, DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00006074 return BinaryOperator::createAnd(Res, C);
6075 }
6076 case Instruction::SExt:
6077 // We need to emit a cast to truncate, then a cast to sext.
6078 return CastInst::create(Instruction::SExt,
Reid Spencer17212df2006-12-12 09:18:51 +00006079 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
6080 CI), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00006081 }
6082 }
6083 }
6084
6085 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
6086 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
6087
6088 switch (SrcI->getOpcode()) {
6089 case Instruction::Add:
6090 case Instruction::Mul:
6091 case Instruction::And:
6092 case Instruction::Or:
6093 case Instruction::Xor:
6094 // If we are discarding information, or just changing the sign,
6095 // rewrite.
6096 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
6097 // Don't insert two casts if they cannot be eliminated. We allow
6098 // two casts to be inserted if the sizes are the same. This could
6099 // only be converting signedness, which is a noop.
6100 if (DestBitSize == SrcBitSize ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00006101 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
6102 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer7eb76382006-12-13 17:19:09 +00006103 Instruction::CastOps opcode = CI.getOpcode();
Reid Spencer17212df2006-12-12 09:18:51 +00006104 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
6105 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
6106 return BinaryOperator::create(
6107 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00006108 }
6109 }
6110
6111 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
6112 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
6113 SrcI->getOpcode() == Instruction::Xor &&
6114 Op1 == ConstantBool::getTrue() &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00006115 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Reid Spencer17212df2006-12-12 09:18:51 +00006116 Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00006117 return BinaryOperator::createXor(New, ConstantInt::get(CI.getType(), 1));
6118 }
6119 break;
6120 case Instruction::SDiv:
6121 case Instruction::UDiv:
6122 case Instruction::SRem:
6123 case Instruction::URem:
6124 // If we are just changing the sign, rewrite.
6125 if (DestBitSize == SrcBitSize) {
6126 // Don't insert two casts if they cannot be eliminated. We allow
6127 // two casts to be inserted if the sizes are the same. This could
6128 // only be converting signedness, which is a noop.
Reid Spencere4d87aa2006-12-23 06:05:41 +00006129 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
6130 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer17212df2006-12-12 09:18:51 +00006131 Value *Op0c = InsertOperandCastBefore(Instruction::BitCast,
6132 Op0, DestTy, SrcI);
6133 Value *Op1c = InsertOperandCastBefore(Instruction::BitCast,
6134 Op1, DestTy, SrcI);
Reid Spencer3da59db2006-11-27 01:05:10 +00006135 return BinaryOperator::create(
6136 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
6137 }
6138 }
6139 break;
6140
6141 case Instruction::Shl:
6142 // Allow changing the sign of the source operand. Do not allow
6143 // changing the size of the shift, UNLESS the shift amount is a
6144 // constant. We must not change variable sized shifts to a smaller
6145 // size, because it is undefined to shift more bits out than exist
6146 // in the value.
6147 if (DestBitSize == SrcBitSize ||
6148 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
Reid Spencer17212df2006-12-12 09:18:51 +00006149 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
6150 Instruction::BitCast : Instruction::Trunc);
6151 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
Reid Spencer3da59db2006-11-27 01:05:10 +00006152 return new ShiftInst(Instruction::Shl, Op0c, Op1);
6153 }
6154 break;
6155 case Instruction::AShr:
6156 // If this is a signed shr, and if all bits shifted in are about to be
6157 // truncated off, turn it into an unsigned shr to allow greater
6158 // simplifications.
6159 if (DestBitSize < SrcBitSize &&
6160 isa<ConstantInt>(Op1)) {
6161 unsigned ShiftAmt = cast<ConstantInt>(Op1)->getZExtValue();
6162 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
6163 // Insert the new logical shift right.
6164 return new ShiftInst(Instruction::LShr, Op0, Op1);
6165 }
6166 }
6167 break;
6168
Reid Spencere4d87aa2006-12-23 06:05:41 +00006169 case Instruction::ICmp:
6170 // If we are just checking for a icmp eq of a single bit and casting it
6171 // to an integer, then shift the bit to the appropriate place and then
Reid Spencer3da59db2006-11-27 01:05:10 +00006172 // cast to integer to avoid the comparison.
6173 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
6174 uint64_t Op1CV = Op1C->getZExtValue();
6175 // cast (X == 0) to int --> X^1 iff X has only the low bit set.
6176 // cast (X == 0) to int --> (X>>1)^1 iff X has only the 2nd bit set.
6177 // cast (X == 1) to int --> X iff X has only the low bit set.
6178 // cast (X == 2) to int --> X>>1 iff X has only the 2nd bit set.
6179 // cast (X != 0) to int --> X iff X has only the low bit set.
6180 // cast (X != 0) to int --> X>>1 iff X has only the 2nd bit set.
6181 // cast (X != 1) to int --> X^1 iff X has only the low bit set.
6182 // cast (X != 2) to int --> (X>>1)^1 iff X has only the 2nd bit set.
6183 if (Op1CV == 0 || isPowerOf2_64(Op1CV)) {
6184 // If Op1C some other power of two, convert:
6185 uint64_t KnownZero, KnownOne;
6186 uint64_t TypeMask = Op1->getType()->getIntegralTypeMask();
6187 ComputeMaskedBits(Op0, TypeMask, KnownZero, KnownOne);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006188
6189 // This only works for EQ and NE
6190 ICmpInst::Predicate pred = cast<ICmpInst>(SrcI)->getPredicate();
6191 if (pred != ICmpInst::ICMP_NE && pred != ICmpInst::ICMP_EQ)
6192 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00006193
6194 if (isPowerOf2_64(KnownZero^TypeMask)) { // Exactly 1 possible 1?
Reid Spencere4d87aa2006-12-23 06:05:41 +00006195 bool isNE = pred == ICmpInst::ICMP_NE;
Reid Spencer3da59db2006-11-27 01:05:10 +00006196 if (Op1CV && (Op1CV != (KnownZero^TypeMask))) {
6197 // (X&4) == 2 --> false
6198 // (X&4) != 2 --> true
Reid Spencere4d87aa2006-12-23 06:05:41 +00006199 Constant *Res = ConstantBool::get(isNE);
Reid Spencerd977d862006-12-12 23:36:14 +00006200 Res = ConstantExpr::getZExt(Res, CI.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00006201 return ReplaceInstUsesWith(CI, Res);
6202 }
6203
6204 unsigned ShiftAmt = Log2_64(KnownZero^TypeMask);
6205 Value *In = Op0;
6206 if (ShiftAmt) {
6207 // Perform a logical shr by shiftamt.
6208 // Insert the shift to put the result in the low bit.
6209 In = InsertNewInstBefore(
6210 new ShiftInst(Instruction::LShr, In,
Reid Spencerc5b206b2006-12-31 05:48:39 +00006211 ConstantInt::get(Type::Int8Ty, ShiftAmt),
Reid Spencer3da59db2006-11-27 01:05:10 +00006212 In->getName()+".lobit"), CI);
6213 }
6214
Reid Spencere4d87aa2006-12-23 06:05:41 +00006215 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
Reid Spencer3da59db2006-11-27 01:05:10 +00006216 Constant *One = ConstantInt::get(In->getType(), 1);
6217 In = BinaryOperator::createXor(In, One, "tmp");
6218 InsertNewInstBefore(cast<Instruction>(In), CI);
6219 }
6220
6221 if (CI.getType() == In->getType())
6222 return ReplaceInstUsesWith(CI, In);
6223 else
Reid Spencerd977d862006-12-12 23:36:14 +00006224 return CastInst::createIntegerCast(In, CI.getType(), false/*ZExt*/);
Reid Spencer3da59db2006-11-27 01:05:10 +00006225 }
6226 }
6227 }
6228 break;
6229 }
6230 return 0;
6231}
6232
6233Instruction *InstCombiner::visitTrunc(CastInst &CI) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00006234 if (Instruction *Result = commonIntCastTransforms(CI))
6235 return Result;
6236
6237 Value *Src = CI.getOperand(0);
6238 const Type *Ty = CI.getType();
6239 unsigned DestBitWidth = Ty->getPrimitiveSizeInBits();
6240
6241 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
6242 switch (SrcI->getOpcode()) {
6243 default: break;
6244 case Instruction::LShr:
6245 // We can shrink lshr to something smaller if we know the bits shifted in
6246 // are already zeros.
6247 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
6248 unsigned ShAmt = ShAmtV->getZExtValue();
6249
6250 // Get a mask for the bits shifting in.
6251 uint64_t Mask = (~0ULL >> (64-ShAmt)) << DestBitWidth;
Reid Spencer17212df2006-12-12 09:18:51 +00006252 Value* SrcIOp0 = SrcI->getOperand(0);
6253 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00006254 if (ShAmt >= DestBitWidth) // All zeros.
6255 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
6256
6257 // Okay, we can shrink this. Truncate the input, then return a new
6258 // shift.
Reid Spencer7eb76382006-12-13 17:19:09 +00006259 Value *V = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00006260 return new ShiftInst(Instruction::LShr, V, SrcI->getOperand(1));
6261 }
Chris Lattnere13ab2a2006-12-05 01:26:29 +00006262 } else { // This is a variable shr.
6263
6264 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
6265 // more LLVM instructions, but allows '1 << Y' to be hoisted if
6266 // loop-invariant and CSE'd.
6267 if (CI.getType() == Type::BoolTy && SrcI->hasOneUse()) {
6268 Value *One = ConstantInt::get(SrcI->getType(), 1);
6269
6270 Value *V = InsertNewInstBefore(new ShiftInst(Instruction::Shl, One,
6271 SrcI->getOperand(1),
6272 "tmp"), CI);
6273 V = InsertNewInstBefore(BinaryOperator::createAnd(V,
6274 SrcI->getOperand(0),
6275 "tmp"), CI);
6276 Value *Zero = Constant::getNullValue(V->getType());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006277 return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
Chris Lattnere13ab2a2006-12-05 01:26:29 +00006278 }
Chris Lattner6aa5eb12006-11-29 07:04:07 +00006279 }
6280 break;
6281 }
6282 }
6283
6284 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00006285}
6286
6287Instruction *InstCombiner::visitZExt(CastInst &CI) {
6288 // If one of the common conversion will work ..
6289 if (Instruction *Result = commonIntCastTransforms(CI))
6290 return Result;
6291
6292 Value *Src = CI.getOperand(0);
6293
6294 // If this is a cast of a cast
6295 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00006296 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
6297 // types and if the sizes are just right we can convert this into a logical
6298 // 'and' which will be much cheaper than the pair of casts.
6299 if (isa<TruncInst>(CSrc)) {
6300 // Get the sizes of the types involved
6301 Value *A = CSrc->getOperand(0);
6302 unsigned SrcSize = A->getType()->getPrimitiveSizeInBits();
6303 unsigned MidSize = CSrc->getType()->getPrimitiveSizeInBits();
6304 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
6305 // If we're actually extending zero bits and the trunc is a no-op
6306 if (MidSize < DstSize && SrcSize == DstSize) {
6307 // Replace both of the casts with an And of the type mask.
6308 uint64_t AndValue = CSrc->getType()->getIntegralTypeMask();
6309 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
6310 Instruction *And =
6311 BinaryOperator::createAnd(CSrc->getOperand(0), AndConst);
6312 // Unfortunately, if the type changed, we need to cast it back.
6313 if (And->getType() != CI.getType()) {
6314 And->setName(CSrc->getName()+".mask");
6315 InsertNewInstBefore(And, CI);
Reid Spencerd977d862006-12-12 23:36:14 +00006316 And = CastInst::createIntegerCast(And, CI.getType(), false/*ZExt*/);
Reid Spencer3da59db2006-11-27 01:05:10 +00006317 }
6318 return And;
6319 }
6320 }
6321 }
6322
6323 return 0;
6324}
6325
6326Instruction *InstCombiner::visitSExt(CastInst &CI) {
6327 return commonIntCastTransforms(CI);
6328}
6329
6330Instruction *InstCombiner::visitFPTrunc(CastInst &CI) {
6331 return commonCastTransforms(CI);
6332}
6333
6334Instruction *InstCombiner::visitFPExt(CastInst &CI) {
6335 return commonCastTransforms(CI);
6336}
6337
6338Instruction *InstCombiner::visitFPToUI(CastInst &CI) {
Reid Spencer44c030a2006-11-30 23:13:36 +00006339 return commonCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00006340}
6341
6342Instruction *InstCombiner::visitFPToSI(CastInst &CI) {
Reid Spencer44c030a2006-11-30 23:13:36 +00006343 return commonCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00006344}
6345
6346Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
6347 return commonCastTransforms(CI);
6348}
6349
6350Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
6351 return commonCastTransforms(CI);
6352}
6353
6354Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
Reid Spencer44c030a2006-11-30 23:13:36 +00006355 return commonCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00006356}
6357
6358Instruction *InstCombiner::visitIntToPtr(CastInst &CI) {
6359 return commonCastTransforms(CI);
6360}
6361
6362Instruction *InstCombiner::visitBitCast(CastInst &CI) {
6363
6364 // If the operands are integer typed then apply the integer transforms,
6365 // otherwise just apply the common ones.
6366 Value *Src = CI.getOperand(0);
6367 const Type *SrcTy = Src->getType();
6368 const Type *DestTy = CI.getType();
6369
6370 if (SrcTy->isInteger() && DestTy->isInteger()) {
6371 if (Instruction *Result = commonIntCastTransforms(CI))
6372 return Result;
6373 } else {
6374 if (Instruction *Result = commonCastTransforms(CI))
6375 return Result;
6376 }
6377
6378
6379 // Get rid of casts from one type to the same type. These are useless and can
6380 // be replaced by the operand.
6381 if (DestTy == Src->getType())
6382 return ReplaceInstUsesWith(CI, Src);
6383
Chris Lattner9fb92132006-04-12 18:09:35 +00006384 // If the source and destination are pointers, and this cast is equivalent to
6385 // a getelementptr X, 0, 0, 0... turn it into the appropriate getelementptr.
6386 // This can enhance SROA and other transforms that want type-safe pointers.
Reid Spencer3da59db2006-11-27 01:05:10 +00006387 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
6388 if (const PointerType *SrcPTy = dyn_cast<PointerType>(SrcTy)) {
6389 const Type *DstElTy = DstPTy->getElementType();
6390 const Type *SrcElTy = SrcPTy->getElementType();
Chris Lattner9fb92132006-04-12 18:09:35 +00006391
Reid Spencerc5b206b2006-12-31 05:48:39 +00006392 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
Chris Lattner9fb92132006-04-12 18:09:35 +00006393 unsigned NumZeros = 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00006394 while (SrcElTy != DstElTy &&
6395 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
6396 SrcElTy->getNumContainedTypes() /* not "{}" */) {
6397 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
Chris Lattner9fb92132006-04-12 18:09:35 +00006398 ++NumZeros;
6399 }
Chris Lattner4e998b22004-09-29 05:07:12 +00006400
Chris Lattner9fb92132006-04-12 18:09:35 +00006401 // If we found a path from the src to dest, create the getelementptr now.
Reid Spencer3da59db2006-11-27 01:05:10 +00006402 if (SrcElTy == DstElTy) {
Chris Lattner9fb92132006-04-12 18:09:35 +00006403 std::vector<Value*> Idxs(NumZeros+1, ZeroUInt);
6404 return new GetElementPtrInst(Src, Idxs);
6405 }
6406 }
Reid Spencer3da59db2006-11-27 01:05:10 +00006407 }
Chris Lattner24c8e382003-07-24 17:35:25 +00006408
Reid Spencer3da59db2006-11-27 01:05:10 +00006409 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
6410 if (SVI->hasOneUse()) {
6411 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
6412 // a bitconvert to a vector with the same # elts.
6413 if (isa<PackedType>(DestTy) &&
6414 cast<PackedType>(DestTy)->getNumElements() ==
6415 SVI->getType()->getNumElements()) {
6416 CastInst *Tmp;
6417 // If either of the operands is a cast from CI.getType(), then
6418 // evaluating the shuffle in the casted destination's type will allow
6419 // us to eliminate at least one cast.
6420 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
6421 Tmp->getOperand(0)->getType() == DestTy) ||
6422 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
6423 Tmp->getOperand(0)->getType() == DestTy)) {
Reid Spencer17212df2006-12-12 09:18:51 +00006424 Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
6425 SVI->getOperand(0), DestTy, &CI);
6426 Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
6427 SVI->getOperand(1), DestTy, &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00006428 // Return a new shuffle vector. Use the same element ID's, as we
6429 // know the vector types match #elts.
6430 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner01575b72006-05-25 23:24:33 +00006431 }
6432 }
6433 }
6434 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00006435 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00006436}
6437
Chris Lattnere576b912004-04-09 23:46:01 +00006438/// GetSelectFoldableOperands - We want to turn code that looks like this:
6439/// %C = or %A, %B
6440/// %D = select %cond, %C, %A
6441/// into:
6442/// %C = select %cond, %B, 0
6443/// %D = or %A, %C
6444///
6445/// Assuming that the specified instruction is an operand to the select, return
6446/// a bitmask indicating which operands of this instruction are foldable if they
6447/// equal the other incoming value of the select.
6448///
6449static unsigned GetSelectFoldableOperands(Instruction *I) {
6450 switch (I->getOpcode()) {
6451 case Instruction::Add:
6452 case Instruction::Mul:
6453 case Instruction::And:
6454 case Instruction::Or:
6455 case Instruction::Xor:
6456 return 3; // Can fold through either operand.
6457 case Instruction::Sub: // Can only fold on the amount subtracted.
6458 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencer3822ff52006-11-08 06:47:33 +00006459 case Instruction::LShr:
6460 case Instruction::AShr:
Misha Brukmanfd939082005-04-21 23:48:37 +00006461 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00006462 default:
6463 return 0; // Cannot fold
6464 }
6465}
6466
6467/// GetSelectFoldableConstant - For the same transformation as the previous
6468/// function, return the identity constant that goes into the select.
6469static Constant *GetSelectFoldableConstant(Instruction *I) {
6470 switch (I->getOpcode()) {
6471 default: assert(0 && "This cannot happen!"); abort();
6472 case Instruction::Add:
6473 case Instruction::Sub:
6474 case Instruction::Or:
6475 case Instruction::Xor:
6476 return Constant::getNullValue(I->getType());
6477 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00006478 case Instruction::LShr:
6479 case Instruction::AShr:
Reid Spencerc5b206b2006-12-31 05:48:39 +00006480 return Constant::getNullValue(Type::Int8Ty);
Chris Lattnere576b912004-04-09 23:46:01 +00006481 case Instruction::And:
6482 return ConstantInt::getAllOnesValue(I->getType());
6483 case Instruction::Mul:
6484 return ConstantInt::get(I->getType(), 1);
6485 }
6486}
6487
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00006488/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
6489/// have the same opcode and only one use each. Try to simplify this.
6490Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
6491 Instruction *FI) {
6492 if (TI->getNumOperands() == 1) {
6493 // If this is a non-volatile load or a cast from the same type,
6494 // merge.
Reid Spencer3da59db2006-11-27 01:05:10 +00006495 if (TI->isCast()) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00006496 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
6497 return 0;
6498 } else {
6499 return 0; // unknown unary op.
6500 }
Misha Brukmanfd939082005-04-21 23:48:37 +00006501
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00006502 // Fold this by inserting a select from the input values.
6503 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
6504 FI->getOperand(0), SI.getName()+".v");
6505 InsertNewInstBefore(NewSI, SI);
Reid Spencer3da59db2006-11-27 01:05:10 +00006506 return CastInst::create(Instruction::CastOps(TI->getOpcode()), NewSI,
6507 TI->getType());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00006508 }
6509
Reid Spencere4d87aa2006-12-23 06:05:41 +00006510 // Only handle binary, compare and shift operators here.
Reid Spencer1b0d8472006-12-23 18:58:04 +00006511 if (!isa<ShiftInst>(TI) && !isa<BinaryOperator>(TI))
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00006512 return 0;
6513
6514 // Figure out if the operations have any operands in common.
6515 Value *MatchOp, *OtherOpT, *OtherOpF;
6516 bool MatchIsOpZero;
6517 if (TI->getOperand(0) == FI->getOperand(0)) {
6518 MatchOp = TI->getOperand(0);
6519 OtherOpT = TI->getOperand(1);
6520 OtherOpF = FI->getOperand(1);
6521 MatchIsOpZero = true;
6522 } else if (TI->getOperand(1) == FI->getOperand(1)) {
6523 MatchOp = TI->getOperand(1);
6524 OtherOpT = TI->getOperand(0);
6525 OtherOpF = FI->getOperand(0);
6526 MatchIsOpZero = false;
6527 } else if (!TI->isCommutative()) {
6528 return 0;
6529 } else if (TI->getOperand(0) == FI->getOperand(1)) {
6530 MatchOp = TI->getOperand(0);
6531 OtherOpT = TI->getOperand(1);
6532 OtherOpF = FI->getOperand(0);
6533 MatchIsOpZero = true;
6534 } else if (TI->getOperand(1) == FI->getOperand(0)) {
6535 MatchOp = TI->getOperand(1);
6536 OtherOpT = TI->getOperand(0);
6537 OtherOpF = FI->getOperand(1);
6538 MatchIsOpZero = true;
6539 } else {
6540 return 0;
6541 }
6542
6543 // If we reach here, they do have operations in common.
6544 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
6545 OtherOpF, SI.getName()+".v");
6546 InsertNewInstBefore(NewSI, SI);
6547
6548 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
6549 if (MatchIsOpZero)
6550 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
6551 else
6552 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00006553 }
Reid Spencer1b0d8472006-12-23 18:58:04 +00006554
6555 assert(isa<ShiftInst>(TI) && "Should only have Shift here");
6556 if (MatchIsOpZero)
6557 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), MatchOp, NewSI);
6558 else
6559 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), NewSI, MatchOp);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00006560}
6561
Chris Lattner3d69f462004-03-12 05:52:32 +00006562Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00006563 Value *CondVal = SI.getCondition();
6564 Value *TrueVal = SI.getTrueValue();
6565 Value *FalseVal = SI.getFalseValue();
6566
6567 // select true, X, Y -> X
6568 // select false, X, Y -> Y
6569 if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
Chris Lattner47811b72006-09-28 23:35:22 +00006570 return ReplaceInstUsesWith(SI, C->getValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00006571
6572 // select C, X, X -> X
6573 if (TrueVal == FalseVal)
6574 return ReplaceInstUsesWith(SI, TrueVal);
6575
Chris Lattnere87597f2004-10-16 18:11:37 +00006576 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
6577 return ReplaceInstUsesWith(SI, FalseVal);
6578 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
6579 return ReplaceInstUsesWith(SI, TrueVal);
6580 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
6581 if (isa<Constant>(TrueVal))
6582 return ReplaceInstUsesWith(SI, TrueVal);
6583 else
6584 return ReplaceInstUsesWith(SI, FalseVal);
6585 }
6586
Chris Lattner0c199a72004-04-08 04:43:23 +00006587 if (SI.getType() == Type::BoolTy)
6588 if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
Chris Lattner47811b72006-09-28 23:35:22 +00006589 if (C->getValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00006590 // Change: A = select B, true, C --> A = or B, C
Chris Lattner48595f12004-06-10 02:07:29 +00006591 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00006592 } else {
6593 // Change: A = select B, false, C --> A = and !B, C
6594 Value *NotCond =
6595 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6596 "not."+CondVal->getName()), SI);
Chris Lattner48595f12004-06-10 02:07:29 +00006597 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00006598 }
6599 } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
Chris Lattner47811b72006-09-28 23:35:22 +00006600 if (C->getValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00006601 // Change: A = select B, C, false --> A = and B, C
Chris Lattner48595f12004-06-10 02:07:29 +00006602 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00006603 } else {
6604 // Change: A = select B, C, true --> A = or !B, C
6605 Value *NotCond =
6606 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6607 "not."+CondVal->getName()), SI);
Chris Lattner48595f12004-06-10 02:07:29 +00006608 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00006609 }
6610 }
6611
Chris Lattner2eefe512004-04-09 19:05:30 +00006612 // Selecting between two integer constants?
6613 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
6614 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
6615 // select C, 1, 0 -> cast C to int
Reid Spencerb83eb642006-10-20 07:07:24 +00006616 if (FalseValC->isNullValue() && TrueValC->getZExtValue() == 1) {
Reid Spencer3da59db2006-11-27 01:05:10 +00006617 return CastInst::create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencerb83eb642006-10-20 07:07:24 +00006618 } else if (TrueValC->isNullValue() && FalseValC->getZExtValue() == 1) {
Chris Lattner2eefe512004-04-09 19:05:30 +00006619 // select C, 0, 1 -> cast !C to int
6620 Value *NotCond =
6621 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00006622 "not."+CondVal->getName()), SI);
Reid Spencer3da59db2006-11-27 01:05:10 +00006623 return CastInst::create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00006624 }
Chris Lattner457dd822004-06-09 07:59:58 +00006625
Reid Spencere4d87aa2006-12-23 06:05:41 +00006626 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattnerb8456462006-09-20 04:44:59 +00006627
Reid Spencere4d87aa2006-12-23 06:05:41 +00006628 // (x <s 0) ? -1 : 0 -> ashr x, 31
6629 // (x >u 2147483647) ? -1 : 0 -> ashr x, 31
Chris Lattnerb8456462006-09-20 04:44:59 +00006630 if (TrueValC->isAllOnesValue() && FalseValC->isNullValue())
6631 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
6632 bool CanXForm = false;
Reid Spencere4d87aa2006-12-23 06:05:41 +00006633 if (IC->isSignedPredicate())
Chris Lattnerb8456462006-09-20 04:44:59 +00006634 CanXForm = CmpCst->isNullValue() &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00006635 IC->getPredicate() == ICmpInst::ICMP_SLT;
Chris Lattnerb8456462006-09-20 04:44:59 +00006636 else {
6637 unsigned Bits = CmpCst->getType()->getPrimitiveSizeInBits();
Reid Spencerb83eb642006-10-20 07:07:24 +00006638 CanXForm = (CmpCst->getZExtValue() == ~0ULL >> (64-Bits+1)) &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00006639 IC->getPredicate() == ICmpInst::ICMP_UGT;
Chris Lattnerb8456462006-09-20 04:44:59 +00006640 }
6641
6642 if (CanXForm) {
6643 // The comparison constant and the result are not neccessarily the
Reid Spencer3da59db2006-11-27 01:05:10 +00006644 // same width. Make an all-ones value by inserting a AShr.
Chris Lattnerb8456462006-09-20 04:44:59 +00006645 Value *X = IC->getOperand(0);
Chris Lattnerb8456462006-09-20 04:44:59 +00006646 unsigned Bits = X->getType()->getPrimitiveSizeInBits();
Reid Spencerc5b206b2006-12-31 05:48:39 +00006647 Constant *ShAmt = ConstantInt::get(Type::Int8Ty, Bits-1);
Reid Spencer3822ff52006-11-08 06:47:33 +00006648 Instruction *SRA = new ShiftInst(Instruction::AShr, X,
Chris Lattnerb8456462006-09-20 04:44:59 +00006649 ShAmt, "ones");
6650 InsertNewInstBefore(SRA, SI);
6651
Reid Spencer3da59db2006-11-27 01:05:10 +00006652 // Finally, convert to the type of the select RHS. We figure out
6653 // if this requires a SExt, Trunc or BitCast based on the sizes.
6654 Instruction::CastOps opc = Instruction::BitCast;
6655 unsigned SRASize = SRA->getType()->getPrimitiveSizeInBits();
6656 unsigned SISize = SI.getType()->getPrimitiveSizeInBits();
6657 if (SRASize < SISize)
6658 opc = Instruction::SExt;
6659 else if (SRASize > SISize)
6660 opc = Instruction::Trunc;
6661 return CastInst::create(opc, SRA, SI.getType());
Chris Lattnerb8456462006-09-20 04:44:59 +00006662 }
6663 }
6664
6665
6666 // If one of the constants is zero (we know they can't both be) and we
Reid Spencere4d87aa2006-12-23 06:05:41 +00006667 // have a fcmp instruction with zero, and we have an 'and' with the
Chris Lattnerb8456462006-09-20 04:44:59 +00006668 // non-constant value, eliminate this whole mess. This corresponds to
6669 // cases like this: ((X & 27) ? 27 : 0)
6670 if (TrueValC->isNullValue() || FalseValC->isNullValue())
Chris Lattner65b72ba2006-09-18 04:22:48 +00006671 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00006672 cast<Constant>(IC->getOperand(1))->isNullValue())
6673 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
6674 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00006675 isa<ConstantInt>(ICA->getOperand(1)) &&
6676 (ICA->getOperand(1) == TrueValC ||
6677 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00006678 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
6679 // Okay, now we know that everything is set up, we just don't
Reid Spencere4d87aa2006-12-23 06:05:41 +00006680 // know whether we have a icmp_ne or icmp_eq and whether the
6681 // true or false val is the zero.
Chris Lattner457dd822004-06-09 07:59:58 +00006682 bool ShouldNotVal = !TrueValC->isNullValue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00006683 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner457dd822004-06-09 07:59:58 +00006684 Value *V = ICA;
6685 if (ShouldNotVal)
6686 V = InsertNewInstBefore(BinaryOperator::create(
6687 Instruction::Xor, V, ICA->getOperand(1)), SI);
6688 return ReplaceInstUsesWith(SI, V);
6689 }
Chris Lattnerb8456462006-09-20 04:44:59 +00006690 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00006691 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00006692
6693 // See if we are selecting two values based on a comparison of the two values.
Reid Spencere4d87aa2006-12-23 06:05:41 +00006694 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
6695 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattnerd76956d2004-04-10 22:21:27 +00006696 // Transform (X == Y) ? X : Y -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00006697 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ)
Chris Lattnerd76956d2004-04-10 22:21:27 +00006698 return ReplaceInstUsesWith(SI, FalseVal);
6699 // Transform (X != Y) ? X : Y -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00006700 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattnerd76956d2004-04-10 22:21:27 +00006701 return ReplaceInstUsesWith(SI, TrueVal);
6702 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6703
Reid Spencere4d87aa2006-12-23 06:05:41 +00006704 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattnerd76956d2004-04-10 22:21:27 +00006705 // Transform (X == Y) ? Y : X -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00006706 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ)
Chris Lattnerfbede522004-04-11 01:39:19 +00006707 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattnerd76956d2004-04-10 22:21:27 +00006708 // Transform (X != Y) ? Y : X -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00006709 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
6710 return ReplaceInstUsesWith(SI, TrueVal);
6711 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6712 }
6713 }
6714
6715 // See if we are selecting two values based on a comparison of the two values.
6716 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
6717 if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
6718 // Transform (X == Y) ? X : Y -> Y
6719 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
6720 return ReplaceInstUsesWith(SI, FalseVal);
6721 // Transform (X != Y) ? X : Y -> X
6722 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
6723 return ReplaceInstUsesWith(SI, TrueVal);
6724 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6725
6726 } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
6727 // Transform (X == Y) ? Y : X -> X
6728 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
6729 return ReplaceInstUsesWith(SI, FalseVal);
6730 // Transform (X != Y) ? Y : X -> Y
6731 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
Chris Lattnerfbede522004-04-11 01:39:19 +00006732 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerd76956d2004-04-10 22:21:27 +00006733 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6734 }
6735 }
Misha Brukmanfd939082005-04-21 23:48:37 +00006736
Chris Lattner87875da2005-01-13 22:52:24 +00006737 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
6738 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
6739 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattner87875da2005-01-13 22:52:24 +00006740 Instruction *AddOp = 0, *SubOp = 0;
6741
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00006742 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
6743 if (TI->getOpcode() == FI->getOpcode())
6744 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
6745 return IV;
6746
6747 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
6748 // even legal for FP.
Chris Lattner87875da2005-01-13 22:52:24 +00006749 if (TI->getOpcode() == Instruction::Sub &&
6750 FI->getOpcode() == Instruction::Add) {
6751 AddOp = FI; SubOp = TI;
6752 } else if (FI->getOpcode() == Instruction::Sub &&
6753 TI->getOpcode() == Instruction::Add) {
6754 AddOp = TI; SubOp = FI;
6755 }
6756
6757 if (AddOp) {
6758 Value *OtherAddOp = 0;
6759 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
6760 OtherAddOp = AddOp->getOperand(1);
6761 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
6762 OtherAddOp = AddOp->getOperand(0);
6763 }
6764
6765 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00006766 // So at this point we know we have (Y -> OtherAddOp):
6767 // select C, (add X, Y), (sub X, Z)
6768 Value *NegVal; // Compute -Z
6769 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
6770 NegVal = ConstantExpr::getNeg(C);
6771 } else {
6772 NegVal = InsertNewInstBefore(
6773 BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00006774 }
Chris Lattner97f37a42006-02-24 18:05:58 +00006775
6776 Value *NewTrueOp = OtherAddOp;
6777 Value *NewFalseOp = NegVal;
6778 if (AddOp != TI)
6779 std::swap(NewTrueOp, NewFalseOp);
6780 Instruction *NewSel =
6781 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
6782
6783 NewSel = InsertNewInstBefore(NewSel, SI);
6784 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00006785 }
6786 }
6787 }
Misha Brukmanfd939082005-04-21 23:48:37 +00006788
Chris Lattnere576b912004-04-09 23:46:01 +00006789 // See if we can fold the select into one of our operands.
6790 if (SI.getType()->isInteger()) {
6791 // See the comment above GetSelectFoldableOperands for a description of the
6792 // transformation we are doing here.
6793 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
6794 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
6795 !isa<Constant>(FalseVal))
6796 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
6797 unsigned OpToFold = 0;
6798 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
6799 OpToFold = 1;
6800 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
6801 OpToFold = 2;
6802 }
6803
6804 if (OpToFold) {
6805 Constant *C = GetSelectFoldableConstant(TVI);
6806 std::string Name = TVI->getName(); TVI->setName("");
6807 Instruction *NewSel =
6808 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
6809 Name);
6810 InsertNewInstBefore(NewSel, SI);
6811 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
6812 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
6813 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
6814 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
6815 else {
6816 assert(0 && "Unknown instruction!!");
6817 }
6818 }
6819 }
Chris Lattnera96879a2004-09-29 17:40:11 +00006820
Chris Lattnere576b912004-04-09 23:46:01 +00006821 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
6822 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
6823 !isa<Constant>(TrueVal))
6824 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
6825 unsigned OpToFold = 0;
6826 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
6827 OpToFold = 1;
6828 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
6829 OpToFold = 2;
6830 }
6831
6832 if (OpToFold) {
6833 Constant *C = GetSelectFoldableConstant(FVI);
6834 std::string Name = FVI->getName(); FVI->setName("");
6835 Instruction *NewSel =
6836 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
6837 Name);
6838 InsertNewInstBefore(NewSel, SI);
6839 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
6840 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
6841 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
6842 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
6843 else {
6844 assert(0 && "Unknown instruction!!");
6845 }
6846 }
6847 }
6848 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00006849
6850 if (BinaryOperator::isNot(CondVal)) {
6851 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
6852 SI.setOperand(1, FalseVal);
6853 SI.setOperand(2, TrueVal);
6854 return &SI;
6855 }
6856
Chris Lattner3d69f462004-03-12 05:52:32 +00006857 return 0;
6858}
6859
Chris Lattner95a959d2006-03-06 20:18:44 +00006860/// GetKnownAlignment - If the specified pointer has an alignment that we can
6861/// determine, return it, otherwise return 0.
6862static unsigned GetKnownAlignment(Value *V, TargetData *TD) {
6863 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
6864 unsigned Align = GV->getAlignment();
6865 if (Align == 0 && TD)
6866 Align = TD->getTypeAlignment(GV->getType()->getElementType());
6867 return Align;
6868 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
6869 unsigned Align = AI->getAlignment();
6870 if (Align == 0 && TD) {
6871 if (isa<AllocaInst>(AI))
6872 Align = TD->getTypeAlignment(AI->getType()->getElementType());
6873 else if (isa<MallocInst>(AI)) {
6874 // Malloc returns maximally aligned memory.
6875 Align = TD->getTypeAlignment(AI->getType()->getElementType());
6876 Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::DoubleTy));
Reid Spencerc5b206b2006-12-31 05:48:39 +00006877 Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::Int64Ty));
Chris Lattner95a959d2006-03-06 20:18:44 +00006878 }
6879 }
6880 return Align;
Reid Spencer3da59db2006-11-27 01:05:10 +00006881 } else if (isa<BitCastInst>(V) ||
Chris Lattner51c26e92006-03-07 01:28:57 +00006882 (isa<ConstantExpr>(V) &&
Reid Spencer3da59db2006-11-27 01:05:10 +00006883 cast<ConstantExpr>(V)->getOpcode() == Instruction::BitCast)) {
Chris Lattner51c26e92006-03-07 01:28:57 +00006884 User *CI = cast<User>(V);
Chris Lattner95a959d2006-03-06 20:18:44 +00006885 if (isa<PointerType>(CI->getOperand(0)->getType()))
6886 return GetKnownAlignment(CI->getOperand(0), TD);
6887 return 0;
Chris Lattner51c26e92006-03-07 01:28:57 +00006888 } else if (isa<GetElementPtrInst>(V) ||
6889 (isa<ConstantExpr>(V) &&
6890 cast<ConstantExpr>(V)->getOpcode()==Instruction::GetElementPtr)) {
6891 User *GEPI = cast<User>(V);
Chris Lattner95a959d2006-03-06 20:18:44 +00006892 unsigned BaseAlignment = GetKnownAlignment(GEPI->getOperand(0), TD);
6893 if (BaseAlignment == 0) return 0;
6894
6895 // If all indexes are zero, it is just the alignment of the base pointer.
6896 bool AllZeroOperands = true;
6897 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
6898 if (!isa<Constant>(GEPI->getOperand(i)) ||
6899 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
6900 AllZeroOperands = false;
6901 break;
6902 }
6903 if (AllZeroOperands)
6904 return BaseAlignment;
6905
6906 // Otherwise, if the base alignment is >= the alignment we expect for the
6907 // base pointer type, then we know that the resultant pointer is aligned at
6908 // least as much as its type requires.
6909 if (!TD) return 0;
6910
6911 const Type *BasePtrTy = GEPI->getOperand(0)->getType();
6912 if (TD->getTypeAlignment(cast<PointerType>(BasePtrTy)->getElementType())
Chris Lattner51c26e92006-03-07 01:28:57 +00006913 <= BaseAlignment) {
6914 const Type *GEPTy = GEPI->getType();
6915 return TD->getTypeAlignment(cast<PointerType>(GEPTy)->getElementType());
6916 }
Chris Lattner95a959d2006-03-06 20:18:44 +00006917 return 0;
6918 }
6919 return 0;
6920}
6921
Chris Lattner3d69f462004-03-12 05:52:32 +00006922
Chris Lattner8b0ea312006-01-13 20:11:04 +00006923/// visitCallInst - CallInst simplification. This mostly only handles folding
6924/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
6925/// the heavy lifting.
6926///
Chris Lattner9fe38862003-06-19 17:00:31 +00006927Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattner8b0ea312006-01-13 20:11:04 +00006928 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
6929 if (!II) return visitCallSite(&CI);
6930
Chris Lattner7bcc0e72004-02-28 05:22:00 +00006931 // Intrinsics cannot occur in an invoke, so handle them here instead of in
6932 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00006933 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00006934 bool Changed = false;
6935
6936 // memmove/cpy/set of zero bytes is a noop.
6937 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
6938 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
6939
Chris Lattner35b9e482004-10-12 04:52:52 +00006940 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +00006941 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +00006942 // Replace the instruction with just byte operations. We would
6943 // transform other cases to loads/stores, but we don't know if
6944 // alignment is sufficient.
6945 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00006946 }
6947
Chris Lattner35b9e482004-10-12 04:52:52 +00006948 // If we have a memmove and the source operation is a constant global,
6949 // then the source and dest pointers can't alias, so we can change this
6950 // into a call to memcpy.
Chris Lattner95a959d2006-03-06 20:18:44 +00006951 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00006952 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
6953 if (GVSrc->isConstant()) {
6954 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner21959392006-03-03 01:34:17 +00006955 const char *Name;
Andrew Lenharth8ed4c472006-11-03 22:45:50 +00006956 if (CI.getCalledFunction()->getFunctionType()->getParamType(2) ==
Reid Spencerc5b206b2006-12-31 05:48:39 +00006957 Type::Int32Ty)
Chris Lattner21959392006-03-03 01:34:17 +00006958 Name = "llvm.memcpy.i32";
6959 else
6960 Name = "llvm.memcpy.i64";
6961 Function *MemCpy = M->getOrInsertFunction(Name,
Chris Lattner35b9e482004-10-12 04:52:52 +00006962 CI.getCalledFunction()->getFunctionType());
6963 CI.setOperand(0, MemCpy);
6964 Changed = true;
6965 }
Chris Lattner95a959d2006-03-06 20:18:44 +00006966 }
Chris Lattner35b9e482004-10-12 04:52:52 +00006967
Chris Lattner95a959d2006-03-06 20:18:44 +00006968 // If we can determine a pointer alignment that is bigger than currently
6969 // set, update the alignment.
6970 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
6971 unsigned Alignment1 = GetKnownAlignment(MI->getOperand(1), TD);
6972 unsigned Alignment2 = GetKnownAlignment(MI->getOperand(2), TD);
6973 unsigned Align = std::min(Alignment1, Alignment2);
Reid Spencerb83eb642006-10-20 07:07:24 +00006974 if (MI->getAlignment()->getZExtValue() < Align) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00006975 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Align));
Chris Lattner95a959d2006-03-06 20:18:44 +00006976 Changed = true;
6977 }
6978 } else if (isa<MemSetInst>(MI)) {
6979 unsigned Alignment = GetKnownAlignment(MI->getDest(), TD);
Reid Spencerb83eb642006-10-20 07:07:24 +00006980 if (MI->getAlignment()->getZExtValue() < Alignment) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00006981 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
Chris Lattner95a959d2006-03-06 20:18:44 +00006982 Changed = true;
6983 }
6984 }
6985
Chris Lattner8b0ea312006-01-13 20:11:04 +00006986 if (Changed) return II;
Chris Lattnera728ddc2006-01-13 21:28:09 +00006987 } else {
6988 switch (II->getIntrinsicID()) {
6989 default: break;
Chris Lattner82ed58f2006-04-02 05:30:25 +00006990 case Intrinsic::ppc_altivec_lvx:
6991 case Intrinsic::ppc_altivec_lvxl:
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00006992 case Intrinsic::x86_sse_loadu_ps:
6993 case Intrinsic::x86_sse2_loadu_pd:
6994 case Intrinsic::x86_sse2_loadu_dq:
6995 // Turn PPC lvx -> load if the pointer is known aligned.
6996 // Turn X86 loadups -> load if the pointer is known aligned.
Chris Lattner82ed58f2006-04-02 05:30:25 +00006997 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
Reid Spencer17212df2006-12-12 09:18:51 +00006998 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
Chris Lattnere2ed0572006-04-06 19:19:17 +00006999 PointerType::get(II->getType()), CI);
Chris Lattner82ed58f2006-04-02 05:30:25 +00007000 return new LoadInst(Ptr);
7001 }
7002 break;
7003 case Intrinsic::ppc_altivec_stvx:
7004 case Intrinsic::ppc_altivec_stvxl:
7005 // Turn stvx -> store if the pointer is known aligned.
7006 if (GetKnownAlignment(II->getOperand(2), TD) >= 16) {
Chris Lattnere2ed0572006-04-06 19:19:17 +00007007 const Type *OpPtrTy = PointerType::get(II->getOperand(1)->getType());
Reid Spencer17212df2006-12-12 09:18:51 +00007008 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(2),
7009 OpPtrTy, CI);
Chris Lattner82ed58f2006-04-02 05:30:25 +00007010 return new StoreInst(II->getOperand(1), Ptr);
7011 }
7012 break;
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00007013 case Intrinsic::x86_sse_storeu_ps:
7014 case Intrinsic::x86_sse2_storeu_pd:
7015 case Intrinsic::x86_sse2_storeu_dq:
7016 case Intrinsic::x86_sse2_storel_dq:
7017 // Turn X86 storeu -> store if the pointer is known aligned.
7018 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
7019 const Type *OpPtrTy = PointerType::get(II->getOperand(2)->getType());
Reid Spencer17212df2006-12-12 09:18:51 +00007020 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
7021 OpPtrTy, CI);
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00007022 return new StoreInst(II->getOperand(2), Ptr);
7023 }
7024 break;
Chris Lattner867b99f2006-10-05 06:55:50 +00007025
7026 case Intrinsic::x86_sse_cvttss2si: {
7027 // These intrinsics only demands the 0th element of its input vector. If
7028 // we can simplify the input based on that, do so now.
7029 uint64_t UndefElts;
7030 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
7031 UndefElts)) {
7032 II->setOperand(1, V);
7033 return II;
7034 }
7035 break;
7036 }
7037
Chris Lattnere2ed0572006-04-06 19:19:17 +00007038 case Intrinsic::ppc_altivec_vperm:
7039 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
7040 if (ConstantPacked *Mask = dyn_cast<ConstantPacked>(II->getOperand(3))) {
7041 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
7042
7043 // Check that all of the elements are integer constants or undefs.
7044 bool AllEltsOk = true;
7045 for (unsigned i = 0; i != 16; ++i) {
7046 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
7047 !isa<UndefValue>(Mask->getOperand(i))) {
7048 AllEltsOk = false;
7049 break;
7050 }
7051 }
7052
7053 if (AllEltsOk) {
7054 // Cast the input vectors to byte vectors.
Reid Spencer17212df2006-12-12 09:18:51 +00007055 Value *Op0 = InsertCastBefore(Instruction::BitCast,
7056 II->getOperand(1), Mask->getType(), CI);
7057 Value *Op1 = InsertCastBefore(Instruction::BitCast,
7058 II->getOperand(2), Mask->getType(), CI);
Chris Lattnere2ed0572006-04-06 19:19:17 +00007059 Value *Result = UndefValue::get(Op0->getType());
7060
7061 // Only extract each element once.
7062 Value *ExtractedElts[32];
7063 memset(ExtractedElts, 0, sizeof(ExtractedElts));
7064
7065 for (unsigned i = 0; i != 16; ++i) {
7066 if (isa<UndefValue>(Mask->getOperand(i)))
7067 continue;
Reid Spencerb83eb642006-10-20 07:07:24 +00007068 unsigned Idx =cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
Chris Lattnere2ed0572006-04-06 19:19:17 +00007069 Idx &= 31; // Match the hardware behavior.
7070
7071 if (ExtractedElts[Idx] == 0) {
7072 Instruction *Elt =
Chris Lattner867b99f2006-10-05 06:55:50 +00007073 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00007074 InsertNewInstBefore(Elt, CI);
7075 ExtractedElts[Idx] = Elt;
7076 }
7077
7078 // Insert this value into the result vector.
Chris Lattner867b99f2006-10-05 06:55:50 +00007079 Result = new InsertElementInst(Result, ExtractedElts[Idx], i,"tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00007080 InsertNewInstBefore(cast<Instruction>(Result), CI);
7081 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007082 return CastInst::create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00007083 }
7084 }
7085 break;
7086
Chris Lattnera728ddc2006-01-13 21:28:09 +00007087 case Intrinsic::stackrestore: {
7088 // If the save is right next to the restore, remove the restore. This can
7089 // happen when variable allocas are DCE'd.
7090 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
7091 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
7092 BasicBlock::iterator BI = SS;
7093 if (&*++BI == II)
7094 return EraseInstFromFunction(CI);
7095 }
7096 }
7097
7098 // If the stack restore is in a return/unwind block and if there are no
7099 // allocas or calls between the restore and the return, nuke the restore.
7100 TerminatorInst *TI = II->getParent()->getTerminator();
7101 if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
7102 BasicBlock::iterator BI = II;
7103 bool CannotRemove = false;
7104 for (++BI; &*BI != TI; ++BI) {
7105 if (isa<AllocaInst>(BI) ||
7106 (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
7107 CannotRemove = true;
7108 break;
7109 }
7110 }
7111 if (!CannotRemove)
7112 return EraseInstFromFunction(CI);
7113 }
7114 break;
7115 }
7116 }
Chris Lattner35b9e482004-10-12 04:52:52 +00007117 }
7118
Chris Lattner8b0ea312006-01-13 20:11:04 +00007119 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +00007120}
7121
7122// InvokeInst simplification
7123//
7124Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +00007125 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +00007126}
7127
Chris Lattnera44d8a22003-10-07 22:32:43 +00007128// visitCallSite - Improvements for call and invoke instructions.
7129//
7130Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +00007131 bool Changed = false;
7132
7133 // If the callee is a constexpr cast of a function, attempt to move the cast
7134 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +00007135 if (transformConstExprCastCall(CS)) return 0;
7136
Chris Lattner6c266db2003-10-07 22:54:13 +00007137 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +00007138
Chris Lattner08b22ec2005-05-13 07:09:09 +00007139 if (Function *CalleeF = dyn_cast<Function>(Callee))
7140 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
7141 Instruction *OldCall = CS.getInstruction();
7142 // If the call and callee calling conventions don't match, this call must
7143 // be unreachable, as the call is undefined.
Chris Lattner47811b72006-09-28 23:35:22 +00007144 new StoreInst(ConstantBool::getTrue(),
Chris Lattner08b22ec2005-05-13 07:09:09 +00007145 UndefValue::get(PointerType::get(Type::BoolTy)), OldCall);
7146 if (!OldCall->use_empty())
7147 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
7148 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
7149 return EraseInstFromFunction(*OldCall);
7150 return 0;
7151 }
7152
Chris Lattner17be6352004-10-18 02:59:09 +00007153 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
7154 // This instruction is not reachable, just remove it. We insert a store to
7155 // undef so that we know that this code is not reachable, despite the fact
7156 // that we can't modify the CFG here.
Chris Lattner47811b72006-09-28 23:35:22 +00007157 new StoreInst(ConstantBool::getTrue(),
Chris Lattner17be6352004-10-18 02:59:09 +00007158 UndefValue::get(PointerType::get(Type::BoolTy)),
7159 CS.getInstruction());
7160
7161 if (!CS.getInstruction()->use_empty())
7162 CS.getInstruction()->
7163 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
7164
7165 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
7166 // Don't break the CFG, insert a dummy cond branch.
7167 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
Chris Lattner47811b72006-09-28 23:35:22 +00007168 ConstantBool::getTrue(), II);
Chris Lattnere87597f2004-10-16 18:11:37 +00007169 }
Chris Lattner17be6352004-10-18 02:59:09 +00007170 return EraseInstFromFunction(*CS.getInstruction());
7171 }
Chris Lattnere87597f2004-10-16 18:11:37 +00007172
Chris Lattner6c266db2003-10-07 22:54:13 +00007173 const PointerType *PTy = cast<PointerType>(Callee->getType());
7174 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
7175 if (FTy->isVarArg()) {
7176 // See if we can optimize any arguments passed through the varargs area of
7177 // the call.
7178 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
7179 E = CS.arg_end(); I != E; ++I)
7180 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
7181 // If this cast does not effect the value passed through the varargs
7182 // area, we can eliminate the use of the cast.
7183 Value *Op = CI->getOperand(0);
Reid Spencer3da59db2006-11-27 01:05:10 +00007184 if (CI->isLosslessCast()) {
Chris Lattner6c266db2003-10-07 22:54:13 +00007185 *I = Op;
7186 Changed = true;
7187 }
7188 }
7189 }
Misha Brukmanfd939082005-04-21 23:48:37 +00007190
Chris Lattner6c266db2003-10-07 22:54:13 +00007191 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +00007192}
7193
Chris Lattner9fe38862003-06-19 17:00:31 +00007194// transformConstExprCastCall - If the callee is a constexpr cast of a function,
7195// attempt to move the cast to the arguments of the call/invoke.
7196//
7197bool InstCombiner::transformConstExprCastCall(CallSite CS) {
7198 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
7199 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +00007200 if (CE->getOpcode() != Instruction::BitCast ||
7201 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +00007202 return false;
Reid Spencer8863f182004-07-18 00:38:32 +00007203 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +00007204 Instruction *Caller = CS.getInstruction();
7205
7206 // Okay, this is a cast from a function to a different type. Unless doing so
7207 // would cause a type conversion of one of our arguments, change this call to
7208 // be a direct call with arguments casted to the appropriate types.
7209 //
7210 const FunctionType *FT = Callee->getFunctionType();
7211 const Type *OldRetTy = Caller->getType();
7212
Chris Lattnerf78616b2004-01-14 06:06:08 +00007213 // Check to see if we are changing the return type...
7214 if (OldRetTy != FT->getReturnType()) {
7215 if (Callee->isExternal() &&
Reid Spencer3da59db2006-11-27 01:05:10 +00007216 !Caller->use_empty() &&
7217 !(OldRetTy->canLosslesslyBitCastTo(FT->getReturnType()) ||
Andrew Lenharth8117f9a2006-04-20 14:56:47 +00007218 (isa<PointerType>(FT->getReturnType()) &&
Reid Spencer3da59db2006-11-27 01:05:10 +00007219 TD->getIntPtrType()->canLosslesslyBitCastTo(OldRetTy)))
7220 )
Chris Lattnerf78616b2004-01-14 06:06:08 +00007221 return false; // Cannot transform this return value...
7222
7223 // If the callsite is an invoke instruction, and the return value is used by
7224 // a PHI node in a successor, we cannot change the return type of the call
7225 // because there is no place to put the cast instruction (without breaking
7226 // the critical edge). Bail out in this case.
7227 if (!Caller->use_empty())
7228 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
7229 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
7230 UI != E; ++UI)
7231 if (PHINode *PN = dyn_cast<PHINode>(*UI))
7232 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00007233 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +00007234 return false;
7235 }
Chris Lattner9fe38862003-06-19 17:00:31 +00007236
7237 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
7238 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +00007239
Chris Lattner9fe38862003-06-19 17:00:31 +00007240 CallSite::arg_iterator AI = CS.arg_begin();
7241 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
7242 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +00007243 const Type *ActTy = (*AI)->getType();
Reid Spencer3da59db2006-11-27 01:05:10 +00007244 ConstantInt *c = dyn_cast<ConstantInt>(*AI);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +00007245 //Either we can cast directly, or we can upconvert the argument
Reid Spencer3da59db2006-11-27 01:05:10 +00007246 bool isConvertible = ActTy->canLosslesslyBitCastTo(ParamTy) ||
Andrew Lenharthb8e604c2006-06-28 01:01:52 +00007247 (ParamTy->isIntegral() && ActTy->isIntegral() &&
Andrew Lenharthb8e604c2006-06-28 01:01:52 +00007248 ParamTy->getPrimitiveSize() >= ActTy->getPrimitiveSize()) ||
7249 (c && ParamTy->getPrimitiveSize() >= ActTy->getPrimitiveSize() &&
Reid Spencerb83eb642006-10-20 07:07:24 +00007250 c->getSExtValue() > 0);
Misha Brukmanfd939082005-04-21 23:48:37 +00007251 if (Callee->isExternal() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +00007252 }
7253
7254 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
7255 Callee->isExternal())
7256 return false; // Do not delete arguments unless we have a function body...
7257
7258 // Okay, we decided that this is a safe thing to do: go ahead and start
7259 // inserting cast instructions as necessary...
7260 std::vector<Value*> Args;
7261 Args.reserve(NumActualArgs);
7262
7263 AI = CS.arg_begin();
7264 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
7265 const Type *ParamTy = FT->getParamType(i);
7266 if ((*AI)->getType() == ParamTy) {
7267 Args.push_back(*AI);
7268 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +00007269 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +00007270 false, ParamTy, false);
Reid Spencer8a903db2006-12-18 08:47:13 +00007271 CastInst *NewCast = CastInst::create(opcode, *AI, ParamTy, "tmp");
Reid Spencer3da59db2006-11-27 01:05:10 +00007272 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner9fe38862003-06-19 17:00:31 +00007273 }
7274 }
7275
7276 // If the function takes more arguments than the call was taking, add them
7277 // now...
7278 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
7279 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
7280
7281 // If we are removing arguments to the function, emit an obnoxious warning...
7282 if (FT->getNumParams() < NumActualArgs)
7283 if (!FT->isVarArg()) {
Bill Wendlinge8156192006-12-07 01:30:32 +00007284 cerr << "WARNING: While resolving call to function '"
7285 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +00007286 } else {
7287 // Add all of the arguments in their promoted form to the arg list...
7288 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
7289 const Type *PTy = getPromotedType((*AI)->getType());
7290 if (PTy != (*AI)->getType()) {
7291 // Must promote to pass through va_arg area!
Reid Spencerc5b206b2006-12-31 05:48:39 +00007292 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
7293 PTy, false);
Reid Spencer8a903db2006-12-18 08:47:13 +00007294 Instruction *Cast = CastInst::create(opcode, *AI, PTy, "tmp");
Chris Lattner9fe38862003-06-19 17:00:31 +00007295 InsertNewInstBefore(Cast, *Caller);
7296 Args.push_back(Cast);
7297 } else {
7298 Args.push_back(*AI);
7299 }
7300 }
7301 }
7302
7303 if (FT->getReturnType() == Type::VoidTy)
7304 Caller->setName(""); // Void type should not have a name...
7305
7306 Instruction *NC;
7307 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00007308 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattner9fe38862003-06-19 17:00:31 +00007309 Args, Caller->getName(), Caller);
Chris Lattnere4370262005-05-14 12:25:32 +00007310 cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
Chris Lattner9fe38862003-06-19 17:00:31 +00007311 } else {
7312 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
Chris Lattnera9e92112005-05-06 06:48:21 +00007313 if (cast<CallInst>(Caller)->isTailCall())
7314 cast<CallInst>(NC)->setTailCall();
Chris Lattnere4370262005-05-14 12:25:32 +00007315 cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Chris Lattner9fe38862003-06-19 17:00:31 +00007316 }
7317
7318 // Insert a cast of the return type as necessary...
7319 Value *NV = NC;
7320 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
7321 if (NV->getType() != Type::VoidTy) {
Reid Spencer8a903db2006-12-18 08:47:13 +00007322 const Type *CallerTy = Caller->getType();
Reid Spencerc5b206b2006-12-31 05:48:39 +00007323 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
7324 CallerTy, false);
Reid Spencer8a903db2006-12-18 08:47:13 +00007325 NV = NC = CastInst::create(opcode, NC, CallerTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +00007326
7327 // If this is an invoke instruction, we should insert it after the first
7328 // non-phi, instruction in the normal successor block.
7329 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
7330 BasicBlock::iterator I = II->getNormalDest()->begin();
7331 while (isa<PHINode>(I)) ++I;
7332 InsertNewInstBefore(NC, *I);
7333 } else {
7334 // Otherwise, it's a call, just insert cast right after the call instr
7335 InsertNewInstBefore(NC, *Caller);
7336 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00007337 AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00007338 } else {
Chris Lattnerc30bda72004-10-17 21:22:38 +00007339 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +00007340 }
7341 }
7342
7343 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
7344 Caller->replaceAllUsesWith(NV);
7345 Caller->getParent()->getInstList().erase(Caller);
7346 removeFromWorkList(Caller);
7347 return true;
7348}
7349
Chris Lattner7da52b22006-11-01 04:51:18 +00007350/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
7351/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
7352/// and a single binop.
7353Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
7354 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Chris Lattner9c080502006-11-01 07:43:41 +00007355 assert(isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst) ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00007356 isa<GetElementPtrInst>(FirstInst) || isa<CmpInst>(FirstInst));
Chris Lattner7da52b22006-11-01 04:51:18 +00007357 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00007358 Value *LHSVal = FirstInst->getOperand(0);
7359 Value *RHSVal = FirstInst->getOperand(1);
7360
7361 const Type *LHSType = LHSVal->getType();
7362 const Type *RHSType = RHSVal->getType();
Chris Lattner7da52b22006-11-01 04:51:18 +00007363
7364 // Scan to see if all operands are the same opcode, all have one use, and all
7365 // kill their operands (i.e. the operands have one use).
Chris Lattnera90a24c2006-11-01 04:55:47 +00007366 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
Chris Lattner7da52b22006-11-01 04:51:18 +00007367 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnera90a24c2006-11-01 04:55:47 +00007368 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00007369 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattner9c080502006-11-01 07:43:41 +00007370 // types or GEP's with different index types.
7371 I->getOperand(0)->getType() != LHSType ||
7372 I->getOperand(1)->getType() != RHSType)
Chris Lattner7da52b22006-11-01 04:51:18 +00007373 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +00007374
7375 // If they are CmpInst instructions, check their predicates
7376 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
7377 if (cast<CmpInst>(I)->getPredicate() !=
7378 cast<CmpInst>(FirstInst)->getPredicate())
7379 return 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00007380
7381 // Keep track of which operand needs a phi node.
7382 if (I->getOperand(0) != LHSVal) LHSVal = 0;
7383 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattner7da52b22006-11-01 04:51:18 +00007384 }
7385
Chris Lattner53738a42006-11-08 19:42:28 +00007386 // Otherwise, this is safe to transform, determine if it is profitable.
7387
7388 // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
7389 // Indexes are often folded into load/store instructions, so we don't want to
7390 // hide them behind a phi.
7391 if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
7392 return 0;
7393
Chris Lattner7da52b22006-11-01 04:51:18 +00007394 Value *InLHS = FirstInst->getOperand(0);
Chris Lattner7da52b22006-11-01 04:51:18 +00007395 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner53738a42006-11-08 19:42:28 +00007396 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00007397 if (LHSVal == 0) {
7398 NewLHS = new PHINode(LHSType, FirstInst->getOperand(0)->getName()+".pn");
7399 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
7400 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +00007401 InsertNewInstBefore(NewLHS, PN);
7402 LHSVal = NewLHS;
7403 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00007404
7405 if (RHSVal == 0) {
7406 NewRHS = new PHINode(RHSType, FirstInst->getOperand(1)->getName()+".pn");
7407 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
7408 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +00007409 InsertNewInstBefore(NewRHS, PN);
7410 RHSVal = NewRHS;
7411 }
7412
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00007413 // Add all operands to the new PHIs.
7414 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7415 if (NewLHS) {
7416 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
7417 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
7418 }
7419 if (NewRHS) {
7420 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
7421 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
7422 }
7423 }
7424
Chris Lattner7da52b22006-11-01 04:51:18 +00007425 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattner9c080502006-11-01 07:43:41 +00007426 return BinaryOperator::create(BinOp->getOpcode(), LHSVal, RHSVal);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007427 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
7428 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
7429 RHSVal);
Chris Lattner9c080502006-11-01 07:43:41 +00007430 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FirstInst))
7431 return new ShiftInst(SI->getOpcode(), LHSVal, RHSVal);
7432 else {
7433 assert(isa<GetElementPtrInst>(FirstInst));
7434 return new GetElementPtrInst(LHSVal, RHSVal);
7435 }
Chris Lattner7da52b22006-11-01 04:51:18 +00007436}
7437
Chris Lattner76c73142006-11-01 07:13:54 +00007438/// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
7439/// of the block that defines it. This means that it must be obvious the value
7440/// of the load is not changed from the point of the load to the end of the
7441/// block it is in.
7442static bool isSafeToSinkLoad(LoadInst *L) {
7443 BasicBlock::iterator BBI = L, E = L->getParent()->end();
7444
7445 for (++BBI; BBI != E; ++BBI)
7446 if (BBI->mayWriteToMemory())
7447 return false;
7448 return true;
7449}
7450
Chris Lattner9fe38862003-06-19 17:00:31 +00007451
Chris Lattnerbac32862004-11-14 19:13:23 +00007452// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
7453// operator and they all are only used by the PHI, PHI together their
7454// inputs, and do the operation once, to the result of the PHI.
7455Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
7456 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
7457
7458 // Scan the instruction, looking for input operations that can be folded away.
7459 // If all input operands to the phi are the same instruction (e.g. a cast from
7460 // the same type or "+42") we can pull the operation through the PHI, reducing
7461 // code size and simplifying code.
7462 Constant *ConstantOp = 0;
7463 const Type *CastSrcTy = 0;
Chris Lattner76c73142006-11-01 07:13:54 +00007464 bool isVolatile = false;
Chris Lattnerbac32862004-11-14 19:13:23 +00007465 if (isa<CastInst>(FirstInst)) {
7466 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00007467 } else if (isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst) ||
7468 isa<CmpInst>(FirstInst)) {
7469 // Can fold binop, compare or shift here if the RHS is a constant,
7470 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattnerbac32862004-11-14 19:13:23 +00007471 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattner7da52b22006-11-01 04:51:18 +00007472 if (ConstantOp == 0)
7473 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner76c73142006-11-01 07:13:54 +00007474 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
7475 isVolatile = LI->isVolatile();
7476 // We can't sink the load if the loaded value could be modified between the
7477 // load and the PHI.
7478 if (LI->getParent() != PN.getIncomingBlock(0) ||
7479 !isSafeToSinkLoad(LI))
7480 return 0;
Chris Lattner9c080502006-11-01 07:43:41 +00007481 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner53738a42006-11-08 19:42:28 +00007482 if (FirstInst->getNumOperands() == 2)
Chris Lattner9c080502006-11-01 07:43:41 +00007483 return FoldPHIArgBinOpIntoPHI(PN);
7484 // Can't handle general GEPs yet.
7485 return 0;
Chris Lattnerbac32862004-11-14 19:13:23 +00007486 } else {
7487 return 0; // Cannot fold this operation.
7488 }
7489
7490 // Check to see if all arguments are the same operation.
7491 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7492 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
7493 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencere4d87aa2006-12-23 06:05:41 +00007494 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattnerbac32862004-11-14 19:13:23 +00007495 return 0;
7496 if (CastSrcTy) {
7497 if (I->getOperand(0)->getType() != CastSrcTy)
7498 return 0; // Cast operation must match.
Chris Lattner76c73142006-11-01 07:13:54 +00007499 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00007500 // We can't sink the load if the loaded value could be modified between
7501 // the load and the PHI.
Chris Lattner76c73142006-11-01 07:13:54 +00007502 if (LI->isVolatile() != isVolatile ||
7503 LI->getParent() != PN.getIncomingBlock(i) ||
7504 !isSafeToSinkLoad(LI))
7505 return 0;
Chris Lattnerbac32862004-11-14 19:13:23 +00007506 } else if (I->getOperand(1) != ConstantOp) {
7507 return 0;
7508 }
7509 }
7510
7511 // Okay, they are all the same operation. Create a new PHI node of the
7512 // correct type, and PHI together all of the LHS's of the instructions.
7513 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
7514 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +00007515 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +00007516
7517 Value *InVal = FirstInst->getOperand(0);
7518 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00007519
7520 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +00007521 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7522 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
7523 if (NewInVal != InVal)
7524 InVal = 0;
7525 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
7526 }
7527
7528 Value *PhiVal;
7529 if (InVal) {
7530 // The new PHI unions all of the same values together. This is really
7531 // common, so we handle it intelligently here for compile-time speed.
7532 PhiVal = InVal;
7533 delete NewPN;
7534 } else {
7535 InsertNewInstBefore(NewPN, PN);
7536 PhiVal = NewPN;
7537 }
Misha Brukmanfd939082005-04-21 23:48:37 +00007538
Chris Lattnerbac32862004-11-14 19:13:23 +00007539 // Insert and return the new operation.
Reid Spencer3da59db2006-11-27 01:05:10 +00007540 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
7541 return CastInst::create(FirstCI->getOpcode(), PhiVal, PN.getType());
Reid Spencer3ed469c2006-11-02 20:25:50 +00007542 else if (isa<LoadInst>(FirstInst))
Chris Lattner76c73142006-11-01 07:13:54 +00007543 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattnerbac32862004-11-14 19:13:23 +00007544 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattnerb5893442004-11-14 19:29:34 +00007545 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007546 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
7547 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(),
7548 PhiVal, ConstantOp);
Chris Lattnerbac32862004-11-14 19:13:23 +00007549 else
7550 return new ShiftInst(cast<ShiftInst>(FirstInst)->getOpcode(),
Chris Lattnerb5893442004-11-14 19:29:34 +00007551 PhiVal, ConstantOp);
Chris Lattnerbac32862004-11-14 19:13:23 +00007552}
Chris Lattnera1be5662002-05-02 17:06:02 +00007553
Chris Lattnera3fd1c52005-01-17 05:10:15 +00007554/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
7555/// that is dead.
7556static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
7557 if (PN->use_empty()) return true;
7558 if (!PN->hasOneUse()) return false;
7559
7560 // Remember this node, and if we find the cycle, return.
7561 if (!PotentiallyDeadPHIs.insert(PN).second)
7562 return true;
7563
7564 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
7565 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +00007566
Chris Lattnera3fd1c52005-01-17 05:10:15 +00007567 return false;
7568}
7569
Chris Lattner473945d2002-05-06 18:06:38 +00007570// PHINode simplification
7571//
Chris Lattner7e708292002-06-25 16:13:24 +00007572Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +00007573 // If LCSSA is around, don't mess with Phi nodes
7574 if (mustPreserveAnalysisID(LCSSAID)) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +00007575
Owen Anderson7e057142006-07-10 22:03:18 +00007576 if (Value *V = PN.hasConstantValue())
7577 return ReplaceInstUsesWith(PN, V);
7578
Owen Anderson7e057142006-07-10 22:03:18 +00007579 // If all PHI operands are the same operation, pull them through the PHI,
7580 // reducing code size.
7581 if (isa<Instruction>(PN.getIncomingValue(0)) &&
7582 PN.getIncomingValue(0)->hasOneUse())
7583 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
7584 return Result;
7585
7586 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
7587 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
7588 // PHI)... break the cycle.
7589 if (PN.hasOneUse())
7590 if (PHINode *PU = dyn_cast<PHINode>(PN.use_back())) {
7591 std::set<PHINode*> PotentiallyDeadPHIs;
7592 PotentiallyDeadPHIs.insert(&PN);
7593 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
7594 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
7595 }
7596
Chris Lattner60921c92003-12-19 05:58:40 +00007597 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +00007598}
7599
Reid Spencer17212df2006-12-12 09:18:51 +00007600static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
7601 Instruction *InsertPoint,
7602 InstCombiner *IC) {
Reid Spencer7eb76382006-12-13 17:19:09 +00007603 unsigned PtrSize = DTy->getPrimitiveSize();
Reid Spencer17212df2006-12-12 09:18:51 +00007604 unsigned VTySize = V->getType()->getPrimitiveSize();
7605 // We must cast correctly to the pointer type. Ensure that we
7606 // sign extend the integer value if it is smaller as this is
7607 // used for address computation.
7608 Instruction::CastOps opcode =
7609 (VTySize < PtrSize ? Instruction::SExt :
7610 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
7611 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
Chris Lattner28977af2004-04-05 01:30:19 +00007612}
7613
Chris Lattnera1be5662002-05-02 17:06:02 +00007614
Chris Lattner7e708292002-06-25 16:13:24 +00007615Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +00007616 Value *PtrOp = GEP.getOperand(0);
Chris Lattnerc54e2b82003-05-22 19:07:21 +00007617 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner7e708292002-06-25 16:13:24 +00007618 // If so, eliminate the noop.
Chris Lattnerc6bd1952004-02-22 05:25:17 +00007619 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +00007620 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +00007621
Chris Lattnere87597f2004-10-16 18:11:37 +00007622 if (isa<UndefValue>(GEP.getOperand(0)))
7623 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
7624
Chris Lattnerc6bd1952004-02-22 05:25:17 +00007625 bool HasZeroPointerIndex = false;
7626 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
7627 HasZeroPointerIndex = C->isNullValue();
7628
7629 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +00007630 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +00007631
Chris Lattner28977af2004-04-05 01:30:19 +00007632 // Eliminate unneeded casts for indices.
7633 bool MadeChange = false;
Chris Lattnercb69a4e2004-04-07 18:38:20 +00007634 gep_type_iterator GTI = gep_type_begin(GEP);
7635 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
7636 if (isa<SequentialType>(*GTI)) {
7637 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
7638 Value *Src = CI->getOperand(0);
7639 const Type *SrcTy = Src->getType();
7640 const Type *DestTy = CI->getType();
7641 if (Src->getType()->isInteger()) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00007642 if (SrcTy->getPrimitiveSizeInBits() ==
7643 DestTy->getPrimitiveSizeInBits()) {
Chris Lattnercb69a4e2004-04-07 18:38:20 +00007644 // We can always eliminate a cast from ulong or long to the other.
7645 // We can always eliminate a cast from uint to int or the other on
7646 // 32-bit pointer platforms.
Chris Lattner484d3cf2005-04-24 06:59:08 +00007647 if (DestTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()){
Chris Lattnercb69a4e2004-04-07 18:38:20 +00007648 MadeChange = true;
7649 GEP.setOperand(i, Src);
7650 }
7651 } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
7652 SrcTy->getPrimitiveSize() == 4) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00007653 // We can eliminate a cast from [u]int to [u]long iff the target
7654 // is a 32-bit pointer target.
7655 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
Chris Lattnercb69a4e2004-04-07 18:38:20 +00007656 MadeChange = true;
7657 GEP.setOperand(i, Src);
7658 }
Chris Lattner28977af2004-04-05 01:30:19 +00007659 }
7660 }
7661 }
Chris Lattnercb69a4e2004-04-07 18:38:20 +00007662 // If we are using a wider index than needed for this platform, shrink it
7663 // to what we need. If the incoming value needs a cast instruction,
7664 // insert it. This explicit cast can make subsequent optimizations more
7665 // obvious.
7666 Value *Op = GEP.getOperand(i);
7667 if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
Chris Lattner4f1134e2004-04-17 18:16:10 +00007668 if (Constant *C = dyn_cast<Constant>(Op)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00007669 GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
Chris Lattner4f1134e2004-04-17 18:16:10 +00007670 MadeChange = true;
7671 } else {
Reid Spencer17212df2006-12-12 09:18:51 +00007672 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
7673 GEP);
Chris Lattnercb69a4e2004-04-07 18:38:20 +00007674 GEP.setOperand(i, Op);
7675 MadeChange = true;
7676 }
Chris Lattner28977af2004-04-05 01:30:19 +00007677 }
7678 if (MadeChange) return &GEP;
7679
Chris Lattner90ac28c2002-08-02 19:29:35 +00007680 // Combine Indices - If the source pointer to this getelementptr instruction
7681 // is a getelementptr instruction, combine the indices of the two
7682 // getelementptr instructions into a single instruction.
7683 //
Chris Lattnerebd985c2004-03-25 22:59:29 +00007684 std::vector<Value*> SrcGEPOperands;
Chris Lattner574da9b2005-01-13 20:14:25 +00007685 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattnerebd985c2004-03-25 22:59:29 +00007686 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
Chris Lattnerebd985c2004-03-25 22:59:29 +00007687
7688 if (!SrcGEPOperands.empty()) {
Chris Lattner620ce142004-05-07 22:09:22 +00007689 // Note that if our source is a gep chain itself that we wait for that
7690 // chain to be resolved before we perform this transformation. This
7691 // avoids us creating a TON of code in some cases.
7692 //
7693 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
7694 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
7695 return 0; // Wait until our source is folded to completion.
7696
Chris Lattner90ac28c2002-08-02 19:29:35 +00007697 std::vector<Value *> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +00007698
7699 // Find out whether the last index in the source GEP is a sequential idx.
7700 bool EndsWithSequential = false;
7701 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
7702 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +00007703 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +00007704
Chris Lattner90ac28c2002-08-02 19:29:35 +00007705 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +00007706 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +00007707 // Replace: gep (gep %P, long B), long A, ...
7708 // With: T = long A+B; gep %P, T, ...
7709 //
Chris Lattner620ce142004-05-07 22:09:22 +00007710 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner28977af2004-04-05 01:30:19 +00007711 if (SO1 == Constant::getNullValue(SO1->getType())) {
7712 Sum = GO1;
7713 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
7714 Sum = SO1;
7715 } else {
7716 // If they aren't the same type, convert both to an integer of the
7717 // target's pointer size.
7718 if (SO1->getType() != GO1->getType()) {
7719 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +00007720 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +00007721 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +00007722 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +00007723 } else {
7724 unsigned PS = TD->getPointerSize();
Chris Lattner28977af2004-04-05 01:30:19 +00007725 if (SO1->getType()->getPrimitiveSize() == PS) {
7726 // Convert GO1 to SO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +00007727 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +00007728
7729 } else if (GO1->getType()->getPrimitiveSize() == PS) {
7730 // Convert SO1 to GO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +00007731 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +00007732 } else {
7733 const Type *PT = TD->getIntPtrType();
Reid Spencer17212df2006-12-12 09:18:51 +00007734 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
7735 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +00007736 }
7737 }
7738 }
Chris Lattner620ce142004-05-07 22:09:22 +00007739 if (isa<Constant>(SO1) && isa<Constant>(GO1))
7740 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
7741 else {
Chris Lattner48595f12004-06-10 02:07:29 +00007742 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
7743 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner620ce142004-05-07 22:09:22 +00007744 }
Chris Lattner28977af2004-04-05 01:30:19 +00007745 }
Chris Lattner620ce142004-05-07 22:09:22 +00007746
7747 // Recycle the GEP we already have if possible.
7748 if (SrcGEPOperands.size() == 2) {
7749 GEP.setOperand(0, SrcGEPOperands[0]);
7750 GEP.setOperand(1, Sum);
7751 return &GEP;
7752 } else {
7753 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
7754 SrcGEPOperands.end()-1);
7755 Indices.push_back(Sum);
7756 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
7757 }
Misha Brukmanfd939082005-04-21 23:48:37 +00007758 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +00007759 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanfd939082005-04-21 23:48:37 +00007760 SrcGEPOperands.size() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +00007761 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerebd985c2004-03-25 22:59:29 +00007762 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
7763 SrcGEPOperands.end());
Chris Lattner90ac28c2002-08-02 19:29:35 +00007764 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
7765 }
7766
7767 if (!Indices.empty())
Chris Lattnerebd985c2004-03-25 22:59:29 +00007768 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
Chris Lattner9b761232002-08-17 22:21:59 +00007769
Chris Lattner620ce142004-05-07 22:09:22 +00007770 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattner9b761232002-08-17 22:21:59 +00007771 // GEP of global variable. If all of the indices for this GEP are
7772 // constants, we can promote this to a constexpr instead of an instruction.
7773
7774 // Scan for nonconstants...
7775 std::vector<Constant*> Indices;
7776 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
7777 for (; I != E && isa<Constant>(*I); ++I)
7778 Indices.push_back(cast<Constant>(*I));
7779
7780 if (I == E) { // If they are all constants...
Chris Lattner9db07b92004-07-18 18:59:44 +00007781 Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
Chris Lattner9b761232002-08-17 22:21:59 +00007782
7783 // Replace all uses of the GEP with the new constexpr...
7784 return ReplaceInstUsesWith(GEP, CE);
7785 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007786 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
Chris Lattnereed48272005-09-13 00:40:14 +00007787 if (!isa<PointerType>(X->getType())) {
7788 // Not interesting. Source pointer must be a cast from pointer.
7789 } else if (HasZeroPointerIndex) {
7790 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
7791 // into : GEP [10 x ubyte]* X, long 0, ...
7792 //
7793 // This occurs when the program declares an array extern like "int X[];"
7794 //
7795 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
7796 const PointerType *XTy = cast<PointerType>(X->getType());
7797 if (const ArrayType *XATy =
7798 dyn_cast<ArrayType>(XTy->getElementType()))
7799 if (const ArrayType *CATy =
7800 dyn_cast<ArrayType>(CPTy->getElementType()))
7801 if (CATy->getElementType() == XATy->getElementType()) {
7802 // At this point, we know that the cast source type is a pointer
7803 // to an array of the same type as the destination pointer
7804 // array. Because the array type is never stepped over (there
7805 // is a leading zero) we can fold the cast into this GEP.
7806 GEP.setOperand(0, X);
7807 return &GEP;
7808 }
7809 } else if (GEP.getNumOperands() == 2) {
7810 // Transform things like:
Chris Lattner7835cdd2005-09-13 18:36:04 +00007811 // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
7812 // into: %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
Chris Lattnereed48272005-09-13 00:40:14 +00007813 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
7814 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
7815 if (isa<ArrayType>(SrcElTy) &&
7816 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
7817 TD->getTypeSize(ResElTy)) {
7818 Value *V = InsertNewInstBefore(
Reid Spencerc5b206b2006-12-31 05:48:39 +00007819 new GetElementPtrInst(X, Constant::getNullValue(Type::Int32Ty),
Chris Lattnereed48272005-09-13 00:40:14 +00007820 GEP.getOperand(1), GEP.getName()), GEP);
Reid Spencer3da59db2006-11-27 01:05:10 +00007821 // V and GEP are both pointer types --> BitCast
7822 return new BitCastInst(V, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +00007823 }
Chris Lattner7835cdd2005-09-13 18:36:04 +00007824
7825 // Transform things like:
7826 // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
7827 // (where tmp = 8*tmp2) into:
7828 // getelementptr [100 x double]* %arr, int 0, int %tmp.2
7829
7830 if (isa<ArrayType>(SrcElTy) &&
Reid Spencerc5b206b2006-12-31 05:48:39 +00007831 (ResElTy == Type::Int8Ty || ResElTy == Type::Int8Ty)) {
Chris Lattner7835cdd2005-09-13 18:36:04 +00007832 uint64_t ArrayEltSize =
7833 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
7834
7835 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
7836 // allow either a mul, shift, or constant here.
7837 Value *NewIdx = 0;
7838 ConstantInt *Scale = 0;
7839 if (ArrayEltSize == 1) {
7840 NewIdx = GEP.getOperand(1);
7841 Scale = ConstantInt::get(NewIdx->getType(), 1);
7842 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattner6e2f8432005-09-14 17:32:56 +00007843 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +00007844 Scale = CI;
7845 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
7846 if (Inst->getOpcode() == Instruction::Shl &&
7847 isa<ConstantInt>(Inst->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00007848 unsigned ShAmt =
7849 cast<ConstantInt>(Inst->getOperand(1))->getZExtValue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00007850 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmt);
Chris Lattner7835cdd2005-09-13 18:36:04 +00007851 NewIdx = Inst->getOperand(0);
7852 } else if (Inst->getOpcode() == Instruction::Mul &&
7853 isa<ConstantInt>(Inst->getOperand(1))) {
7854 Scale = cast<ConstantInt>(Inst->getOperand(1));
7855 NewIdx = Inst->getOperand(0);
7856 }
7857 }
7858
7859 // If the index will be to exactly the right offset with the scale taken
7860 // out, perform the transformation.
Reid Spencerb83eb642006-10-20 07:07:24 +00007861 if (Scale && Scale->getZExtValue() % ArrayEltSize == 0) {
Reid Spencer3ed469c2006-11-02 20:25:50 +00007862 if (isa<ConstantInt>(Scale))
Reid Spencerb83eb642006-10-20 07:07:24 +00007863 Scale = ConstantInt::get(Scale->getType(),
7864 Scale->getZExtValue() / ArrayEltSize);
7865 if (Scale->getZExtValue() != 1) {
Reid Spencer17212df2006-12-12 09:18:51 +00007866 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
7867 true /*SExt*/);
Chris Lattner7835cdd2005-09-13 18:36:04 +00007868 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
7869 NewIdx = InsertNewInstBefore(Sc, GEP);
7870 }
7871
7872 // Insert the new GEP instruction.
Reid Spencer3da59db2006-11-27 01:05:10 +00007873 Instruction *NewGEP =
Reid Spencerc5b206b2006-12-31 05:48:39 +00007874 new GetElementPtrInst(X, Constant::getNullValue(Type::Int32Ty),
Chris Lattner7835cdd2005-09-13 18:36:04 +00007875 NewIdx, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +00007876 NewGEP = InsertNewInstBefore(NewGEP, GEP);
7877 // The NewGEP must be pointer typed, so must the old one -> BitCast
7878 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +00007879 }
7880 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +00007881 }
Chris Lattner8a2a3112001-12-14 16:52:21 +00007882 }
7883
Chris Lattner8a2a3112001-12-14 16:52:21 +00007884 return 0;
7885}
7886
Chris Lattner0864acf2002-11-04 16:18:53 +00007887Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
7888 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
7889 if (AI.isArrayAllocation()) // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +00007890 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
7891 const Type *NewTy =
7892 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattner0006bd72002-11-09 00:49:43 +00007893 AllocationInst *New = 0;
Chris Lattner0864acf2002-11-04 16:18:53 +00007894
7895 // Create and insert the replacement instruction...
7896 if (isa<MallocInst>(AI))
Nate Begeman14b05292005-11-05 09:21:28 +00007897 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +00007898 else {
7899 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman14b05292005-11-05 09:21:28 +00007900 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +00007901 }
Chris Lattner7c881df2004-03-19 06:08:10 +00007902
7903 InsertNewInstBefore(New, AI);
Misha Brukmanfd939082005-04-21 23:48:37 +00007904
Chris Lattner0864acf2002-11-04 16:18:53 +00007905 // Scan to the end of the allocation instructions, to skip over a block of
7906 // allocas if possible...
7907 //
7908 BasicBlock::iterator It = New;
7909 while (isa<AllocationInst>(*It)) ++It;
7910
7911 // Now that I is pointing to the first non-allocation-inst in the block,
7912 // insert our getelementptr instruction...
7913 //
Reid Spencerc5b206b2006-12-31 05:48:39 +00007914 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
Chris Lattner693787a2005-05-04 19:10:26 +00007915 Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
7916 New->getName()+".sub", It);
Chris Lattner0864acf2002-11-04 16:18:53 +00007917
7918 // Now make everything use the getelementptr instead of the original
7919 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +00007920 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +00007921 } else if (isa<UndefValue>(AI.getArraySize())) {
7922 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +00007923 }
Chris Lattner7c881df2004-03-19 06:08:10 +00007924
7925 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
7926 // Note that we only do this for alloca's, because malloc should allocate and
7927 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanfd939082005-04-21 23:48:37 +00007928 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Chris Lattnercf27afb2004-07-02 22:55:47 +00007929 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattner7c881df2004-03-19 06:08:10 +00007930 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
7931
Chris Lattner0864acf2002-11-04 16:18:53 +00007932 return 0;
7933}
7934
Chris Lattner67b1e1b2003-12-07 01:24:23 +00007935Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
7936 Value *Op = FI.getOperand(0);
7937
7938 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
7939 if (CastInst *CI = dyn_cast<CastInst>(Op))
7940 if (isa<PointerType>(CI->getOperand(0)->getType())) {
7941 FI.setOperand(0, CI->getOperand(0));
7942 return &FI;
7943 }
7944
Chris Lattner17be6352004-10-18 02:59:09 +00007945 // free undef -> unreachable.
7946 if (isa<UndefValue>(Op)) {
7947 // Insert a new store to null because we cannot modify the CFG here.
Chris Lattner47811b72006-09-28 23:35:22 +00007948 new StoreInst(ConstantBool::getTrue(),
Chris Lattner17be6352004-10-18 02:59:09 +00007949 UndefValue::get(PointerType::get(Type::BoolTy)), &FI);
7950 return EraseInstFromFunction(FI);
7951 }
7952
Chris Lattner6160e852004-02-28 04:57:37 +00007953 // If we have 'free null' delete the instruction. This can happen in stl code
7954 // when lots of inlining happens.
Chris Lattner17be6352004-10-18 02:59:09 +00007955 if (isa<ConstantPointerNull>(Op))
Chris Lattner7bcc0e72004-02-28 05:22:00 +00007956 return EraseInstFromFunction(FI);
Chris Lattner6160e852004-02-28 04:57:37 +00007957
Chris Lattner67b1e1b2003-12-07 01:24:23 +00007958 return 0;
7959}
7960
7961
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00007962/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Chris Lattnerb89e0712004-07-13 01:49:43 +00007963static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
7964 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +00007965 Value *CastOp = CI->getOperand(0);
Chris Lattnerb89e0712004-07-13 01:49:43 +00007966
7967 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +00007968 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattnerb89e0712004-07-13 01:49:43 +00007969 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +00007970
Chris Lattnera1c35382006-04-02 05:37:12 +00007971 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
7972 isa<PackedType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +00007973 // If the source is an array, the code below will not succeed. Check to
7974 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
7975 // constants.
7976 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
7977 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
7978 if (ASrcTy->getNumElements() != 0) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007979 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::Int32Ty));
Chris Lattnerf9527852005-01-31 04:50:46 +00007980 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
7981 SrcTy = cast<PointerType>(CastOp->getType());
7982 SrcPTy = SrcTy->getElementType();
7983 }
7984
Chris Lattnera1c35382006-04-02 05:37:12 +00007985 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
7986 isa<PackedType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +00007987 // Do not allow turning this into a load of an integer, which is then
7988 // casted to a pointer, this pessimizes pointer analysis a lot.
7989 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Misha Brukmanfd939082005-04-21 23:48:37 +00007990 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattnerf9527852005-01-31 04:50:46 +00007991 IC.getTargetData().getTypeSize(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +00007992
Chris Lattnerf9527852005-01-31 04:50:46 +00007993 // Okay, we are casting from one integer or pointer type to another of
7994 // the same size. Instead of casting the pointer before the load, cast
7995 // the result of the loaded value.
7996 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
7997 CI->getName(),
7998 LI.isVolatile()),LI);
7999 // Now cast the result of the load.
Reid Spencerd977d862006-12-12 23:36:14 +00008000 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerf9527852005-01-31 04:50:46 +00008001 }
Chris Lattnerb89e0712004-07-13 01:49:43 +00008002 }
8003 }
8004 return 0;
8005}
8006
Chris Lattnerc10aced2004-09-19 18:43:46 +00008007/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattner8a375202004-09-19 19:18:10 +00008008/// from this value cannot trap. If it is not obviously safe to load from the
8009/// specified pointer, we do a quick local scan of the basic block containing
8010/// ScanFrom, to determine if the address is already accessed.
8011static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
8012 // If it is an alloca or global variable, it is always safe to load from.
8013 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
8014
8015 // Otherwise, be a little bit agressive by scanning the local block where we
8016 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00008017 // from/to. If so, the previous load or store would have already trapped,
8018 // so there is no harm doing an extra load (also, CSE will later eliminate
8019 // the load entirely).
Chris Lattner8a375202004-09-19 19:18:10 +00008020 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
8021
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00008022 while (BBI != E) {
Chris Lattner8a375202004-09-19 19:18:10 +00008023 --BBI;
8024
8025 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
8026 if (LI->getOperand(0) == V) return true;
8027 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
8028 if (SI->getOperand(1) == V) return true;
Misha Brukmanfd939082005-04-21 23:48:37 +00008029
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00008030 }
Chris Lattner8a375202004-09-19 19:18:10 +00008031 return false;
Chris Lattnerc10aced2004-09-19 18:43:46 +00008032}
8033
Chris Lattner833b8a42003-06-26 05:06:25 +00008034Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
8035 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +00008036
Chris Lattner37366c12005-05-01 04:24:53 +00008037 // load (cast X) --> cast (load X) iff safe
Reid Spencer3ed469c2006-11-02 20:25:50 +00008038 if (isa<CastInst>(Op))
Chris Lattner37366c12005-05-01 04:24:53 +00008039 if (Instruction *Res = InstCombineLoadCast(*this, LI))
8040 return Res;
8041
8042 // None of the following transforms are legal for volatile loads.
8043 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +00008044
Chris Lattner62f254d2005-09-12 22:00:15 +00008045 if (&LI.getParent()->front() != &LI) {
8046 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattner9c1f0fd2005-09-12 22:21:03 +00008047 // If the instruction immediately before this is a store to the same
8048 // address, do a simple form of store->load forwarding.
Chris Lattner62f254d2005-09-12 22:00:15 +00008049 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
8050 if (SI->getOperand(1) == LI.getOperand(0))
8051 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattner9c1f0fd2005-09-12 22:21:03 +00008052 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
8053 if (LIB->getOperand(0) == LI.getOperand(0))
8054 return ReplaceInstUsesWith(LI, LIB);
Chris Lattner62f254d2005-09-12 22:00:15 +00008055 }
Chris Lattner37366c12005-05-01 04:24:53 +00008056
8057 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
8058 if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
8059 isa<UndefValue>(GEPI->getOperand(0))) {
8060 // Insert a new store to null instruction before the load to indicate
8061 // that this code is not reachable. We do this instead of inserting
8062 // an unreachable instruction directly because we cannot modify the
8063 // CFG.
8064 new StoreInst(UndefValue::get(LI.getType()),
8065 Constant::getNullValue(Op->getType()), &LI);
8066 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8067 }
8068
Chris Lattnere87597f2004-10-16 18:11:37 +00008069 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner37366c12005-05-01 04:24:53 +00008070 // load null/undef -> undef
8071 if ((C->isNullValue() || isa<UndefValue>(C))) {
Chris Lattner17be6352004-10-18 02:59:09 +00008072 // Insert a new store to null instruction before the load to indicate that
8073 // this code is not reachable. We do this instead of inserting an
8074 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattner37366c12005-05-01 04:24:53 +00008075 new StoreInst(UndefValue::get(LI.getType()),
8076 Constant::getNullValue(Op->getType()), &LI);
Chris Lattnere87597f2004-10-16 18:11:37 +00008077 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner17be6352004-10-18 02:59:09 +00008078 }
Chris Lattner833b8a42003-06-26 05:06:25 +00008079
Chris Lattnere87597f2004-10-16 18:11:37 +00008080 // Instcombine load (constant global) into the value loaded.
8081 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
8082 if (GV->isConstant() && !GV->isExternal())
8083 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +00008084
Chris Lattnere87597f2004-10-16 18:11:37 +00008085 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
8086 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
8087 if (CE->getOpcode() == Instruction::GetElementPtr) {
8088 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
8089 if (GV->isConstant() && !GV->isExternal())
Chris Lattner363f2a22005-09-26 05:28:06 +00008090 if (Constant *V =
8091 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattnere87597f2004-10-16 18:11:37 +00008092 return ReplaceInstUsesWith(LI, V);
Chris Lattner37366c12005-05-01 04:24:53 +00008093 if (CE->getOperand(0)->isNullValue()) {
8094 // Insert a new store to null instruction before the load to indicate
8095 // that this code is not reachable. We do this instead of inserting
8096 // an unreachable instruction directly because we cannot modify the
8097 // CFG.
8098 new StoreInst(UndefValue::get(LI.getType()),
8099 Constant::getNullValue(Op->getType()), &LI);
8100 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8101 }
8102
Reid Spencer3da59db2006-11-27 01:05:10 +00008103 } else if (CE->isCast()) {
Chris Lattnere87597f2004-10-16 18:11:37 +00008104 if (Instruction *Res = InstCombineLoadCast(*this, LI))
8105 return Res;
8106 }
8107 }
Chris Lattnerf499eac2004-04-08 20:39:49 +00008108
Chris Lattner37366c12005-05-01 04:24:53 +00008109 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +00008110 // Change select and PHI nodes to select values instead of addresses: this
8111 // helps alias analysis out a lot, allows many others simplifications, and
8112 // exposes redundancy in the code.
8113 //
8114 // Note that we cannot do the transformation unless we know that the
8115 // introduced loads cannot trap! Something like this is valid as long as
8116 // the condition is always false: load (select bool %C, int* null, int* %G),
8117 // but it would not be valid if we transformed it to load from null
8118 // unconditionally.
8119 //
8120 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
8121 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +00008122 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
8123 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerc10aced2004-09-19 18:43:46 +00008124 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner79f0c8e2004-09-20 10:15:10 +00008125 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +00008126 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner79f0c8e2004-09-20 10:15:10 +00008127 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +00008128 return new SelectInst(SI->getCondition(), V1, V2);
8129 }
8130
Chris Lattner684fe212004-09-23 15:46:00 +00008131 // load (select (cond, null, P)) -> load P
8132 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
8133 if (C->isNullValue()) {
8134 LI.setOperand(0, SI->getOperand(2));
8135 return &LI;
8136 }
8137
8138 // load (select (cond, P, null)) -> load P
8139 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
8140 if (C->isNullValue()) {
8141 LI.setOperand(0, SI->getOperand(1));
8142 return &LI;
8143 }
Chris Lattnerc10aced2004-09-19 18:43:46 +00008144 }
8145 }
Chris Lattner833b8a42003-06-26 05:06:25 +00008146 return 0;
8147}
8148
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00008149/// InstCombineStoreToCast - Fold 'store V, (cast P)' -> store (cast V), P'
8150/// when possible.
8151static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
8152 User *CI = cast<User>(SI.getOperand(1));
8153 Value *CastOp = CI->getOperand(0);
8154
8155 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
8156 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
8157 const Type *SrcPTy = SrcTy->getElementType();
8158
8159 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
8160 // If the source is an array, the code below will not succeed. Check to
8161 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
8162 // constants.
8163 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
8164 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
8165 if (ASrcTy->getNumElements() != 0) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00008166 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::Int32Ty));
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00008167 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
8168 SrcTy = cast<PointerType>(CastOp->getType());
8169 SrcPTy = SrcTy->getElementType();
8170 }
8171
8172 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
Misha Brukmanfd939082005-04-21 23:48:37 +00008173 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00008174 IC.getTargetData().getTypeSize(DestPTy)) {
8175
8176 // Okay, we are casting from one integer or pointer type to another of
8177 // the same size. Instead of casting the pointer before the store, cast
8178 // the value to be stored.
8179 Value *NewCast;
Reid Spencerd977d862006-12-12 23:36:14 +00008180 Instruction::CastOps opcode = Instruction::BitCast;
8181 Value *SIOp0 = SI.getOperand(0);
Reid Spencerc55b2432006-12-13 18:21:21 +00008182 if (isa<PointerType>(SrcPTy)) {
Reid Spencerd977d862006-12-12 23:36:14 +00008183 if (SIOp0->getType()->isIntegral())
8184 opcode = Instruction::IntToPtr;
8185 } else if (SrcPTy->isIntegral()) {
Reid Spencerc55b2432006-12-13 18:21:21 +00008186 if (isa<PointerType>(SIOp0->getType()))
Reid Spencerd977d862006-12-12 23:36:14 +00008187 opcode = Instruction::PtrToInt;
8188 }
8189 if (Constant *C = dyn_cast<Constant>(SIOp0))
8190 NewCast = ConstantExpr::getCast(opcode, C, SrcPTy);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00008191 else
Reid Spencer3da59db2006-11-27 01:05:10 +00008192 NewCast = IC.InsertNewInstBefore(
Reid Spencerd977d862006-12-12 23:36:14 +00008193 CastInst::create(opcode, SIOp0, SrcPTy, SIOp0->getName()+".c"), SI);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00008194 return new StoreInst(NewCast, CastOp);
8195 }
8196 }
8197 }
8198 return 0;
8199}
8200
Chris Lattner2f503e62005-01-31 05:36:43 +00008201Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
8202 Value *Val = SI.getOperand(0);
8203 Value *Ptr = SI.getOperand(1);
8204
8205 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner9ca96412006-02-08 03:25:32 +00008206 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +00008207 ++NumCombined;
8208 return 0;
8209 }
8210
Chris Lattner9ca96412006-02-08 03:25:32 +00008211 // Do really simple DSE, to catch cases where there are several consequtive
8212 // stores to the same location, separated by a few arithmetic operations. This
8213 // situation often occurs with bitfield accesses.
8214 BasicBlock::iterator BBI = &SI;
8215 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
8216 --ScanInsts) {
8217 --BBI;
8218
8219 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
8220 // Prev store isn't volatile, and stores to the same location?
8221 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
8222 ++NumDeadStore;
8223 ++BBI;
8224 EraseInstFromFunction(*PrevSI);
8225 continue;
8226 }
8227 break;
8228 }
8229
Chris Lattnerb4db97f2006-05-26 19:19:20 +00008230 // If this is a load, we have to stop. However, if the loaded value is from
8231 // the pointer we're loading and is producing the pointer we're storing,
8232 // then *this* store is dead (X = load P; store X -> P).
8233 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
8234 if (LI == Val && LI->getOperand(0) == Ptr) {
8235 EraseInstFromFunction(SI);
8236 ++NumCombined;
8237 return 0;
8238 }
8239 // Otherwise, this is a load from some other location. Stores before it
8240 // may not be dead.
8241 break;
8242 }
8243
Chris Lattner9ca96412006-02-08 03:25:32 +00008244 // Don't skip over loads or things that can modify memory.
Chris Lattnerb4db97f2006-05-26 19:19:20 +00008245 if (BBI->mayWriteToMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +00008246 break;
8247 }
8248
8249
8250 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +00008251
8252 // store X, null -> turns into 'unreachable' in SimplifyCFG
8253 if (isa<ConstantPointerNull>(Ptr)) {
8254 if (!isa<UndefValue>(Val)) {
8255 SI.setOperand(0, UndefValue::get(Val->getType()));
8256 if (Instruction *U = dyn_cast<Instruction>(Val))
8257 WorkList.push_back(U); // Dropped a use.
8258 ++NumCombined;
8259 }
8260 return 0; // Do not modify these!
8261 }
8262
8263 // store undef, Ptr -> noop
8264 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +00008265 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +00008266 ++NumCombined;
8267 return 0;
8268 }
8269
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00008270 // If the pointer destination is a cast, see if we can fold the cast into the
8271 // source instead.
Reid Spencer3ed469c2006-11-02 20:25:50 +00008272 if (isa<CastInst>(Ptr))
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00008273 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
8274 return Res;
8275 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer3da59db2006-11-27 01:05:10 +00008276 if (CE->isCast())
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00008277 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
8278 return Res;
8279
Chris Lattner408902b2005-09-12 23:23:25 +00008280
8281 // If this store is the last instruction in the basic block, and if the block
8282 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner9ca96412006-02-08 03:25:32 +00008283 BBI = &SI; ++BBI;
Chris Lattner408902b2005-09-12 23:23:25 +00008284 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
8285 if (BI->isUnconditional()) {
8286 // Check to see if the successor block has exactly two incoming edges. If
8287 // so, see if the other predecessor contains a store to the same location.
8288 // if so, insert a PHI node (if needed) and move the stores down.
8289 BasicBlock *Dest = BI->getSuccessor(0);
8290
8291 pred_iterator PI = pred_begin(Dest);
8292 BasicBlock *Other = 0;
8293 if (*PI != BI->getParent())
8294 Other = *PI;
8295 ++PI;
8296 if (PI != pred_end(Dest)) {
8297 if (*PI != BI->getParent())
8298 if (Other)
8299 Other = 0;
8300 else
8301 Other = *PI;
8302 if (++PI != pred_end(Dest))
8303 Other = 0;
8304 }
8305 if (Other) { // If only one other pred...
8306 BBI = Other->getTerminator();
8307 // Make sure this other block ends in an unconditional branch and that
8308 // there is an instruction before the branch.
8309 if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
8310 BBI != Other->begin()) {
8311 --BBI;
8312 StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
8313
8314 // If this instruction is a store to the same location.
8315 if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
8316 // Okay, we know we can perform this transformation. Insert a PHI
8317 // node now if we need it.
8318 Value *MergedVal = OtherStore->getOperand(0);
8319 if (MergedVal != SI.getOperand(0)) {
8320 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
8321 PN->reserveOperandSpace(2);
8322 PN->addIncoming(SI.getOperand(0), SI.getParent());
8323 PN->addIncoming(OtherStore->getOperand(0), Other);
8324 MergedVal = InsertNewInstBefore(PN, Dest->front());
8325 }
8326
8327 // Advance to a place where it is safe to insert the new store and
8328 // insert it.
8329 BBI = Dest->begin();
8330 while (isa<PHINode>(BBI)) ++BBI;
8331 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
8332 OtherStore->isVolatile()), *BBI);
8333
8334 // Nuke the old stores.
Chris Lattner9ca96412006-02-08 03:25:32 +00008335 EraseInstFromFunction(SI);
8336 EraseInstFromFunction(*OtherStore);
Chris Lattner408902b2005-09-12 23:23:25 +00008337 ++NumCombined;
8338 return 0;
8339 }
8340 }
8341 }
8342 }
8343
Chris Lattner2f503e62005-01-31 05:36:43 +00008344 return 0;
8345}
8346
8347
Chris Lattnerc4d10eb2003-06-04 04:46:00 +00008348Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
8349 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +00008350 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00008351 BasicBlock *TrueDest;
8352 BasicBlock *FalseDest;
8353 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
8354 !isa<Constant>(X)) {
8355 // Swap Destinations and condition...
8356 BI.setCondition(X);
8357 BI.setSuccessor(0, FalseDest);
8358 BI.setSuccessor(1, TrueDest);
8359 return &BI;
8360 }
8361
Reid Spencere4d87aa2006-12-23 06:05:41 +00008362 // Cannonicalize fcmp_one -> fcmp_oeq
8363 FCmpInst::Predicate FPred; Value *Y;
8364 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
8365 TrueDest, FalseDest)))
8366 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
8367 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
8368 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
Chris Lattneracd1f0f2004-07-30 07:50:03 +00008369 std::string Name = I->getName(); I->setName("");
Reid Spencere4d87aa2006-12-23 06:05:41 +00008370 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
8371 Value *NewSCC = new FCmpInst(NewPred, X, Y, Name, I);
8372 // Swap Destinations and condition...
8373 BI.setCondition(NewSCC);
8374 BI.setSuccessor(0, FalseDest);
8375 BI.setSuccessor(1, TrueDest);
8376 removeFromWorkList(I);
8377 I->getParent()->getInstList().erase(I);
8378 WorkList.push_back(cast<Instruction>(NewSCC));
8379 return &BI;
8380 }
8381
8382 // Cannonicalize icmp_ne -> icmp_eq
8383 ICmpInst::Predicate IPred;
8384 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
8385 TrueDest, FalseDest)))
8386 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
8387 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
8388 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
8389 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
8390 std::string Name = I->getName(); I->setName("");
8391 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
8392 Value *NewSCC = new ICmpInst(NewPred, X, Y, Name, I);
Chris Lattner40f5d702003-06-04 05:10:11 +00008393 // Swap Destinations and condition...
Chris Lattneracd1f0f2004-07-30 07:50:03 +00008394 BI.setCondition(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +00008395 BI.setSuccessor(0, FalseDest);
8396 BI.setSuccessor(1, TrueDest);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00008397 removeFromWorkList(I);
8398 I->getParent()->getInstList().erase(I);
8399 WorkList.push_back(cast<Instruction>(NewSCC));
Chris Lattner40f5d702003-06-04 05:10:11 +00008400 return &BI;
8401 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008402
Chris Lattnerc4d10eb2003-06-04 04:46:00 +00008403 return 0;
8404}
Chris Lattner0864acf2002-11-04 16:18:53 +00008405
Chris Lattner46238a62004-07-03 00:26:11 +00008406Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
8407 Value *Cond = SI.getCondition();
8408 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
8409 if (I->getOpcode() == Instruction::Add)
8410 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
8411 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
8412 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattnere87597f2004-10-16 18:11:37 +00008413 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +00008414 AddRHS));
8415 SI.setOperand(0, I->getOperand(0));
8416 WorkList.push_back(I);
8417 return &SI;
8418 }
8419 }
8420 return 0;
8421}
8422
Chris Lattner220b0cf2006-03-05 00:22:33 +00008423/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
8424/// is to leave as a vector operation.
8425static bool CheapToScalarize(Value *V, bool isConstant) {
8426 if (isa<ConstantAggregateZero>(V))
8427 return true;
8428 if (ConstantPacked *C = dyn_cast<ConstantPacked>(V)) {
8429 if (isConstant) return true;
8430 // If all elts are the same, we can extract.
8431 Constant *Op0 = C->getOperand(0);
8432 for (unsigned i = 1; i < C->getNumOperands(); ++i)
8433 if (C->getOperand(i) != Op0)
8434 return false;
8435 return true;
8436 }
8437 Instruction *I = dyn_cast<Instruction>(V);
8438 if (!I) return false;
8439
8440 // Insert element gets simplified to the inserted element or is deleted if
8441 // this is constant idx extract element and its a constant idx insertelt.
8442 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
8443 isa<ConstantInt>(I->getOperand(2)))
8444 return true;
8445 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
8446 return true;
8447 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
8448 if (BO->hasOneUse() &&
8449 (CheapToScalarize(BO->getOperand(0), isConstant) ||
8450 CheapToScalarize(BO->getOperand(1), isConstant)))
8451 return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +00008452 if (CmpInst *CI = dyn_cast<CmpInst>(I))
8453 if (CI->hasOneUse() &&
8454 (CheapToScalarize(CI->getOperand(0), isConstant) ||
8455 CheapToScalarize(CI->getOperand(1), isConstant)))
8456 return true;
Chris Lattner220b0cf2006-03-05 00:22:33 +00008457
8458 return false;
8459}
8460
Chris Lattner863bcff2006-05-25 23:48:38 +00008461/// getShuffleMask - Read and decode a shufflevector mask. It turns undef
8462/// elements into values that are larger than the #elts in the input.
8463static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
8464 unsigned NElts = SVI->getType()->getNumElements();
8465 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
8466 return std::vector<unsigned>(NElts, 0);
8467 if (isa<UndefValue>(SVI->getOperand(2)))
8468 return std::vector<unsigned>(NElts, 2*NElts);
8469
8470 std::vector<unsigned> Result;
8471 const ConstantPacked *CP = cast<ConstantPacked>(SVI->getOperand(2));
8472 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
8473 if (isa<UndefValue>(CP->getOperand(i)))
8474 Result.push_back(NElts*2); // undef -> 8
8475 else
Reid Spencerb83eb642006-10-20 07:07:24 +00008476 Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
Chris Lattner863bcff2006-05-25 23:48:38 +00008477 return Result;
8478}
8479
Chris Lattner6e6b0da2006-03-31 23:01:56 +00008480/// FindScalarElement - Given a vector and an element number, see if the scalar
8481/// value is already around as a register, for example if it were inserted then
8482/// extracted from the vector.
8483static Value *FindScalarElement(Value *V, unsigned EltNo) {
8484 assert(isa<PackedType>(V->getType()) && "Not looking at a vector?");
8485 const PackedType *PTy = cast<PackedType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +00008486 unsigned Width = PTy->getNumElements();
8487 if (EltNo >= Width) // Out of range access.
Chris Lattner6e6b0da2006-03-31 23:01:56 +00008488 return UndefValue::get(PTy->getElementType());
8489
8490 if (isa<UndefValue>(V))
8491 return UndefValue::get(PTy->getElementType());
8492 else if (isa<ConstantAggregateZero>(V))
8493 return Constant::getNullValue(PTy->getElementType());
8494 else if (ConstantPacked *CP = dyn_cast<ConstantPacked>(V))
8495 return CP->getOperand(EltNo);
8496 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
8497 // If this is an insert to a variable element, we don't know what it is.
Reid Spencerb83eb642006-10-20 07:07:24 +00008498 if (!isa<ConstantInt>(III->getOperand(2)))
8499 return 0;
8500 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner6e6b0da2006-03-31 23:01:56 +00008501
8502 // If this is an insert to the element we are looking for, return the
8503 // inserted value.
Reid Spencerb83eb642006-10-20 07:07:24 +00008504 if (EltNo == IIElt)
8505 return III->getOperand(1);
Chris Lattner6e6b0da2006-03-31 23:01:56 +00008506
8507 // Otherwise, the insertelement doesn't modify the value, recurse on its
8508 // vector input.
8509 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner389a6f52006-04-10 23:06:36 +00008510 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Chris Lattner863bcff2006-05-25 23:48:38 +00008511 unsigned InEl = getShuffleMask(SVI)[EltNo];
8512 if (InEl < Width)
8513 return FindScalarElement(SVI->getOperand(0), InEl);
8514 else if (InEl < Width*2)
8515 return FindScalarElement(SVI->getOperand(1), InEl - Width);
8516 else
8517 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +00008518 }
8519
8520 // Otherwise, we don't know.
8521 return 0;
8522}
8523
Robert Bocchino1d7456d2006-01-13 22:48:06 +00008524Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Chris Lattner6e6b0da2006-03-31 23:01:56 +00008525
Chris Lattner1f13c882006-03-31 18:25:14 +00008526 // If packed val is undef, replace extract with scalar undef.
8527 if (isa<UndefValue>(EI.getOperand(0)))
8528 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
8529
8530 // If packed val is constant 0, replace extract with scalar 0.
8531 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
8532 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
8533
Robert Bocchino1d7456d2006-01-13 22:48:06 +00008534 if (ConstantPacked *C = dyn_cast<ConstantPacked>(EI.getOperand(0))) {
8535 // If packed val is constant with uniform operands, replace EI
8536 // with that operand
Chris Lattner220b0cf2006-03-05 00:22:33 +00008537 Constant *op0 = C->getOperand(0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +00008538 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +00008539 if (C->getOperand(i) != op0) {
8540 op0 = 0;
8541 break;
8542 }
8543 if (op0)
8544 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +00008545 }
Chris Lattner220b0cf2006-03-05 00:22:33 +00008546
Chris Lattner6e6b0da2006-03-31 23:01:56 +00008547 // If extracting a specified index from the vector, see if we can recursively
8548 // find a previously computed scalar that was inserted into the vector.
Reid Spencerb83eb642006-10-20 07:07:24 +00008549 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner867b99f2006-10-05 06:55:50 +00008550 // This instruction only demands the single element from the input vector.
8551 // If the input vector has a single use, simplify it based on this use
8552 // property.
Reid Spencerb83eb642006-10-20 07:07:24 +00008553 uint64_t IndexVal = IdxC->getZExtValue();
Chris Lattner867b99f2006-10-05 06:55:50 +00008554 if (EI.getOperand(0)->hasOneUse()) {
8555 uint64_t UndefElts;
8556 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Reid Spencerb83eb642006-10-20 07:07:24 +00008557 1 << IndexVal,
Chris Lattner867b99f2006-10-05 06:55:50 +00008558 UndefElts)) {
8559 EI.setOperand(0, V);
8560 return &EI;
8561 }
8562 }
8563
Reid Spencerb83eb642006-10-20 07:07:24 +00008564 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
Chris Lattner6e6b0da2006-03-31 23:01:56 +00008565 return ReplaceInstUsesWith(EI, Elt);
Chris Lattner389a6f52006-04-10 23:06:36 +00008566 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +00008567
Chris Lattner73fa49d2006-05-25 22:53:38 +00008568 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchino1d7456d2006-01-13 22:48:06 +00008569 if (I->hasOneUse()) {
8570 // Push extractelement into predecessor operation if legal and
8571 // profitable to do so
8572 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +00008573 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
8574 if (CheapToScalarize(BO, isConstantElt)) {
8575 ExtractElementInst *newEI0 =
8576 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
8577 EI.getName()+".lhs");
8578 ExtractElementInst *newEI1 =
8579 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
8580 EI.getName()+".rhs");
8581 InsertNewInstBefore(newEI0, EI);
8582 InsertNewInstBefore(newEI1, EI);
8583 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
8584 }
Reid Spencer3ed469c2006-11-02 20:25:50 +00008585 } else if (isa<LoadInst>(I)) {
Reid Spencer17212df2006-12-12 09:18:51 +00008586 Value *Ptr = InsertCastBefore(Instruction::BitCast, I->getOperand(0),
Robert Bocchino1d7456d2006-01-13 22:48:06 +00008587 PointerType::get(EI.getType()), EI);
8588 GetElementPtrInst *GEP =
Reid Spencerde331242006-11-29 01:11:01 +00008589 new GetElementPtrInst(Ptr, EI.getOperand(1), I->getName() + ".gep");
Robert Bocchino1d7456d2006-01-13 22:48:06 +00008590 InsertNewInstBefore(GEP, EI);
8591 return new LoadInst(GEP);
Chris Lattner73fa49d2006-05-25 22:53:38 +00008592 }
8593 }
8594 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
8595 // Extracting the inserted element?
8596 if (IE->getOperand(2) == EI.getOperand(1))
8597 return ReplaceInstUsesWith(EI, IE->getOperand(1));
8598 // If the inserted and extracted elements are constants, they must not
8599 // be the same value, extract from the pre-inserted value instead.
8600 if (isa<Constant>(IE->getOperand(2)) &&
8601 isa<Constant>(EI.getOperand(1))) {
8602 AddUsesToWorkList(EI);
8603 EI.setOperand(0, IE->getOperand(0));
8604 return &EI;
8605 }
8606 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
8607 // If this is extracting an element from a shufflevector, figure out where
8608 // it came from and extract from the appropriate input element instead.
Reid Spencerb83eb642006-10-20 07:07:24 +00008609 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
8610 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner863bcff2006-05-25 23:48:38 +00008611 Value *Src;
8612 if (SrcIdx < SVI->getType()->getNumElements())
8613 Src = SVI->getOperand(0);
8614 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
8615 SrcIdx -= SVI->getType()->getNumElements();
8616 Src = SVI->getOperand(1);
8617 } else {
8618 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +00008619 }
Chris Lattner867b99f2006-10-05 06:55:50 +00008620 return new ExtractElementInst(Src, SrcIdx);
Robert Bocchino1d7456d2006-01-13 22:48:06 +00008621 }
8622 }
Chris Lattner73fa49d2006-05-25 22:53:38 +00008623 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +00008624 return 0;
8625}
8626
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00008627/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
8628/// elements from either LHS or RHS, return the shuffle mask and true.
8629/// Otherwise, return false.
8630static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
8631 std::vector<Constant*> &Mask) {
8632 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
8633 "Invalid CollectSingleShuffleElements");
8634 unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
8635
8636 if (isa<UndefValue>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00008637 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00008638 return true;
8639 } else if (V == LHS) {
8640 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +00008641 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00008642 return true;
8643 } else if (V == RHS) {
8644 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +00008645 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00008646 return true;
8647 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
8648 // If this is an insert of an extract from some other vector, include it.
8649 Value *VecOp = IEI->getOperand(0);
8650 Value *ScalarOp = IEI->getOperand(1);
8651 Value *IdxOp = IEI->getOperand(2);
8652
Chris Lattnerd929f062006-04-27 21:14:21 +00008653 if (!isa<ConstantInt>(IdxOp))
8654 return false;
Reid Spencerb83eb642006-10-20 07:07:24 +00008655 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerd929f062006-04-27 21:14:21 +00008656
8657 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
8658 // Okay, we can handle this if the vector we are insertinting into is
8659 // transitively ok.
8660 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
8661 // If so, update the mask to reflect the inserted undef.
Reid Spencerc5b206b2006-12-31 05:48:39 +00008662 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
Chris Lattnerd929f062006-04-27 21:14:21 +00008663 return true;
8664 }
8665 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
8666 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00008667 EI->getOperand(0)->getType() == V->getType()) {
8668 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +00008669 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00008670
8671 // This must be extracting from either LHS or RHS.
8672 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
8673 // Okay, we can handle this if the vector we are insertinting into is
8674 // transitively ok.
8675 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
8676 // If so, update the mask to reflect the inserted value.
8677 if (EI->getOperand(0) == LHS) {
8678 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +00008679 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00008680 } else {
8681 assert(EI->getOperand(0) == RHS);
8682 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +00008683 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00008684
8685 }
8686 return true;
8687 }
8688 }
8689 }
8690 }
8691 }
8692 // TODO: Handle shufflevector here!
8693
8694 return false;
8695}
8696
8697/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
8698/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
8699/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +00008700static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00008701 Value *&RHS) {
8702 assert(isa<PackedType>(V->getType()) &&
8703 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +00008704 "Invalid shuffle!");
8705 unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
8706
8707 if (isa<UndefValue>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00008708 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +00008709 return V;
8710 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00008711 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
Chris Lattnerefb47352006-04-15 01:39:45 +00008712 return V;
8713 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
8714 // If this is an insert of an extract from some other vector, include it.
8715 Value *VecOp = IEI->getOperand(0);
8716 Value *ScalarOp = IEI->getOperand(1);
8717 Value *IdxOp = IEI->getOperand(2);
8718
8719 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
8720 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
8721 EI->getOperand(0)->getType() == V->getType()) {
8722 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +00008723 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8724 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +00008725
8726 // Either the extracted from or inserted into vector must be RHSVec,
8727 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00008728 if (EI->getOperand(0) == RHS || RHS == 0) {
8729 RHS = EI->getOperand(0);
8730 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +00008731 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +00008732 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +00008733 return V;
8734 }
8735
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00008736 if (VecOp == RHS) {
8737 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +00008738 // Everything but the extracted element is replaced with the RHS.
8739 for (unsigned i = 0; i != NumElts; ++i) {
8740 if (i != InsertedIdx)
Reid Spencerc5b206b2006-12-31 05:48:39 +00008741 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
Chris Lattnerefb47352006-04-15 01:39:45 +00008742 }
8743 return V;
8744 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00008745
8746 // If this insertelement is a chain that comes from exactly these two
8747 // vectors, return the vector and the effective shuffle.
8748 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
8749 return EI->getOperand(0);
8750
Chris Lattnerefb47352006-04-15 01:39:45 +00008751 }
8752 }
8753 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00008754 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +00008755
8756 // Otherwise, can't do anything fancy. Return an identity vector.
8757 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +00008758 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattnerefb47352006-04-15 01:39:45 +00008759 return V;
8760}
8761
8762Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
8763 Value *VecOp = IE.getOperand(0);
8764 Value *ScalarOp = IE.getOperand(1);
8765 Value *IdxOp = IE.getOperand(2);
8766
8767 // If the inserted element was extracted from some other vector, and if the
8768 // indexes are constant, try to turn this into a shufflevector operation.
8769 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
8770 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
8771 EI->getOperand(0)->getType() == IE.getType()) {
8772 unsigned NumVectorElts = IE.getType()->getNumElements();
Reid Spencerb83eb642006-10-20 07:07:24 +00008773 unsigned ExtractedIdx=cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8774 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +00008775
8776 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
8777 return ReplaceInstUsesWith(IE, VecOp);
8778
8779 if (InsertedIdx >= NumVectorElts) // Out of range insert.
8780 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
8781
8782 // If we are extracting a value from a vector, then inserting it right
8783 // back into the same place, just use the input vector.
8784 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
8785 return ReplaceInstUsesWith(IE, VecOp);
8786
8787 // We could theoretically do this for ANY input. However, doing so could
8788 // turn chains of insertelement instructions into a chain of shufflevector
8789 // instructions, and right now we do not merge shufflevectors. As such,
8790 // only do this in a situation where it is clear that there is benefit.
8791 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
8792 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
8793 // the values of VecOp, except then one read from EIOp0.
8794 // Build a new shuffle mask.
8795 std::vector<Constant*> Mask;
8796 if (isa<UndefValue>(VecOp))
Reid Spencerc5b206b2006-12-31 05:48:39 +00008797 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +00008798 else {
8799 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Reid Spencerc5b206b2006-12-31 05:48:39 +00008800 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
Chris Lattnerefb47352006-04-15 01:39:45 +00008801 NumVectorElts));
8802 }
Reid Spencerc5b206b2006-12-31 05:48:39 +00008803 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +00008804 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
8805 ConstantPacked::get(Mask));
8806 }
8807
8808 // If this insertelement isn't used by some other insertelement, turn it
8809 // (and any insertelements it points to), into one big shuffle.
8810 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
8811 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00008812 Value *RHS = 0;
8813 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
8814 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
8815 // We now have a shuffle of LHS, RHS, Mask.
8816 return new ShuffleVectorInst(LHS, RHS, ConstantPacked::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +00008817 }
8818 }
8819 }
8820
8821 return 0;
8822}
8823
8824
Chris Lattnera844fc4c2006-04-10 22:45:52 +00008825Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
8826 Value *LHS = SVI.getOperand(0);
8827 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +00008828 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +00008829
8830 bool MadeChange = false;
8831
Chris Lattner867b99f2006-10-05 06:55:50 +00008832 // Undefined shuffle mask -> undefined value.
Chris Lattner863bcff2006-05-25 23:48:38 +00008833 if (isa<UndefValue>(SVI.getOperand(2)))
Chris Lattnera844fc4c2006-04-10 22:45:52 +00008834 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
8835
Chris Lattnerefb47352006-04-15 01:39:45 +00008836 // TODO: If we have shuffle(x, undef, mask) and any elements of mask refer to
8837 // the undef, change them to undefs.
8838
Chris Lattner863bcff2006-05-25 23:48:38 +00008839 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
8840 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
8841 if (LHS == RHS || isa<UndefValue>(LHS)) {
8842 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +00008843 // shuffle(undef,undef,mask) -> undef.
8844 return ReplaceInstUsesWith(SVI, LHS);
8845 }
8846
Chris Lattner863bcff2006-05-25 23:48:38 +00008847 // Remap any references to RHS to use LHS.
8848 std::vector<Constant*> Elts;
8849 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +00008850 if (Mask[i] >= 2*e)
Reid Spencerc5b206b2006-12-31 05:48:39 +00008851 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +00008852 else {
8853 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
8854 (Mask[i] < e && isa<UndefValue>(LHS)))
8855 Mask[i] = 2*e; // Turn into undef.
8856 else
8857 Mask[i] &= (e-1); // Force to LHS.
Reid Spencerc5b206b2006-12-31 05:48:39 +00008858 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +00008859 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +00008860 }
Chris Lattner863bcff2006-05-25 23:48:38 +00008861 SVI.setOperand(0, SVI.getOperand(1));
Chris Lattnera844fc4c2006-04-10 22:45:52 +00008862 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Chris Lattner863bcff2006-05-25 23:48:38 +00008863 SVI.setOperand(2, ConstantPacked::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +00008864 LHS = SVI.getOperand(0);
8865 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +00008866 MadeChange = true;
8867 }
8868
Chris Lattner7b2e27922006-05-26 00:29:06 +00008869 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +00008870 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +00008871
Chris Lattner863bcff2006-05-25 23:48:38 +00008872 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
8873 if (Mask[i] >= e*2) continue; // Ignore undef values.
8874 // Is this an identity shuffle of the LHS value?
8875 isLHSID &= (Mask[i] == i);
8876
8877 // Is this an identity shuffle of the RHS value?
8878 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +00008879 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +00008880
Chris Lattner863bcff2006-05-25 23:48:38 +00008881 // Eliminate identity shuffles.
8882 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
8883 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +00008884
Chris Lattner7b2e27922006-05-26 00:29:06 +00008885 // If the LHS is a shufflevector itself, see if we can combine it with this
8886 // one without producing an unusual shuffle. Here we are really conservative:
8887 // we are absolutely afraid of producing a shuffle mask not in the input
8888 // program, because the code gen may not be smart enough to turn a merged
8889 // shuffle into two specific shuffles: it may produce worse code. As such,
8890 // we only merge two shuffles if the result is one of the two input shuffle
8891 // masks. In this case, merging the shuffles just removes one instruction,
8892 // which we know is safe. This is good for things like turning:
8893 // (splat(splat)) -> splat.
8894 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
8895 if (isa<UndefValue>(RHS)) {
8896 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
8897
8898 std::vector<unsigned> NewMask;
8899 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
8900 if (Mask[i] >= 2*e)
8901 NewMask.push_back(2*e);
8902 else
8903 NewMask.push_back(LHSMask[Mask[i]]);
8904
8905 // If the result mask is equal to the src shuffle or this shuffle mask, do
8906 // the replacement.
8907 if (NewMask == LHSMask || NewMask == Mask) {
8908 std::vector<Constant*> Elts;
8909 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
8910 if (NewMask[i] >= e*2) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00008911 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +00008912 } else {
Reid Spencerc5b206b2006-12-31 05:48:39 +00008913 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +00008914 }
8915 }
8916 return new ShuffleVectorInst(LHSSVI->getOperand(0),
8917 LHSSVI->getOperand(1),
8918 ConstantPacked::get(Elts));
8919 }
8920 }
8921 }
8922
Chris Lattnera844fc4c2006-04-10 22:45:52 +00008923 return MadeChange ? &SVI : 0;
8924}
8925
8926
Robert Bocchino1d7456d2006-01-13 22:48:06 +00008927
Chris Lattner62b14df2002-09-02 04:59:56 +00008928void InstCombiner::removeFromWorkList(Instruction *I) {
8929 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
8930 WorkList.end());
8931}
8932
Chris Lattnerea1c4542004-12-08 23:43:58 +00008933
8934/// TryToSinkInstruction - Try to move the specified instruction from its
8935/// current block into the beginning of DestBlock, which can only happen if it's
8936/// safe to move the instruction past all of the instructions between it and the
8937/// end of its block.
8938static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
8939 assert(I->hasOneUse() && "Invariants didn't hold!");
8940
Chris Lattner108e9022005-10-27 17:13:11 +00008941 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
8942 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
Misha Brukmanfd939082005-04-21 23:48:37 +00008943
Chris Lattnerea1c4542004-12-08 23:43:58 +00008944 // Do not sink alloca instructions out of the entry block.
8945 if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
8946 return false;
8947
Chris Lattner96a52a62004-12-09 07:14:34 +00008948 // We can only sink load instructions if there is nothing between the load and
8949 // the end of block that could change the value.
8950 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattner96a52a62004-12-09 07:14:34 +00008951 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
8952 Scan != E; ++Scan)
8953 if (Scan->mayWriteToMemory())
8954 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +00008955 }
Chris Lattnerea1c4542004-12-08 23:43:58 +00008956
8957 BasicBlock::iterator InsertPos = DestBlock->begin();
8958 while (isa<PHINode>(InsertPos)) ++InsertPos;
8959
Chris Lattner4bc5f802005-08-08 19:11:57 +00008960 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +00008961 ++NumSunkInst;
8962 return true;
8963}
8964
Chris Lattner8c8c66a2006-05-11 17:11:52 +00008965/// OptimizeConstantExpr - Given a constant expression and target data layout
Reid Spencer17212df2006-12-12 09:18:51 +00008966/// information, symbolically evaluate the constant expr to something simpler
Chris Lattner8c8c66a2006-05-11 17:11:52 +00008967/// if possible.
8968static Constant *OptimizeConstantExpr(ConstantExpr *CE, const TargetData *TD) {
8969 if (!TD) return CE;
8970
8971 Constant *Ptr = CE->getOperand(0);
8972 if (CE->getOpcode() == Instruction::GetElementPtr && Ptr->isNullValue() &&
8973 cast<PointerType>(Ptr->getType())->getElementType()->isSized()) {
8974 // If this is a constant expr gep that is effectively computing an
8975 // "offsetof", fold it into 'cast int Size to T*' instead of 'gep 0, 0, 12'
8976 bool isFoldableGEP = true;
8977 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
8978 if (!isa<ConstantInt>(CE->getOperand(i)))
8979 isFoldableGEP = false;
8980 if (isFoldableGEP) {
8981 std::vector<Value*> Ops(CE->op_begin()+1, CE->op_end());
8982 uint64_t Offset = TD->getIndexedOffset(Ptr->getType(), Ops);
Reid Spencer7eb76382006-12-13 17:19:09 +00008983 Constant *C = ConstantInt::get(TD->getIntPtrType(), Offset);
Reid Spencer17212df2006-12-12 09:18:51 +00008984 return ConstantExpr::getIntToPtr(C, CE->getType());
Chris Lattner8c8c66a2006-05-11 17:11:52 +00008985 }
8986 }
8987
8988 return CE;
8989}
8990
Chris Lattnerf4f5a772006-05-10 19:00:36 +00008991
8992/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
8993/// all reachable code to the worklist.
8994///
8995/// This has a couple of tricks to make the code faster and more powerful. In
8996/// particular, we constant fold and DCE instructions as we go, to avoid adding
8997/// them to the worklist (this significantly speeds up instcombine on code where
8998/// many instructions are dead or constant). Additionally, if we find a branch
8999/// whose condition is a known constant, we only visit the reachable successors.
9000///
9001static void AddReachableCodeToWorklist(BasicBlock *BB,
9002 std::set<BasicBlock*> &Visited,
Chris Lattner8c8c66a2006-05-11 17:11:52 +00009003 std::vector<Instruction*> &WorkList,
9004 const TargetData *TD) {
Chris Lattnerf4f5a772006-05-10 19:00:36 +00009005 // We have now visited this block! If we've already been here, bail out.
9006 if (!Visited.insert(BB).second) return;
9007
9008 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
9009 Instruction *Inst = BBI++;
9010
9011 // DCE instruction if trivially dead.
9012 if (isInstructionTriviallyDead(Inst)) {
9013 ++NumDeadInst;
Bill Wendlingb7427032006-11-26 09:46:52 +00009014 DOUT << "IC: DCE: " << *Inst;
Chris Lattnerf4f5a772006-05-10 19:00:36 +00009015 Inst->eraseFromParent();
9016 continue;
9017 }
9018
9019 // ConstantProp instruction if trivially constant.
9020 if (Constant *C = ConstantFoldInstruction(Inst)) {
Chris Lattner8c8c66a2006-05-11 17:11:52 +00009021 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
9022 C = OptimizeConstantExpr(CE, TD);
Bill Wendlingb7427032006-11-26 09:46:52 +00009023 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
Chris Lattnerf4f5a772006-05-10 19:00:36 +00009024 Inst->replaceAllUsesWith(C);
9025 ++NumConstProp;
9026 Inst->eraseFromParent();
9027 continue;
9028 }
9029
9030 WorkList.push_back(Inst);
9031 }
9032
9033 // Recursively visit successors. If this is a branch or switch on a constant,
9034 // only visit the reachable successor.
9035 TerminatorInst *TI = BB->getTerminator();
9036 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
9037 if (BI->isConditional() && isa<ConstantBool>(BI->getCondition())) {
9038 bool CondVal = cast<ConstantBool>(BI->getCondition())->getValue();
Chris Lattner8c8c66a2006-05-11 17:11:52 +00009039 AddReachableCodeToWorklist(BI->getSuccessor(!CondVal), Visited, WorkList,
9040 TD);
Chris Lattnerf4f5a772006-05-10 19:00:36 +00009041 return;
9042 }
9043 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
9044 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
9045 // See if this is an explicit destination.
9046 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
9047 if (SI->getCaseValue(i) == Cond) {
Chris Lattner8c8c66a2006-05-11 17:11:52 +00009048 AddReachableCodeToWorklist(SI->getSuccessor(i), Visited, WorkList,TD);
Chris Lattnerf4f5a772006-05-10 19:00:36 +00009049 return;
9050 }
9051
9052 // Otherwise it is the default destination.
Chris Lattner8c8c66a2006-05-11 17:11:52 +00009053 AddReachableCodeToWorklist(SI->getSuccessor(0), Visited, WorkList, TD);
Chris Lattnerf4f5a772006-05-10 19:00:36 +00009054 return;
9055 }
9056 }
9057
9058 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
Chris Lattner8c8c66a2006-05-11 17:11:52 +00009059 AddReachableCodeToWorklist(TI->getSuccessor(i), Visited, WorkList, TD);
Chris Lattnerf4f5a772006-05-10 19:00:36 +00009060}
9061
Chris Lattner7e708292002-06-25 16:13:24 +00009062bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerdd841ae2002-04-18 17:39:14 +00009063 bool Changed = false;
Chris Lattnerbc61e662003-11-02 05:57:39 +00009064 TD = &getAnalysis<TargetData>();
Chris Lattner8a2a3112001-12-14 16:52:21 +00009065
Chris Lattnerb3d59702005-07-07 20:40:38 +00009066 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +00009067 // Do a depth-first traversal of the function, populate the worklist with
9068 // the reachable instructions. Ignore blocks that are not reachable. Keep
9069 // track of which blocks we visit.
Chris Lattnerb3d59702005-07-07 20:40:38 +00009070 std::set<BasicBlock*> Visited;
Chris Lattner8c8c66a2006-05-11 17:11:52 +00009071 AddReachableCodeToWorklist(F.begin(), Visited, WorkList, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +00009072
Chris Lattnerb3d59702005-07-07 20:40:38 +00009073 // Do a quick scan over the function. If we find any blocks that are
9074 // unreachable, remove any instructions inside of them. This prevents
9075 // the instcombine code from having to deal with some bad special cases.
9076 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
9077 if (!Visited.count(BB)) {
9078 Instruction *Term = BB->getTerminator();
9079 while (Term != BB->begin()) { // Remove instrs bottom-up
9080 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +00009081
Bill Wendlingb7427032006-11-26 09:46:52 +00009082 DOUT << "IC: DCE: " << *I;
Chris Lattnerb3d59702005-07-07 20:40:38 +00009083 ++NumDeadInst;
9084
9085 if (!I->use_empty())
9086 I->replaceAllUsesWith(UndefValue::get(I->getType()));
9087 I->eraseFromParent();
9088 }
9089 }
9090 }
Chris Lattner8a2a3112001-12-14 16:52:21 +00009091
9092 while (!WorkList.empty()) {
9093 Instruction *I = WorkList.back(); // Get an instruction from the worklist
9094 WorkList.pop_back();
9095
Chris Lattner8c8c66a2006-05-11 17:11:52 +00009096 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +00009097 if (isInstructionTriviallyDead(I)) {
Chris Lattner8c8c66a2006-05-11 17:11:52 +00009098 // Add operands to the worklist.
Chris Lattner4bb7c022003-10-06 17:11:01 +00009099 if (I->getNumOperands() < 4)
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009100 AddUsesToWorkList(*I);
Chris Lattner62b14df2002-09-02 04:59:56 +00009101 ++NumDeadInst;
Chris Lattner4bb7c022003-10-06 17:11:01 +00009102
Bill Wendlingb7427032006-11-26 09:46:52 +00009103 DOUT << "IC: DCE: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +00009104
9105 I->eraseFromParent();
Chris Lattner4bb7c022003-10-06 17:11:01 +00009106 removeFromWorkList(I);
9107 continue;
9108 }
Chris Lattner62b14df2002-09-02 04:59:56 +00009109
Chris Lattner8c8c66a2006-05-11 17:11:52 +00009110 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattner62b14df2002-09-02 04:59:56 +00009111 if (Constant *C = ConstantFoldInstruction(I)) {
Chris Lattner8c8c66a2006-05-11 17:11:52 +00009112 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
9113 C = OptimizeConstantExpr(CE, TD);
Bill Wendlingb7427032006-11-26 09:46:52 +00009114 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +00009115
Chris Lattner8c8c66a2006-05-11 17:11:52 +00009116 // Add operands to the worklist.
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009117 AddUsesToWorkList(*I);
Chris Lattnerc736d562002-12-05 22:41:53 +00009118 ReplaceInstUsesWith(*I, C);
9119
Chris Lattner62b14df2002-09-02 04:59:56 +00009120 ++NumConstProp;
Chris Lattnerf4f5a772006-05-10 19:00:36 +00009121 I->eraseFromParent();
Chris Lattner60610002003-10-07 15:17:02 +00009122 removeFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +00009123 continue;
Chris Lattner62b14df2002-09-02 04:59:56 +00009124 }
Chris Lattner4bb7c022003-10-06 17:11:01 +00009125
Chris Lattnerea1c4542004-12-08 23:43:58 +00009126 // See if we can trivially sink this instruction to a successor basic block.
9127 if (I->hasOneUse()) {
9128 BasicBlock *BB = I->getParent();
9129 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
9130 if (UserParent != BB) {
9131 bool UserIsSuccessor = false;
9132 // See if the user is one of our successors.
9133 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
9134 if (*SI == UserParent) {
9135 UserIsSuccessor = true;
9136 break;
9137 }
9138
9139 // If the user is one of our immediate successors, and if that successor
9140 // only has us as a predecessors (we'd have to split the critical edge
9141 // otherwise), we can keep going.
9142 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
9143 next(pred_begin(UserParent)) == pred_end(UserParent))
9144 // Okay, the CFG is simple enough, try to sink this instruction.
9145 Changed |= TryToSinkInstruction(I, UserParent);
9146 }
9147 }
9148
Chris Lattner8a2a3112001-12-14 16:52:21 +00009149 // Now that we have an instruction, try combining it to simplify it...
Chris Lattner90ac28c2002-08-02 19:29:35 +00009150 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +00009151 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00009152 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +00009153 if (Result != I) {
Bill Wendlingb7427032006-11-26 09:46:52 +00009154 DOUT << "IC: Old = " << *I
9155 << " New = " << *Result;
Chris Lattner0cea42a2004-03-13 23:54:27 +00009156
Chris Lattnerf523d062004-06-09 05:08:07 +00009157 // Everything uses the new instruction now.
9158 I->replaceAllUsesWith(Result);
9159
9160 // Push the new instruction and any users onto the worklist.
9161 WorkList.push_back(Result);
9162 AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +00009163
9164 // Move the name to the new instruction first...
9165 std::string OldName = I->getName(); I->setName("");
Chris Lattnerd558dc32003-10-07 22:58:41 +00009166 Result->setName(OldName);
Chris Lattner4bb7c022003-10-06 17:11:01 +00009167
9168 // Insert the new instruction into the basic block...
9169 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +00009170 BasicBlock::iterator InsertPos = I;
9171
9172 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
9173 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
9174 ++InsertPos;
9175
9176 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +00009177
Chris Lattner00d51312004-05-01 23:27:23 +00009178 // Make sure that we reprocess all operands now that we reduced their
9179 // use counts.
Chris Lattner216d4d82004-05-01 23:19:52 +00009180 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
9181 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
9182 WorkList.push_back(OpI);
9183
Chris Lattnerf523d062004-06-09 05:08:07 +00009184 // Instructions can end up on the worklist more than once. Make sure
9185 // we do not process an instruction that has been deleted.
9186 removeFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +00009187
9188 // Erase the old instruction.
9189 InstParent->getInstList().erase(I);
Chris Lattner7e708292002-06-25 16:13:24 +00009190 } else {
Bill Wendlingb7427032006-11-26 09:46:52 +00009191 DOUT << "IC: MOD = " << *I;
Chris Lattner0cea42a2004-03-13 23:54:27 +00009192
Chris Lattner90ac28c2002-08-02 19:29:35 +00009193 // If the instruction was modified, it's possible that it is now dead.
9194 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +00009195 if (isInstructionTriviallyDead(I)) {
9196 // Make sure we process all operands now that we are reducing their
9197 // use counts.
9198 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
9199 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
9200 WorkList.push_back(OpI);
Misha Brukmanfd939082005-04-21 23:48:37 +00009201
Chris Lattner00d51312004-05-01 23:27:23 +00009202 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchino1d7456d2006-01-13 22:48:06 +00009203 // occurrences of this instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +00009204 removeFromWorkList(I);
Chris Lattner2f503e62005-01-31 05:36:43 +00009205 I->eraseFromParent();
Chris Lattnerf523d062004-06-09 05:08:07 +00009206 } else {
9207 WorkList.push_back(Result);
9208 AddUsersToWorkList(*Result);
Chris Lattner90ac28c2002-08-02 19:29:35 +00009209 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +00009210 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00009211 Changed = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +00009212 }
9213 }
9214
Chris Lattnerdd841ae2002-04-18 17:39:14 +00009215 return Changed;
Chris Lattnerbd0ef772002-02-26 21:46:54 +00009216}
9217
Brian Gaeke96d4bf72004-07-27 17:43:21 +00009218FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +00009219 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +00009220}
Brian Gaeked0fde302003-11-11 22:41:34 +00009221