blob: 49966ae2e25293054026b5599c04a3f842708a91 [file] [log] [blame]
Chris Lattnere6794492002-08-12 21:17:25 +00001//===- InstructionCombining.cpp - Combine multiple instructions -----------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
John Criswell482202a2003-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 Brukmanb1c93172005-04-21 23:48:37 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattnerca081252001-12-14 16:52:21 +00009//
10// InstructionCombining - Combine instructions to form fewer, simple
Chris Lattner99f48c62002-09-02 04:59:56 +000011// instructions. This pass does not modify the CFG This pass is where algebraic
12// simplification happens.
Chris Lattnerca081252001-12-14 16:52:21 +000013//
14// This pass combines things like:
Chris Lattnerdd1a86d2004-05-04 15:19:33 +000015// %Y = add int %X, 1
16// %Z = add int %Y, 1
Chris Lattnerca081252001-12-14 16:52:21 +000017// into:
Chris Lattnerdd1a86d2004-05-04 15:19:33 +000018// %Z = add int %X, 2
Chris Lattnerca081252001-12-14 16:52:21 +000019//
20// This is a simple worklist driven algorithm.
21//
Chris Lattner216c7b82003-09-10 05:29:43 +000022// This pass guarantees that the following canonicalizations are performed on
Chris Lattnerbfb1d032003-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 Lattnerdeaa0dd2003-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.
Chris Lattnerbfb1d032003-07-23 21:41:57 +000027// 3. SetCC instructions are converted from <,>,<=,>= to ==,!= if possible
28// 4. All SetCC instructions on boolean values are replaced with logical ops
Chris Lattnerede3fe02003-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 Lattner7515cab2004-11-14 19:13:23 +000032// ... etc.
Chris Lattnerbfb1d032003-07-23 21:41:57 +000033//
Chris Lattnerca081252001-12-14 16:52:21 +000034//===----------------------------------------------------------------------===//
35
Chris Lattner7d2a5392004-03-13 23:54:27 +000036#define DEBUG_TYPE "instcombine"
Chris Lattnerb4cfa7f2002-05-07 20:03:00 +000037#include "llvm/Transforms/Scalar.h"
Chris Lattner00648e12004-10-12 04:52:52 +000038#include "llvm/IntrinsicInst.h"
Chris Lattner04805fa2002-02-26 21:46:54 +000039#include "llvm/Pass.h"
Chris Lattner1085bdf2002-11-04 16:18:53 +000040#include "llvm/DerivedTypes.h"
Chris Lattner0f1d8a32003-06-26 05:06:25 +000041#include "llvm/GlobalVariable.h"
Chris Lattnerf4ad1652003-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 Lattner69193f92004-04-05 01:30:19 +000045#include "llvm/Support/CallSite.h"
Chris Lattner39c98bb2004-12-08 23:43:58 +000046#include "llvm/Support/Debug.h"
Chris Lattner69193f92004-04-05 01:30:19 +000047#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner260ab202002-04-18 17:39:14 +000048#include "llvm/Support/InstVisitor.h"
Chris Lattner22d00a82005-08-02 19:16:58 +000049#include "llvm/Support/MathExtras.h"
Chris Lattnerd4252a72004-07-30 07:50:03 +000050#include "llvm/Support/PatternMatch.h"
Chris Lattner4ed40f72005-07-07 20:40:38 +000051#include "llvm/ADT/DepthFirstIterator.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000052#include "llvm/ADT/Statistic.h"
Chris Lattner39c98bb2004-12-08 23:43:58 +000053#include "llvm/ADT/STLExtras.h"
Chris Lattner053c0932002-05-14 15:24:07 +000054#include <algorithm>
Chris Lattnerc597b8a2006-01-22 23:32:06 +000055#include <iostream>
Chris Lattner8427bff2003-12-07 01:24:23 +000056using namespace llvm;
Chris Lattnerd4252a72004-07-30 07:50:03 +000057using namespace llvm::PatternMatch;
Brian Gaeke960707c2003-11-11 22:41:34 +000058
Chris Lattner260ab202002-04-18 17:39:14 +000059namespace {
Chris Lattnerbf3a0992002-10-01 22:38:41 +000060 Statistic<> NumCombined ("instcombine", "Number of insts combined");
61 Statistic<> NumConstProp("instcombine", "Number of constant folds");
62 Statistic<> NumDeadInst ("instcombine", "Number of dead inst eliminated");
Chris Lattner5997cf92006-02-08 03:25:32 +000063 Statistic<> NumDeadStore("instcombine", "Number of dead stores eliminated");
Chris Lattner39c98bb2004-12-08 23:43:58 +000064 Statistic<> NumSunkInst ("instcombine", "Number of instructions sunk");
Chris Lattnerbf3a0992002-10-01 22:38:41 +000065
Chris Lattnerc8e66542002-04-27 06:56:12 +000066 class InstCombiner : public FunctionPass,
Chris Lattner260ab202002-04-18 17:39:14 +000067 public InstVisitor<InstCombiner, Instruction*> {
68 // Worklist of all of the instructions that need to be simplified.
69 std::vector<Instruction*> WorkList;
Chris Lattnerf4ad1652003-11-02 05:57:39 +000070 TargetData *TD;
Chris Lattner260ab202002-04-18 17:39:14 +000071
Chris Lattner51ea1272004-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 Lattner2590e512006-02-07 06:56:34 +000076 void AddUsersToWorkList(Value &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +000077 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattner260ab202002-04-18 17:39:14 +000078 UI != UE; ++UI)
79 WorkList.push_back(cast<Instruction>(*UI));
80 }
81
Chris Lattner51ea1272004-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 }
90
Chris Lattner99f48c62002-09-02 04:59:56 +000091 // removeFromWorkList - remove all instances of I from the worklist.
92 void removeFromWorkList(Instruction *I);
Chris Lattner260ab202002-04-18 17:39:14 +000093 public:
Chris Lattner113f4f42002-06-25 16:13:24 +000094 virtual bool runOnFunction(Function &F);
Chris Lattner260ab202002-04-18 17:39:14 +000095
Chris Lattnerf12cc842002-04-28 21:27:06 +000096 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerf4ad1652003-11-02 05:57:39 +000097 AU.addRequired<TargetData>();
Chris Lattner820d9712002-10-21 20:00:28 +000098 AU.setPreservesCFG();
Chris Lattnerf12cc842002-04-28 21:27:06 +000099 }
100
Chris Lattner69193f92004-04-05 01:30:19 +0000101 TargetData &getTargetData() const { return *TD; }
102
Chris Lattner260ab202002-04-18 17:39:14 +0000103 // Visitation implementation - Implement instruction combining for different
104 // instruction types. The semantics are as follows:
105 // Return Value:
106 // null - No change was made
Chris Lattnere6794492002-08-12 21:17:25 +0000107 // I - Change was made, I is still valid, I may be dead though
Chris Lattner260ab202002-04-18 17:39:14 +0000108 // otherwise - Change was made, replace I with returned instruction
Misha Brukmanb1c93172005-04-21 23:48:37 +0000109 //
Chris Lattner113f4f42002-06-25 16:13:24 +0000110 Instruction *visitAdd(BinaryOperator &I);
111 Instruction *visitSub(BinaryOperator &I);
112 Instruction *visitMul(BinaryOperator &I);
113 Instruction *visitDiv(BinaryOperator &I);
114 Instruction *visitRem(BinaryOperator &I);
115 Instruction *visitAnd(BinaryOperator &I);
116 Instruction *visitOr (BinaryOperator &I);
117 Instruction *visitXor(BinaryOperator &I);
Chris Lattnerd1f46d32005-04-24 06:59:08 +0000118 Instruction *visitSetCondInst(SetCondInst &I);
119 Instruction *visitSetCondInstWithCastAndCast(SetCondInst &SCI);
120
Chris Lattner0798af32005-01-13 20:14:25 +0000121 Instruction *FoldGEPSetCC(User *GEPLHS, Value *RHS,
122 Instruction::BinaryOps Cond, Instruction &I);
Chris Lattnere8d6c602003-03-10 19:16:08 +0000123 Instruction *visitShiftInst(ShiftInst &I);
Chris Lattner14553932006-01-06 07:12:35 +0000124 Instruction *FoldShiftByConstant(Value *Op0, ConstantUInt *Op1,
125 ShiftInst &I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000126 Instruction *visitCastInst(CastInst &CI);
Chris Lattner411336f2005-01-19 21:50:18 +0000127 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
128 Instruction *FI);
Chris Lattnerb909e8b2004-03-12 05:52:32 +0000129 Instruction *visitSelectInst(SelectInst &CI);
Chris Lattner970c33a2003-06-19 17:00:31 +0000130 Instruction *visitCallInst(CallInst &CI);
131 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner113f4f42002-06-25 16:13:24 +0000132 Instruction *visitPHINode(PHINode &PN);
133 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner1085bdf2002-11-04 16:18:53 +0000134 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner8427bff2003-12-07 01:24:23 +0000135 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner0f1d8a32003-06-26 05:06:25 +0000136 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner31f486c2005-01-31 05:36:43 +0000137 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattner9eef8a72003-06-04 04:46:00 +0000138 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner4c9c20a2004-07-03 00:26:11 +0000139 Instruction *visitSwitchInst(SwitchInst &SI);
Robert Bocchinoa8352962006-01-13 22:48:06 +0000140 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattner260ab202002-04-18 17:39:14 +0000141
142 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner113f4f42002-06-25 16:13:24 +0000143 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000144
Chris Lattner970c33a2003-06-19 17:00:31 +0000145 private:
Chris Lattneraec3d942003-10-07 22:32:43 +0000146 Instruction *visitCallSite(CallSite CS);
Chris Lattner970c33a2003-06-19 17:00:31 +0000147 bool transformConstExprCastCall(CallSite CS);
148
Chris Lattner69193f92004-04-05 01:30:19 +0000149 public:
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000150 // InsertNewInstBefore - insert an instruction New before instruction Old
151 // in the program. Add the new instruction to the worklist.
152 //
Chris Lattner623826c2004-09-28 21:48:02 +0000153 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattner65217ff2002-08-23 18:32:43 +0000154 assert(New && New->getParent() == 0 &&
155 "New instruction already inserted into a basic block!");
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000156 BasicBlock *BB = Old.getParent();
157 BB->getInstList().insert(&Old, New); // Insert inst
158 WorkList.push_back(New); // Add to worklist
Chris Lattnere79e8542004-02-23 06:38:22 +0000159 return New;
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000160 }
161
Chris Lattner7e794272004-09-24 15:21:34 +0000162 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
163 /// This also adds the cast to the worklist. Finally, this returns the
164 /// cast.
165 Value *InsertCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
166 if (V->getType() == Ty) return V;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000167
Chris Lattner7e794272004-09-24 15:21:34 +0000168 Instruction *C = new CastInst(V, Ty, V->getName(), &Pos);
169 WorkList.push_back(C);
170 return C;
171 }
172
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000173 // ReplaceInstUsesWith - This method is to be used when an instruction is
174 // found to be dead, replacable with another preexisting expression. Here
175 // we add all uses of I to the worklist, replace all uses of I with the new
176 // value, then return I, so that the inst combiner will know that I was
177 // modified.
178 //
179 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner51ea1272004-02-28 05:22:00 +0000180 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner8953b902004-04-05 02:10:19 +0000181 if (&I != V) {
182 I.replaceAllUsesWith(V);
183 return &I;
184 } else {
185 // If we are replacing the instruction with itself, this must be in a
186 // segment of unreachable code, so just clobber the instruction.
Chris Lattner8ba9ec92004-10-18 02:59:09 +0000187 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner8953b902004-04-05 02:10:19 +0000188 return &I;
189 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000190 }
Chris Lattner51ea1272004-02-28 05:22:00 +0000191
Chris Lattner2590e512006-02-07 06:56:34 +0000192 // UpdateValueUsesWith - This method is to be used when an value is
193 // found to be replacable with another preexisting expression or was
194 // updated. Here we add all uses of I to the worklist, replace all uses of
195 // I with the new value (unless the instruction was just updated), then
196 // return true, so that the inst combiner will know that I was modified.
197 //
198 bool UpdateValueUsesWith(Value *Old, Value *New) {
199 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
200 if (Old != New)
201 Old->replaceAllUsesWith(New);
202 if (Instruction *I = dyn_cast<Instruction>(Old))
203 WorkList.push_back(I);
204 return true;
205 }
206
Chris Lattner51ea1272004-02-28 05:22:00 +0000207 // EraseInstFromFunction - When dealing with an instruction that has side
208 // effects or produces a void value, we can't rely on DCE to delete the
209 // instruction. Instead, visit methods should return the value returned by
210 // this function.
211 Instruction *EraseInstFromFunction(Instruction &I) {
212 assert(I.use_empty() && "Cannot erase instruction that is used!");
213 AddUsesToWorkList(I);
214 removeFromWorkList(&I);
Chris Lattner95307542004-11-18 21:41:39 +0000215 I.eraseFromParent();
Chris Lattner51ea1272004-02-28 05:22:00 +0000216 return 0; // Don't do anything with FI
217 }
218
Chris Lattner3ac7c262003-08-13 20:16:26 +0000219 private:
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000220 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
221 /// InsertBefore instruction. This is specialized a bit to avoid inserting
222 /// casts that are known to not do anything...
223 ///
224 Value *InsertOperandCastBefore(Value *V, const Type *DestTy,
225 Instruction *InsertBefore);
226
Chris Lattner7fb29e12003-03-11 00:12:48 +0000227 // SimplifyCommutative - This performs a few simplifications for commutative
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000228 // operators.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000229 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerba1cb382003-09-19 17:17:26 +0000230
Chris Lattner2590e512006-02-07 06:56:34 +0000231 bool SimplifyDemandedBits(Value *V, uint64_t Mask, unsigned Depth = 0);
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000232
233 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
234 // PHI node as operand #0, see if we can fold the instruction into the PHI
235 // (which is only possible if all operands to the PHI are constants).
236 Instruction *FoldOpIntoPhi(Instruction &I);
237
Chris Lattner7515cab2004-11-14 19:13:23 +0000238 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
239 // operator and they all are only used by the PHI, PHI together their
240 // inputs, and do the operation once, to the result of the PHI.
241 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
242
Chris Lattnerba1cb382003-09-19 17:17:26 +0000243 Instruction *OptAndOp(Instruction *Op, ConstantIntegral *OpRHS,
244 ConstantIntegral *AndRHS, BinaryOperator &TheAnd);
Chris Lattneraf517572005-09-18 04:24:45 +0000245
246 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantIntegral *Mask,
247 bool isSub, Instruction &I);
Chris Lattner6862fbd2004-09-29 17:40:11 +0000248 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
249 bool Inside, Instruction &IB);
Chris Lattner216be912005-10-24 06:03:58 +0000250 Instruction *PromoteCastOfAllocation(CastInst &CI, AllocationInst &AI);
Chris Lattner260ab202002-04-18 17:39:14 +0000251 };
Chris Lattnerb28b6802002-07-23 18:06:35 +0000252
Chris Lattnerc8b70922002-07-26 21:12:46 +0000253 RegisterOpt<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattner260ab202002-04-18 17:39:14 +0000254}
255
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000256// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattner81a7a232004-10-16 18:11:37 +0000257// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000258static unsigned getComplexity(Value *V) {
259 if (isa<Instruction>(V)) {
260 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattner81a7a232004-10-16 18:11:37 +0000261 return 3;
262 return 4;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000263 }
Chris Lattner81a7a232004-10-16 18:11:37 +0000264 if (isa<Argument>(V)) return 3;
265 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000266}
Chris Lattner260ab202002-04-18 17:39:14 +0000267
Chris Lattner7fb29e12003-03-11 00:12:48 +0000268// isOnlyUse - Return true if this instruction will be deleted if we stop using
269// it.
270static bool isOnlyUse(Value *V) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000271 return V->hasOneUse() || isa<Constant>(V);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000272}
273
Chris Lattnere79e8542004-02-23 06:38:22 +0000274// getPromotedType - Return the specified type promoted as it would be to pass
275// though a va_arg area...
276static const Type *getPromotedType(const Type *Ty) {
Chris Lattner97bfcea2004-06-17 18:16:02 +0000277 switch (Ty->getTypeID()) {
Chris Lattnere79e8542004-02-23 06:38:22 +0000278 case Type::SByteTyID:
279 case Type::ShortTyID: return Type::IntTy;
280 case Type::UByteTyID:
281 case Type::UShortTyID: return Type::UIntTy;
282 case Type::FloatTyID: return Type::DoubleTy;
283 default: return Ty;
284 }
285}
286
Chris Lattner567b81f2005-09-13 00:40:14 +0000287/// isCast - If the specified operand is a CastInst or a constant expr cast,
288/// return the operand value, otherwise return null.
289static Value *isCast(Value *V) {
290 if (CastInst *I = dyn_cast<CastInst>(V))
291 return I->getOperand(0);
292 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
293 if (CE->getOpcode() == Instruction::Cast)
294 return CE->getOperand(0);
295 return 0;
296}
297
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000298// SimplifyCommutative - This performs a few simplifications for commutative
299// operators:
Chris Lattner260ab202002-04-18 17:39:14 +0000300//
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000301// 1. Order operands such that they are listed from right (least complex) to
302// left (most complex). This puts constants before unary operators before
303// binary operators.
304//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000305// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
306// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000307//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000308bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000309 bool Changed = false;
310 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
311 Changed = !I.swapOperands();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000312
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000313 if (!I.isAssociative()) return Changed;
314 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattner7fb29e12003-03-11 00:12:48 +0000315 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
316 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
317 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner34428442003-05-27 16:40:51 +0000318 Constant *Folded = ConstantExpr::get(I.getOpcode(),
319 cast<Constant>(I.getOperand(1)),
320 cast<Constant>(Op->getOperand(1)));
Chris Lattner7fb29e12003-03-11 00:12:48 +0000321 I.setOperand(0, Op->getOperand(0));
322 I.setOperand(1, Folded);
323 return true;
324 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
325 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
326 isOnlyUse(Op) && isOnlyUse(Op1)) {
327 Constant *C1 = cast<Constant>(Op->getOperand(1));
328 Constant *C2 = cast<Constant>(Op1->getOperand(1));
329
330 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner34428442003-05-27 16:40:51 +0000331 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000332 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
333 Op1->getOperand(0),
334 Op1->getName(), &I);
335 WorkList.push_back(New);
336 I.setOperand(0, New);
337 I.setOperand(1, Folded);
338 return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000339 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000340 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000341 return Changed;
Chris Lattner260ab202002-04-18 17:39:14 +0000342}
Chris Lattnerca081252001-12-14 16:52:21 +0000343
Chris Lattnerbb74e222003-03-10 23:06:50 +0000344// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
345// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattner9fa53de2002-05-06 16:49:18 +0000346//
Chris Lattnerbb74e222003-03-10 23:06:50 +0000347static inline Value *dyn_castNegVal(Value *V) {
348 if (BinaryOperator::isNeg(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000349 return BinaryOperator::getNegArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000350
Chris Lattner9ad0d552004-12-14 20:08:06 +0000351 // Constants can be considered to be negated values if they can be folded.
352 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
353 return ConstantExpr::getNeg(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000354 return 0;
Chris Lattner9fa53de2002-05-06 16:49:18 +0000355}
356
Chris Lattnerbb74e222003-03-10 23:06:50 +0000357static inline Value *dyn_castNotVal(Value *V) {
358 if (BinaryOperator::isNot(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000359 return BinaryOperator::getNotArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000360
361 // Constants can be considered to be not'ed values...
Chris Lattnerdd65d862003-04-30 22:34:06 +0000362 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
Chris Lattnerc8e7e292004-06-10 02:12:35 +0000363 return ConstantExpr::getNot(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000364 return 0;
365}
366
Chris Lattner7fb29e12003-03-11 00:12:48 +0000367// dyn_castFoldableMul - If this value is a multiply that can be folded into
368// other computations (because it has a constant operand), return the
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000369// non-constant operand of the multiply, and set CST to point to the multiplier.
370// Otherwise, return null.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000371//
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000372static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000373 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000374 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattner7fb29e12003-03-11 00:12:48 +0000375 if (I->getOpcode() == Instruction::Mul)
Chris Lattner970136362004-11-15 05:54:07 +0000376 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattner7fb29e12003-03-11 00:12:48 +0000377 return I->getOperand(0);
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000378 if (I->getOpcode() == Instruction::Shl)
Chris Lattner970136362004-11-15 05:54:07 +0000379 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000380 // The multiplier is really 1 << CST.
381 Constant *One = ConstantInt::get(V->getType(), 1);
382 CST = cast<ConstantInt>(ConstantExpr::getShl(One, CST));
383 return I->getOperand(0);
384 }
385 }
Chris Lattner7fb29e12003-03-11 00:12:48 +0000386 return 0;
Chris Lattner3082c5a2003-02-18 19:28:33 +0000387}
Chris Lattner31ae8632002-08-14 17:51:49 +0000388
Chris Lattner0798af32005-01-13 20:14:25 +0000389/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
390/// expression, return it.
391static User *dyn_castGetElementPtr(Value *V) {
392 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
393 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
394 if (CE->getOpcode() == Instruction::GetElementPtr)
395 return cast<User>(V);
396 return false;
397}
398
Chris Lattner623826c2004-09-28 21:48:02 +0000399// AddOne, SubOne - Add or subtract a constant one from an integer constant...
Chris Lattner6862fbd2004-09-29 17:40:11 +0000400static ConstantInt *AddOne(ConstantInt *C) {
401 return cast<ConstantInt>(ConstantExpr::getAdd(C,
402 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000403}
Chris Lattner6862fbd2004-09-29 17:40:11 +0000404static ConstantInt *SubOne(ConstantInt *C) {
405 return cast<ConstantInt>(ConstantExpr::getSub(C,
406 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000407}
408
Chris Lattner4534dd592006-02-09 07:38:58 +0000409/// ComputeMaskedBits - Determine which of the bits specified in Mask are
410/// known to be either zero or one and return them in the KnownZero/KnownOne
411/// bitsets. This code only analyzes bits in Mask, in order to short-circuit
412/// processing.
413static void ComputeMaskedBits(Value *V, uint64_t Mask, uint64_t &KnownZero,
414 uint64_t &KnownOne, unsigned Depth = 0) {
Chris Lattner0b3557f2005-09-24 23:43:33 +0000415 // Note, we cannot consider 'undef' to be "IsZero" here. The problem is that
416 // we cannot optimize based on the assumption that it is zero without changing
Chris Lattnerc3ebf402006-02-07 07:27:52 +0000417 // it to be an explicit zero. If we don't change it to zero, other code could
Chris Lattner0b3557f2005-09-24 23:43:33 +0000418 // optimized based on the contradictory assumption that it is non-zero.
419 // Because instcombine aggressively folds operations with undef args anyway,
420 // this won't lose us code quality.
Chris Lattner4534dd592006-02-09 07:38:58 +0000421 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V)) {
422 // We know all of the bits for a constant!
423 KnownOne = CI->getZExtValue();
424 KnownZero = ~KnownOne & Mask;
425 return;
426 }
427
428 KnownZero = KnownOne = 0; // Don't know anything.
Chris Lattner92a68652006-02-07 08:05:22 +0000429 if (Depth == 6 || Mask == 0)
Chris Lattner4534dd592006-02-09 07:38:58 +0000430 return; // Limit search depth.
431
432 uint64_t KnownZero2, KnownOne2;
Chris Lattner0b3557f2005-09-24 23:43:33 +0000433 if (Instruction *I = dyn_cast<Instruction>(V)) {
434 switch (I->getOpcode()) {
Chris Lattner62010c42005-10-09 06:36:35 +0000435 case Instruction::And:
Chris Lattner4534dd592006-02-09 07:38:58 +0000436 // If either the LHS or the RHS are Zero, the result is zero.
437 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
438 Mask &= ~KnownZero;
439 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
440 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
441 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
442
443 // Output known-1 bits are only known if set in both the LHS & RHS.
444 KnownOne &= KnownOne2;
445 // Output known-0 are known to be clear if zero in either the LHS | RHS.
446 KnownZero |= KnownZero2;
447 return;
Chris Lattner62010c42005-10-09 06:36:35 +0000448 case Instruction::Or:
Chris Lattner4534dd592006-02-09 07:38:58 +0000449 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
450 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
451 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
452 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
453
454 // Output known-0 bits are only known if clear in both the LHS & RHS.
455 KnownZero &= KnownZero2;
456 // Output known-1 are known to be set if set in either the LHS | RHS.
457 KnownOne |= KnownOne2;
458 return;
459 case Instruction::Xor: {
460 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
461 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
462 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
463 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
464
465 // Output known-0 bits are known if clear or set in both the LHS & RHS.
466 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
467 // Output known-1 are known to be set if set in only one of the LHS, RHS.
468 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
469 KnownZero = KnownZeroOut;
470 return;
471 }
Chris Lattner62010c42005-10-09 06:36:35 +0000472 case Instruction::Select:
Chris Lattner4534dd592006-02-09 07:38:58 +0000473 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
474 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
475 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
476 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
477
478 // Only known if known in both the LHS and RHS.
479 KnownOne &= KnownOne2;
480 KnownZero &= KnownZero2;
481 return;
Chris Lattner62010c42005-10-09 06:36:35 +0000482 case Instruction::Cast: {
483 const Type *SrcTy = I->getOperand(0)->getType();
Chris Lattner4534dd592006-02-09 07:38:58 +0000484 if (!SrcTy->isIntegral()) return;
Chris Lattner62010c42005-10-09 06:36:35 +0000485
Chris Lattner4534dd592006-02-09 07:38:58 +0000486 // If this is an integer truncate or noop, just look in the input.
487 if (SrcTy->getPrimitiveSizeInBits() >=
488 I->getType()->getPrimitiveSizeInBits()) {
489 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
490 return;
Chris Lattner92a68652006-02-07 08:05:22 +0000491 }
492
Chris Lattner4534dd592006-02-09 07:38:58 +0000493 // Sign or Zero extension. Compute the bits in the result that are not
494 // present in the input.
495 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
496 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
497
498 // Handle zero extension.
499 if (!SrcTy->isSigned()) {
500 Mask &= SrcTy->getIntegralTypeMask();
501 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
502 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
503 // The top bits are known to be zero.
504 KnownZero |= NewBits;
505 } else {
506 // Sign extension.
507 Mask &= SrcTy->getIntegralTypeMask();
508 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
509 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
510
511 // If the sign bit of the input is known set or clear, then we know the
512 // top bits of the result.
513 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
514 if (KnownZero & InSignBit) { // Input sign bit known zero
515 KnownZero |= NewBits;
516 KnownOne &= ~NewBits;
517 } else if (KnownOne & InSignBit) { // Input sign bit known set
518 KnownOne |= NewBits;
519 KnownZero &= ~NewBits;
520 } else { // Input sign bit unknown
521 KnownZero &= ~NewBits;
522 KnownOne &= ~NewBits;
523 }
524 }
525 return;
Chris Lattner62010c42005-10-09 06:36:35 +0000526 }
527 case Instruction::Shl:
528 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
Chris Lattner4534dd592006-02-09 07:38:58 +0000529 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
530 Mask >> SA->getValue();
531 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
532 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
533 KnownZero <<= SA->getValue();
534 KnownOne <<= SA->getValue();
535 KnownZero |= (1ULL << SA->getValue())-1; // low bits known zero.
536 return;
537 }
Chris Lattner62010c42005-10-09 06:36:35 +0000538 break;
539 case Instruction::Shr:
540 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
Chris Lattner4534dd592006-02-09 07:38:58 +0000541 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
542 // Compute the new bits that are at the top now.
543 uint64_t HighBits = (1ULL << SA->getValue())-1;
544 HighBits <<= I->getType()->getPrimitiveSizeInBits()-SA->getValue();
545
546 if (I->getType()->isUnsigned()) { // Unsigned shift right.
547 Mask << SA->getValue();
548 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
549 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
550 KnownZero >>= SA->getValue();
551 KnownOne >>= SA->getValue();
552 KnownZero |= HighBits; // high bits known zero.
553 } else {
554 Mask << SA->getValue();
555 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
556 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
557 KnownZero >>= SA->getValue();
558 KnownOne >>= SA->getValue();
559
560 // Handle the sign bits.
561 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
562 SignBit >>= SA->getValue(); // Adjust to where it is now in the mask.
563
564 if (KnownZero & SignBit) { // New bits are known zero.
565 KnownZero |= HighBits;
566 } else if (KnownOne & SignBit) { // New bits are known one.
567 KnownOne |= HighBits;
568 }
Chris Lattner62010c42005-10-09 06:36:35 +0000569 }
Chris Lattner4534dd592006-02-09 07:38:58 +0000570 return;
571 }
Chris Lattner62010c42005-10-09 06:36:35 +0000572 break;
Chris Lattner0b3557f2005-09-24 23:43:33 +0000573 }
574 }
Chris Lattner92a68652006-02-07 08:05:22 +0000575}
576
577/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
578/// this predicate to simplify operations downstream. Mask is known to be zero
579/// for bits that V cannot have.
580static bool MaskedValueIsZero(Value *V, uint64_t Mask, unsigned Depth = 0) {
Chris Lattner4534dd592006-02-09 07:38:58 +0000581 uint64_t KnownZero, KnownOne;
582 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
583 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
584 return (KnownZero & Mask) == Mask;
Chris Lattner0b3557f2005-09-24 23:43:33 +0000585}
586
Chris Lattner2590e512006-02-07 06:56:34 +0000587/// SimplifyDemandedBits - Look at V. At this point, we know that only the Mask
588/// bits of the result of V are ever used downstream. If we can use this
589/// information to simplify V, return V and set NewVal to the new value we
590/// should use in V's place.
591bool InstCombiner::SimplifyDemandedBits(Value *V, uint64_t Mask,
592 unsigned Depth) {
593 if (!V->hasOneUse()) { // Other users may use these bits.
594 if (Depth != 0) // Not at the root.
595 return false;
596 // If this is the root being simplified, allow it to have multiple uses,
597 // just set the Mask to all bits.
598 Mask = V->getType()->getIntegralTypeMask();
599 } else if (Mask == 0) { // Not demanding any bits from V.
Chris Lattner92a68652006-02-07 08:05:22 +0000600 if (V != UndefValue::get(V->getType()))
601 return UpdateValueUsesWith(V, UndefValue::get(V->getType()));
602 return false;
Chris Lattner2590e512006-02-07 06:56:34 +0000603 } else if (Depth == 6) { // Limit search depth.
604 return false;
605 }
606
607 Instruction *I = dyn_cast<Instruction>(V);
608 if (!I) return false; // Only analyze instructions.
609
610 switch (I->getOpcode()) {
611 default: break;
612 case Instruction::And:
613 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
614 // Only demanding an intersection of the bits.
615 if (SimplifyDemandedBits(I->getOperand(0), RHS->getRawValue() & Mask,
616 Depth+1))
617 return true;
Chris Lattner92a68652006-02-07 08:05:22 +0000618 if (~Mask & RHS->getZExtValue()) {
Chris Lattner2590e512006-02-07 06:56:34 +0000619 // If this is producing any bits that are not needed, simplify the RHS.
Chris Lattner92a68652006-02-07 08:05:22 +0000620 uint64_t Val = Mask & RHS->getZExtValue();
621 Constant *RHS =
622 ConstantUInt::get(I->getType()->getUnsignedVersion(), Val);
623 if (I->getType()->isSigned())
624 RHS = ConstantExpr::getCast(RHS, I->getType());
625 I->setOperand(1, RHS);
Chris Lattner2590e512006-02-07 06:56:34 +0000626 return UpdateValueUsesWith(I, I);
627 }
628 }
629 // Walk the LHS and the RHS.
630 return SimplifyDemandedBits(I->getOperand(0), Mask, Depth+1) ||
631 SimplifyDemandedBits(I->getOperand(1), Mask, Depth+1);
632 case Instruction::Or:
633 case Instruction::Xor:
634 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
635 // If none of the [x]or'd in bits are demanded, don't both with the [x]or.
636 if ((Mask & RHS->getRawValue()) == 0)
637 return UpdateValueUsesWith(I, I->getOperand(0));
638
639 // Otherwise, for an OR, we only demand those bits not set by the OR.
640 if (I->getOpcode() == Instruction::Or)
641 Mask &= ~RHS->getRawValue();
642 return SimplifyDemandedBits(I->getOperand(0), Mask, Depth+1);
643 }
644 // Walk the LHS and the RHS.
645 return SimplifyDemandedBits(I->getOperand(0), Mask, Depth+1) ||
646 SimplifyDemandedBits(I->getOperand(1), Mask, Depth+1);
647 case Instruction::Cast: {
648 const Type *SrcTy = I->getOperand(0)->getType();
649 if (SrcTy == Type::BoolTy)
650 return SimplifyDemandedBits(I->getOperand(0), Mask&1, Depth+1);
651
652 if (!SrcTy->isInteger()) return false;
653
654 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
655 // If this is a sign-extend, treat specially.
656 if (SrcTy->isSigned() &&
657 SrcBits < I->getType()->getPrimitiveSizeInBits()) {
658 // If none of the top bits are demanded, convert this into an unsigned
659 // extend instead of a sign extend.
660 if ((Mask & ((1ULL << SrcBits)-1)) == 0) {
661 // Convert to unsigned first.
Chris Lattner44314822006-02-07 19:07:40 +0000662 Instruction *NewVal;
Chris Lattner2590e512006-02-07 06:56:34 +0000663 NewVal = new CastInst(I->getOperand(0), SrcTy->getUnsignedVersion(),
Chris Lattner44314822006-02-07 19:07:40 +0000664 I->getOperand(0)->getName());
665 InsertNewInstBefore(NewVal, *I);
666 NewVal = new CastInst(NewVal, I->getType(), I->getName());
667 InsertNewInstBefore(NewVal, *I);
Chris Lattner2590e512006-02-07 06:56:34 +0000668 return UpdateValueUsesWith(I, NewVal);
669 }
670
671 // Otherwise, the high-bits *are* demanded. This means that the code
672 // implicitly demands computation of the sign bit of the input, make sure
673 // we explicitly include it in Mask.
674 Mask |= 1ULL << (SrcBits-1);
675 }
676
677 // If this is an extension, the top bits are ignored.
678 Mask &= SrcTy->getIntegralTypeMask();
679 return SimplifyDemandedBits(I->getOperand(0), Mask, Depth+1);
680 }
681 case Instruction::Select:
682 // Simplify the T and F values if they are not demanded.
683 return SimplifyDemandedBits(I->getOperand(2), Mask, Depth+1) ||
684 SimplifyDemandedBits(I->getOperand(1), Mask, Depth+1);
685 case Instruction::Shl:
686 // We only demand the low bits of the input.
687 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1)))
688 return SimplifyDemandedBits(I->getOperand(0), Mask >> SA->getValue(),
689 Depth+1);
690 break;
691 case Instruction::Shr:
692 // We only demand the high bits of the input.
693 if (I->getType()->isUnsigned())
694 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
695 Mask <<= SA->getValue();
696 Mask &= I->getType()->getIntegralTypeMask();
697 return SimplifyDemandedBits(I->getOperand(0), Mask, Depth+1);
698 }
699 // FIXME: handle signed shr, demanding the appropriate bits. If the top
700 // bits aren't demanded, strength reduce to a logical SHR instead.
701 break;
702 }
703 return false;
704}
705
Chris Lattner623826c2004-09-28 21:48:02 +0000706// isTrueWhenEqual - Return true if the specified setcondinst instruction is
707// true when both operands are equal...
708//
709static bool isTrueWhenEqual(Instruction &I) {
710 return I.getOpcode() == Instruction::SetEQ ||
711 I.getOpcode() == Instruction::SetGE ||
712 I.getOpcode() == Instruction::SetLE;
713}
Chris Lattnerb8b97502003-08-13 19:01:45 +0000714
715/// AssociativeOpt - Perform an optimization on an associative operator. This
716/// function is designed to check a chain of associative operators for a
717/// potential to apply a certain optimization. Since the optimization may be
718/// applicable if the expression was reassociated, this checks the chain, then
719/// reassociates the expression as necessary to expose the optimization
720/// opportunity. This makes use of a special Functor, which must define
721/// 'shouldApply' and 'apply' methods.
722///
723template<typename Functor>
724Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
725 unsigned Opcode = Root.getOpcode();
726 Value *LHS = Root.getOperand(0);
727
728 // Quick check, see if the immediate LHS matches...
729 if (F.shouldApply(LHS))
730 return F.apply(Root);
731
732 // Otherwise, if the LHS is not of the same opcode as the root, return.
733 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000734 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +0000735 // Should we apply this transform to the RHS?
736 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
737
738 // If not to the RHS, check to see if we should apply to the LHS...
739 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
740 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
741 ShouldApply = true;
742 }
743
744 // If the functor wants to apply the optimization to the RHS of LHSI,
745 // reassociate the expression from ((? op A) op B) to (? op (A op B))
746 if (ShouldApply) {
747 BasicBlock *BB = Root.getParent();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000748
Chris Lattnerb8b97502003-08-13 19:01:45 +0000749 // Now all of the instructions are in the current basic block, go ahead
750 // and perform the reassociation.
751 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
752
753 // First move the selected RHS to the LHS of the root...
754 Root.setOperand(0, LHSI->getOperand(1));
755
756 // Make what used to be the LHS of the root be the user of the root...
757 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner284d3b02004-04-16 18:08:07 +0000758 if (&Root == TmpLHSI) {
Chris Lattner8953b902004-04-05 02:10:19 +0000759 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
760 return 0;
761 }
Chris Lattner284d3b02004-04-16 18:08:07 +0000762 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattnerb8b97502003-08-13 19:01:45 +0000763 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner284d3b02004-04-16 18:08:07 +0000764 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
765 BasicBlock::iterator ARI = &Root; ++ARI;
766 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
767 ARI = Root;
Chris Lattnerb8b97502003-08-13 19:01:45 +0000768
769 // Now propagate the ExtraOperand down the chain of instructions until we
770 // get to LHSI.
771 while (TmpLHSI != LHSI) {
772 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner284d3b02004-04-16 18:08:07 +0000773 // Move the instruction to immediately before the chain we are
774 // constructing to avoid breaking dominance properties.
775 NextLHSI->getParent()->getInstList().remove(NextLHSI);
776 BB->getInstList().insert(ARI, NextLHSI);
777 ARI = NextLHSI;
778
Chris Lattnerb8b97502003-08-13 19:01:45 +0000779 Value *NextOp = NextLHSI->getOperand(1);
780 NextLHSI->setOperand(1, ExtraOperand);
781 TmpLHSI = NextLHSI;
782 ExtraOperand = NextOp;
783 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000784
Chris Lattnerb8b97502003-08-13 19:01:45 +0000785 // Now that the instructions are reassociated, have the functor perform
786 // the transformation...
787 return F.apply(Root);
788 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000789
Chris Lattnerb8b97502003-08-13 19:01:45 +0000790 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
791 }
792 return 0;
793}
794
795
796// AddRHS - Implements: X + X --> X << 1
797struct AddRHS {
798 Value *RHS;
799 AddRHS(Value *rhs) : RHS(rhs) {}
800 bool shouldApply(Value *LHS) const { return LHS == RHS; }
801 Instruction *apply(BinaryOperator &Add) const {
802 return new ShiftInst(Instruction::Shl, Add.getOperand(0),
803 ConstantInt::get(Type::UByteTy, 1));
804 }
805};
806
807// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
808// iff C1&C2 == 0
809struct AddMaskingAnd {
810 Constant *C2;
811 AddMaskingAnd(Constant *c) : C2(c) {}
812 bool shouldApply(Value *LHS) const {
Chris Lattnerd4252a72004-07-30 07:50:03 +0000813 ConstantInt *C1;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000814 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattnerd4252a72004-07-30 07:50:03 +0000815 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattnerb8b97502003-08-13 19:01:45 +0000816 }
817 Instruction *apply(BinaryOperator &Add) const {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000818 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattnerb8b97502003-08-13 19:01:45 +0000819 }
820};
821
Chris Lattner86102b82005-01-01 16:22:27 +0000822static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner183b3362004-04-09 19:05:30 +0000823 InstCombiner *IC) {
Chris Lattner86102b82005-01-01 16:22:27 +0000824 if (isa<CastInst>(I)) {
825 if (Constant *SOC = dyn_cast<Constant>(SO))
826 return ConstantExpr::getCast(SOC, I.getType());
Misha Brukmanb1c93172005-04-21 23:48:37 +0000827
Chris Lattner86102b82005-01-01 16:22:27 +0000828 return IC->InsertNewInstBefore(new CastInst(SO, I.getType(),
829 SO->getName() + ".cast"), I);
830 }
831
Chris Lattner183b3362004-04-09 19:05:30 +0000832 // Figure out if the constant is the left or the right argument.
Chris Lattner86102b82005-01-01 16:22:27 +0000833 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
834 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattnerb8b97502003-08-13 19:01:45 +0000835
Chris Lattner183b3362004-04-09 19:05:30 +0000836 if (Constant *SOC = dyn_cast<Constant>(SO)) {
837 if (ConstIsRHS)
Chris Lattner86102b82005-01-01 16:22:27 +0000838 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
839 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner183b3362004-04-09 19:05:30 +0000840 }
841
842 Value *Op0 = SO, *Op1 = ConstOperand;
843 if (!ConstIsRHS)
844 std::swap(Op0, Op1);
845 Instruction *New;
Chris Lattner86102b82005-01-01 16:22:27 +0000846 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
847 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
848 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
849 New = new ShiftInst(SI->getOpcode(), Op0, Op1, SO->getName()+".sh");
Chris Lattnerf9d96652004-04-10 19:15:56 +0000850 else {
Chris Lattner183b3362004-04-09 19:05:30 +0000851 assert(0 && "Unknown binary instruction type!");
Chris Lattnerf9d96652004-04-10 19:15:56 +0000852 abort();
853 }
Chris Lattner86102b82005-01-01 16:22:27 +0000854 return IC->InsertNewInstBefore(New, I);
855}
856
857// FoldOpIntoSelect - Given an instruction with a select as one operand and a
858// constant as the other operand, try to fold the binary operator into the
859// select arguments. This also works for Cast instructions, which obviously do
860// not have a second operand.
861static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
862 InstCombiner *IC) {
863 // Don't modify shared select instructions
864 if (!SI->hasOneUse()) return 0;
865 Value *TV = SI->getOperand(1);
866 Value *FV = SI->getOperand(2);
867
868 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner374e6592005-04-21 05:43:13 +0000869 // Bool selects with constant operands can be folded to logical ops.
870 if (SI->getType() == Type::BoolTy) return 0;
871
Chris Lattner86102b82005-01-01 16:22:27 +0000872 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
873 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
874
875 return new SelectInst(SI->getCondition(), SelectTrueVal,
876 SelectFalseVal);
877 }
878 return 0;
Chris Lattner183b3362004-04-09 19:05:30 +0000879}
880
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000881
882/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
883/// node as operand #0, see if we can fold the instruction into the PHI (which
884/// is only possible if all operands to the PHI are constants).
885Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
886 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattner7515cab2004-11-14 19:13:23 +0000887 unsigned NumPHIValues = PN->getNumIncomingValues();
888 if (!PN->hasOneUse() || NumPHIValues == 0 ||
889 !isa<Constant>(PN->getIncomingValue(0))) return 0;
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000890
891 // Check to see if all of the operands of the PHI are constants. If not, we
892 // cannot do the transformation.
Chris Lattner7515cab2004-11-14 19:13:23 +0000893 for (unsigned i = 1; i != NumPHIValues; ++i)
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000894 if (!isa<Constant>(PN->getIncomingValue(i)))
895 return 0;
896
897 // Okay, we can do the transformation: create the new PHI node.
898 PHINode *NewPN = new PHINode(I.getType(), I.getName());
899 I.setName("");
Chris Lattnerd8e20182005-01-29 00:39:08 +0000900 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000901 InsertNewInstBefore(NewPN, *PN);
902
903 // Next, add all of the operands to the PHI.
904 if (I.getNumOperands() == 2) {
905 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattner7515cab2004-11-14 19:13:23 +0000906 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000907 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
908 NewPN->addIncoming(ConstantExpr::get(I.getOpcode(), InV, C),
909 PN->getIncomingBlock(i));
910 }
911 } else {
912 assert(isa<CastInst>(I) && "Unary op should be a cast!");
913 const Type *RetTy = I.getType();
Chris Lattner7515cab2004-11-14 19:13:23 +0000914 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000915 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
916 NewPN->addIncoming(ConstantExpr::getCast(InV, RetTy),
917 PN->getIncomingBlock(i));
918 }
919 }
920 return ReplaceInstUsesWith(I, NewPN);
921}
922
Chris Lattner113f4f42002-06-25 16:13:24 +0000923Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000924 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000925 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000926
Chris Lattnercf4a9962004-04-10 22:01:55 +0000927 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattner81a7a232004-10-16 18:11:37 +0000928 // X + undef -> undef
929 if (isa<UndefValue>(RHS))
930 return ReplaceInstUsesWith(I, RHS);
931
Chris Lattnercf4a9962004-04-10 22:01:55 +0000932 // X + 0 --> X
Chris Lattner7fde91e2005-10-17 17:56:38 +0000933 if (!I.getType()->isFloatingPoint()) { // NOTE: -0 + +0 = +0.
934 if (RHSC->isNullValue())
935 return ReplaceInstUsesWith(I, LHS);
Chris Lattnerda1b1522005-10-17 20:18:38 +0000936 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
937 if (CFP->isExactlyValue(-0.0))
938 return ReplaceInstUsesWith(I, LHS);
Chris Lattner7fde91e2005-10-17 17:56:38 +0000939 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000940
Chris Lattnercf4a9962004-04-10 22:01:55 +0000941 // X + (signbit) --> X ^ signbit
942 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattner92a68652006-02-07 08:05:22 +0000943 uint64_t Val = CI->getZExtValue();
Chris Lattner77defba2006-02-07 07:00:41 +0000944 if (Val == (1ULL << (CI->getType()->getPrimitiveSizeInBits()-1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000945 return BinaryOperator::createXor(LHS, RHS);
Chris Lattnercf4a9962004-04-10 22:01:55 +0000946 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000947
948 if (isa<PHINode>(LHS))
949 if (Instruction *NV = FoldOpIntoPhi(I))
950 return NV;
Chris Lattner0b3557f2005-09-24 23:43:33 +0000951
Chris Lattner330628a2006-01-06 17:59:59 +0000952 ConstantInt *XorRHS = 0;
953 Value *XorLHS = 0;
Chris Lattner0b3557f2005-09-24 23:43:33 +0000954 if (match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
955 unsigned TySizeBits = I.getType()->getPrimitiveSizeInBits();
956 int64_t RHSSExt = cast<ConstantInt>(RHSC)->getSExtValue();
957 uint64_t RHSZExt = cast<ConstantInt>(RHSC)->getZExtValue();
958
959 uint64_t C0080Val = 1ULL << 31;
960 int64_t CFF80Val = -C0080Val;
961 unsigned Size = 32;
962 do {
963 if (TySizeBits > Size) {
964 bool Found = false;
965 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
966 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
967 if (RHSSExt == CFF80Val) {
968 if (XorRHS->getZExtValue() == C0080Val)
969 Found = true;
970 } else if (RHSZExt == C0080Val) {
971 if (XorRHS->getSExtValue() == CFF80Val)
972 Found = true;
973 }
974 if (Found) {
975 // This is a sign extend if the top bits are known zero.
Chris Lattner4534dd592006-02-09 07:38:58 +0000976 uint64_t Mask = ~0ULL;
Chris Lattnerc3ebf402006-02-07 07:27:52 +0000977 Mask <<= 64-(TySizeBits-Size);
Chris Lattner4534dd592006-02-09 07:38:58 +0000978 Mask &= XorLHS->getType()->getIntegralTypeMask();
Chris Lattnerc3ebf402006-02-07 07:27:52 +0000979 if (!MaskedValueIsZero(XorLHS, Mask))
Chris Lattner0b3557f2005-09-24 23:43:33 +0000980 Size = 0; // Not a sign ext, but can't be any others either.
981 goto FoundSExt;
982 }
983 }
984 Size >>= 1;
985 C0080Val >>= Size;
986 CFF80Val >>= Size;
987 } while (Size >= 8);
988
989FoundSExt:
990 const Type *MiddleType = 0;
991 switch (Size) {
992 default: break;
993 case 32: MiddleType = Type::IntTy; break;
994 case 16: MiddleType = Type::ShortTy; break;
995 case 8: MiddleType = Type::SByteTy; break;
996 }
997 if (MiddleType) {
998 Instruction *NewTrunc = new CastInst(XorLHS, MiddleType, "sext");
999 InsertNewInstBefore(NewTrunc, I);
1000 return new CastInst(NewTrunc, I.getType());
1001 }
1002 }
Chris Lattnercf4a9962004-04-10 22:01:55 +00001003 }
Chris Lattner9fa53de2002-05-06 16:49:18 +00001004
Chris Lattnerb8b97502003-08-13 19:01:45 +00001005 // X + X --> X << 1
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00001006 if (I.getType()->isInteger()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +00001007 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner47060462005-04-07 17:14:51 +00001008
1009 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
1010 if (RHSI->getOpcode() == Instruction::Sub)
1011 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
1012 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
1013 }
1014 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
1015 if (LHSI->getOpcode() == Instruction::Sub)
1016 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
1017 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
1018 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00001019 }
Chris Lattnerede3fe02003-08-13 04:18:28 +00001020
Chris Lattner147e9752002-05-08 22:46:53 +00001021 // -A + B --> B - A
Chris Lattnerbb74e222003-03-10 23:06:50 +00001022 if (Value *V = dyn_castNegVal(LHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001023 return BinaryOperator::createSub(RHS, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001024
1025 // A + -B --> A - B
Chris Lattnerbb74e222003-03-10 23:06:50 +00001026 if (!isa<Constant>(RHS))
1027 if (Value *V = dyn_castNegVal(RHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001028 return BinaryOperator::createSub(LHS, V);
Chris Lattner260ab202002-04-18 17:39:14 +00001029
Misha Brukmanb1c93172005-04-21 23:48:37 +00001030
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001031 ConstantInt *C2;
1032 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
1033 if (X == RHS) // X*C + X --> X * (C+1)
1034 return BinaryOperator::createMul(RHS, AddOne(C2));
1035
1036 // X*C1 + X*C2 --> X * (C1+C2)
1037 ConstantInt *C1;
1038 if (X == dyn_castFoldableMul(RHS, C1))
1039 return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattner57c8d992003-02-18 19:57:07 +00001040 }
1041
1042 // X + X*C --> X * (C+1)
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001043 if (dyn_castFoldableMul(RHS, C2) == LHS)
1044 return BinaryOperator::createMul(LHS, AddOne(C2));
1045
Chris Lattner57c8d992003-02-18 19:57:07 +00001046
Chris Lattnerb8b97502003-08-13 19:01:45 +00001047 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +00001048 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnerb8b97502003-08-13 19:01:45 +00001049 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
Chris Lattner7fb29e12003-03-11 00:12:48 +00001050
Chris Lattnerb9cde762003-10-02 15:11:26 +00001051 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner330628a2006-01-06 17:59:59 +00001052 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00001053 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
1054 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
1055 return BinaryOperator::createSub(C, X);
Chris Lattnerb9cde762003-10-02 15:11:26 +00001056 }
Chris Lattnerd4252a72004-07-30 07:50:03 +00001057
Chris Lattnerbff91d92004-10-08 05:07:56 +00001058 // (X & FF00) + xx00 -> (X+xx00) & FF00
1059 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
1060 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
1061 if (Anded == CRHS) {
1062 // See if all bits from the first bit set in the Add RHS up are included
1063 // in the mask. First, get the rightmost bit.
1064 uint64_t AddRHSV = CRHS->getRawValue();
1065
1066 // Form a mask of all bits from the lowest bit added through the top.
1067 uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
Chris Lattner77defba2006-02-07 07:00:41 +00001068 AddRHSHighBits &= C2->getType()->getIntegralTypeMask();
Chris Lattnerbff91d92004-10-08 05:07:56 +00001069
1070 // See if the and mask includes all of these bits.
1071 uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getRawValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001072
Chris Lattnerbff91d92004-10-08 05:07:56 +00001073 if (AddRHSHighBits == AddRHSHighBitsAnd) {
1074 // Okay, the xform is safe. Insert the new add pronto.
1075 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
1076 LHS->getName()), I);
1077 return BinaryOperator::createAnd(NewAdd, C2);
1078 }
1079 }
1080 }
1081
Chris Lattnerd4252a72004-07-30 07:50:03 +00001082 // Try to fold constant add into select arguments.
1083 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner86102b82005-01-01 16:22:27 +00001084 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerd4252a72004-07-30 07:50:03 +00001085 return R;
Chris Lattnerb9cde762003-10-02 15:11:26 +00001086 }
1087
Chris Lattner113f4f42002-06-25 16:13:24 +00001088 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00001089}
1090
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00001091// isSignBit - Return true if the value represented by the constant only has the
1092// highest order bit set.
1093static bool isSignBit(ConstantInt *CI) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001094 unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
Chris Lattner2f1457f2005-04-24 17:46:05 +00001095 return (CI->getRawValue() & (~0ULL >> (64-NumBits))) == (1ULL << (NumBits-1));
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00001096}
1097
Chris Lattner022167f2004-03-13 00:11:49 +00001098/// RemoveNoopCast - Strip off nonconverting casts from the value.
1099///
1100static Value *RemoveNoopCast(Value *V) {
1101 if (CastInst *CI = dyn_cast<CastInst>(V)) {
1102 const Type *CTy = CI->getType();
1103 const Type *OpTy = CI->getOperand(0)->getType();
1104 if (CTy->isInteger() && OpTy->isInteger()) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001105 if (CTy->getPrimitiveSizeInBits() == OpTy->getPrimitiveSizeInBits())
Chris Lattner022167f2004-03-13 00:11:49 +00001106 return RemoveNoopCast(CI->getOperand(0));
1107 } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
1108 return RemoveNoopCast(CI->getOperand(0));
1109 }
1110 return V;
1111}
1112
Chris Lattner113f4f42002-06-25 16:13:24 +00001113Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00001114 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001115
Chris Lattnere6794492002-08-12 21:17:25 +00001116 if (Op0 == Op1) // sub X, X -> 0
1117 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner260ab202002-04-18 17:39:14 +00001118
Chris Lattnere6794492002-08-12 21:17:25 +00001119 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattnerbb74e222003-03-10 23:06:50 +00001120 if (Value *V = dyn_castNegVal(Op1))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001121 return BinaryOperator::createAdd(Op0, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001122
Chris Lattner81a7a232004-10-16 18:11:37 +00001123 if (isa<UndefValue>(Op0))
1124 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
1125 if (isa<UndefValue>(Op1))
1126 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
1127
Chris Lattner8f2f5982003-11-05 01:06:05 +00001128 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
1129 // Replace (-1 - A) with (~A)...
Chris Lattner3082c5a2003-02-18 19:28:33 +00001130 if (C->isAllOnesValue())
1131 return BinaryOperator::createNot(Op1);
Chris Lattnerad3c4952002-05-09 01:29:19 +00001132
Chris Lattner8f2f5982003-11-05 01:06:05 +00001133 // C - ~X == X + (1+C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00001134 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00001135 if (match(Op1, m_Not(m_Value(X))))
1136 return BinaryOperator::createAdd(X,
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001137 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
Chris Lattner92295c52004-03-12 23:53:13 +00001138 // -((uint)X >> 31) -> ((int)X >> 31)
1139 // -((int)X >> 31) -> ((uint)X >> 31)
Chris Lattner022167f2004-03-13 00:11:49 +00001140 if (C->isNullValue()) {
1141 Value *NoopCastedRHS = RemoveNoopCast(Op1);
1142 if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
Chris Lattner92295c52004-03-12 23:53:13 +00001143 if (SI->getOpcode() == Instruction::Shr)
1144 if (ConstantUInt *CU = dyn_cast<ConstantUInt>(SI->getOperand(1))) {
1145 const Type *NewTy;
Chris Lattner022167f2004-03-13 00:11:49 +00001146 if (SI->getType()->isSigned())
Chris Lattner97bfcea2004-06-17 18:16:02 +00001147 NewTy = SI->getType()->getUnsignedVersion();
Chris Lattner92295c52004-03-12 23:53:13 +00001148 else
Chris Lattner97bfcea2004-06-17 18:16:02 +00001149 NewTy = SI->getType()->getSignedVersion();
Chris Lattner92295c52004-03-12 23:53:13 +00001150 // Check to see if we are shifting out everything but the sign bit.
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001151 if (CU->getValue() == SI->getType()->getPrimitiveSizeInBits()-1) {
Chris Lattner92295c52004-03-12 23:53:13 +00001152 // Ok, the transformation is safe. Insert a cast of the incoming
1153 // value, then the new shift, then the new cast.
1154 Instruction *FirstCast = new CastInst(SI->getOperand(0), NewTy,
1155 SI->getOperand(0)->getName());
1156 Value *InV = InsertNewInstBefore(FirstCast, I);
1157 Instruction *NewShift = new ShiftInst(Instruction::Shr, FirstCast,
1158 CU, SI->getName());
Chris Lattner022167f2004-03-13 00:11:49 +00001159 if (NewShift->getType() == I.getType())
1160 return NewShift;
1161 else {
1162 InV = InsertNewInstBefore(NewShift, I);
1163 return new CastInst(NewShift, I.getType());
1164 }
Chris Lattner92295c52004-03-12 23:53:13 +00001165 }
1166 }
Chris Lattner022167f2004-03-13 00:11:49 +00001167 }
Chris Lattner183b3362004-04-09 19:05:30 +00001168
1169 // Try to fold constant sub into select arguments.
1170 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00001171 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00001172 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001173
1174 if (isa<PHINode>(Op0))
1175 if (Instruction *NV = FoldOpIntoPhi(I))
1176 return NV;
Chris Lattner8f2f5982003-11-05 01:06:05 +00001177 }
1178
Chris Lattnera9be4492005-04-07 16:15:25 +00001179 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
1180 if (Op1I->getOpcode() == Instruction::Add &&
1181 !Op0->getType()->isFloatingPoint()) {
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00001182 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +00001183 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00001184 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +00001185 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00001186 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
1187 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
1188 // C1-(X+C2) --> (C1-C2)-X
1189 return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
1190 Op1I->getOperand(0));
1191 }
Chris Lattnera9be4492005-04-07 16:15:25 +00001192 }
1193
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001194 if (Op1I->hasOneUse()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00001195 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
1196 // is not used by anyone else...
1197 //
Chris Lattnerc2f0aa52004-02-02 20:09:56 +00001198 if (Op1I->getOpcode() == Instruction::Sub &&
1199 !Op1I->getType()->isFloatingPoint()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00001200 // Swap the two operands of the subexpr...
1201 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
1202 Op1I->setOperand(0, IIOp1);
1203 Op1I->setOperand(1, IIOp0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001204
Chris Lattner3082c5a2003-02-18 19:28:33 +00001205 // Create the new top level add instruction...
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001206 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001207 }
1208
1209 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
1210 //
1211 if (Op1I->getOpcode() == Instruction::And &&
1212 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
1213 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
1214
Chris Lattner396dbfe2004-06-09 05:08:07 +00001215 Value *NewNot =
1216 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001217 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001218 }
Chris Lattner57c8d992003-02-18 19:57:07 +00001219
Chris Lattner0aee4b72004-10-06 15:08:25 +00001220 // -(X sdiv C) -> (X sdiv -C)
1221 if (Op1I->getOpcode() == Instruction::Div)
1222 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
Chris Lattnera9be4492005-04-07 16:15:25 +00001223 if (CSI->isNullValue())
Chris Lattner0aee4b72004-10-06 15:08:25 +00001224 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Misha Brukmanb1c93172005-04-21 23:48:37 +00001225 return BinaryOperator::createDiv(Op1I->getOperand(0),
Chris Lattner0aee4b72004-10-06 15:08:25 +00001226 ConstantExpr::getNeg(DivRHS));
1227
Chris Lattner57c8d992003-02-18 19:57:07 +00001228 // X - X*C --> X * (1-C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00001229 ConstantInt *C2 = 0;
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001230 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00001231 Constant *CP1 =
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001232 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001233 return BinaryOperator::createMul(Op0, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +00001234 }
Chris Lattnerad3c4952002-05-09 01:29:19 +00001235 }
Chris Lattnera9be4492005-04-07 16:15:25 +00001236 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001237
Chris Lattner47060462005-04-07 17:14:51 +00001238 if (!Op0->getType()->isFloatingPoint())
1239 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
1240 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner411336f2005-01-19 21:50:18 +00001241 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
1242 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
1243 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
1244 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner47060462005-04-07 17:14:51 +00001245 } else if (Op0I->getOpcode() == Instruction::Sub) {
1246 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
1247 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
Chris Lattner411336f2005-01-19 21:50:18 +00001248 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001249
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001250 ConstantInt *C1;
1251 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
1252 if (X == Op1) { // X*C - X --> X * (C-1)
1253 Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
1254 return BinaryOperator::createMul(Op1, CP1);
1255 }
Chris Lattner57c8d992003-02-18 19:57:07 +00001256
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001257 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
1258 if (X == dyn_castFoldableMul(Op1, C2))
1259 return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
1260 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001261 return 0;
Chris Lattner260ab202002-04-18 17:39:14 +00001262}
1263
Chris Lattnere79e8542004-02-23 06:38:22 +00001264/// isSignBitCheck - Given an exploded setcc instruction, return true if it is
1265/// really just returns true if the most significant (sign) bit is set.
1266static bool isSignBitCheck(unsigned Opcode, Value *LHS, ConstantInt *RHS) {
1267 if (RHS->getType()->isSigned()) {
1268 // True if source is LHS < 0 or LHS <= -1
1269 return Opcode == Instruction::SetLT && RHS->isNullValue() ||
1270 Opcode == Instruction::SetLE && RHS->isAllOnesValue();
1271 } else {
1272 ConstantUInt *RHSC = cast<ConstantUInt>(RHS);
1273 // True if source is LHS > 127 or LHS >= 128, where the constants depend on
1274 // the size of the integer type.
1275 if (Opcode == Instruction::SetGE)
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001276 return RHSC->getValue() ==
1277 1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1);
Chris Lattnere79e8542004-02-23 06:38:22 +00001278 if (Opcode == Instruction::SetGT)
1279 return RHSC->getValue() ==
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001280 (1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1))-1;
Chris Lattnere79e8542004-02-23 06:38:22 +00001281 }
1282 return false;
1283}
1284
Chris Lattner113f4f42002-06-25 16:13:24 +00001285Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001286 bool Changed = SimplifyCommutative(I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001287 Value *Op0 = I.getOperand(0);
Chris Lattner260ab202002-04-18 17:39:14 +00001288
Chris Lattner81a7a232004-10-16 18:11:37 +00001289 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
1290 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1291
Chris Lattnere6794492002-08-12 21:17:25 +00001292 // Simplify mul instructions with a constant RHS...
Chris Lattner3082c5a2003-02-18 19:28:33 +00001293 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
1294 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerede3fe02003-08-13 04:18:28 +00001295
1296 // ((X << C1)*C2) == (X * (C2 << C1))
1297 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
1298 if (SI->getOpcode() == Instruction::Shl)
1299 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001300 return BinaryOperator::createMul(SI->getOperand(0),
1301 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanb1c93172005-04-21 23:48:37 +00001302
Chris Lattnercce81be2003-09-11 22:24:54 +00001303 if (CI->isNullValue())
1304 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
1305 if (CI->equalsInt(1)) // X * 1 == X
1306 return ReplaceInstUsesWith(I, Op0);
1307 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner35236d82003-06-25 17:09:20 +00001308 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner31ba1292002-04-29 22:24:47 +00001309
Chris Lattnercce81be2003-09-11 22:24:54 +00001310 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getRawValue();
Chris Lattner22d00a82005-08-02 19:16:58 +00001311 if (isPowerOf2_64(Val)) { // Replace X*(2^C) with X << C
1312 uint64_t C = Log2_64(Val);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001313 return new ShiftInst(Instruction::Shl, Op0,
1314 ConstantUInt::get(Type::UByteTy, C));
Chris Lattner22d00a82005-08-02 19:16:58 +00001315 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00001316 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00001317 if (Op1F->isNullValue())
1318 return ReplaceInstUsesWith(I, Op1);
Chris Lattner31ba1292002-04-29 22:24:47 +00001319
Chris Lattner3082c5a2003-02-18 19:28:33 +00001320 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
1321 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
1322 if (Op1F->getValue() == 1.0)
1323 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
1324 }
Chris Lattner183b3362004-04-09 19:05:30 +00001325
1326 // Try to fold constant mul into select arguments.
1327 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00001328 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00001329 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001330
1331 if (isa<PHINode>(Op0))
1332 if (Instruction *NV = FoldOpIntoPhi(I))
1333 return NV;
Chris Lattner260ab202002-04-18 17:39:14 +00001334 }
1335
Chris Lattner934a64cf2003-03-10 23:23:04 +00001336 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
1337 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001338 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattner934a64cf2003-03-10 23:23:04 +00001339
Chris Lattner2635b522004-02-23 05:39:21 +00001340 // If one of the operands of the multiply is a cast from a boolean value, then
1341 // we know the bool is either zero or one, so this is a 'masking' multiply.
1342 // See if we can simplify things based on how the boolean was originally
1343 // formed.
1344 CastInst *BoolCast = 0;
1345 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(0)))
1346 if (CI->getOperand(0)->getType() == Type::BoolTy)
1347 BoolCast = CI;
1348 if (!BoolCast)
1349 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(1)))
1350 if (CI->getOperand(0)->getType() == Type::BoolTy)
1351 BoolCast = CI;
1352 if (BoolCast) {
1353 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BoolCast->getOperand(0))) {
1354 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
1355 const Type *SCOpTy = SCIOp0->getType();
1356
Chris Lattnere79e8542004-02-23 06:38:22 +00001357 // If the setcc is true iff the sign bit of X is set, then convert this
1358 // multiply into a shift/and combination.
1359 if (isa<ConstantInt>(SCIOp1) &&
1360 isSignBitCheck(SCI->getOpcode(), SCIOp0, cast<ConstantInt>(SCIOp1))) {
Chris Lattner2635b522004-02-23 05:39:21 +00001361 // Shift the X value right to turn it into "all signbits".
1362 Constant *Amt = ConstantUInt::get(Type::UByteTy,
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001363 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattnere79e8542004-02-23 06:38:22 +00001364 if (SCIOp0->getType()->isUnsigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +00001365 const Type *NewTy = SCIOp0->getType()->getSignedVersion();
Chris Lattnere79e8542004-02-23 06:38:22 +00001366 SCIOp0 = InsertNewInstBefore(new CastInst(SCIOp0, NewTy,
1367 SCIOp0->getName()), I);
1368 }
1369
1370 Value *V =
1371 InsertNewInstBefore(new ShiftInst(Instruction::Shr, SCIOp0, Amt,
1372 BoolCast->getOperand(0)->getName()+
1373 ".mask"), I);
Chris Lattner2635b522004-02-23 05:39:21 +00001374
1375 // If the multiply type is not the same as the source type, sign extend
1376 // or truncate to the multiply type.
1377 if (I.getType() != V->getType())
Chris Lattnere79e8542004-02-23 06:38:22 +00001378 V = InsertNewInstBefore(new CastInst(V, I.getType(), V->getName()),I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001379
Chris Lattner2635b522004-02-23 05:39:21 +00001380 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001381 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattner2635b522004-02-23 05:39:21 +00001382 }
1383 }
1384 }
1385
Chris Lattner113f4f42002-06-25 16:13:24 +00001386 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00001387}
1388
Chris Lattner113f4f42002-06-25 16:13:24 +00001389Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001390 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner81a7a232004-10-16 18:11:37 +00001391
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001392 if (isa<UndefValue>(Op0)) // undef / X -> 0
1393 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1394 if (isa<UndefValue>(Op1))
1395 return ReplaceInstUsesWith(I, Op1); // X / undef -> undef
1396
1397 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere20c3342004-04-26 14:01:59 +00001398 // div X, 1 == X
Chris Lattnere6794492002-08-12 21:17:25 +00001399 if (RHS->equalsInt(1))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001400 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001401
Chris Lattnere20c3342004-04-26 14:01:59 +00001402 // div X, -1 == -X
1403 if (RHS->isAllOnesValue())
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001404 return BinaryOperator::createNeg(Op0);
Chris Lattnere20c3342004-04-26 14:01:59 +00001405
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001406 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
Chris Lattner272d5ca2004-09-28 18:22:15 +00001407 if (LHS->getOpcode() == Instruction::Div)
1408 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Chris Lattner272d5ca2004-09-28 18:22:15 +00001409 // (X / C1) / C2 -> X / (C1*C2)
1410 return BinaryOperator::createDiv(LHS->getOperand(0),
1411 ConstantExpr::getMul(RHS, LHSRHS));
1412 }
1413
Chris Lattner3082c5a2003-02-18 19:28:33 +00001414 // Check to see if this is an unsigned division with an exact power of 2,
1415 // if so, convert to a right shift.
1416 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
1417 if (uint64_t Val = C->getValue()) // Don't break X / 0
Chris Lattner22d00a82005-08-02 19:16:58 +00001418 if (isPowerOf2_64(Val)) {
1419 uint64_t C = Log2_64(Val);
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001420 return new ShiftInst(Instruction::Shr, Op0,
Chris Lattner3082c5a2003-02-18 19:28:33 +00001421 ConstantUInt::get(Type::UByteTy, C));
Chris Lattner22d00a82005-08-02 19:16:58 +00001422 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001423
Chris Lattner4ad08352004-10-09 02:50:40 +00001424 // -X/C -> X/-C
1425 if (RHS->getType()->isSigned())
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001426 if (Value *LHSNeg = dyn_castNegVal(Op0))
Chris Lattner4ad08352004-10-09 02:50:40 +00001427 return BinaryOperator::createDiv(LHSNeg, ConstantExpr::getNeg(RHS));
1428
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001429 if (!RHS->isNullValue()) {
1430 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00001431 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001432 return R;
1433 if (isa<PHINode>(Op0))
1434 if (Instruction *NV = FoldOpIntoPhi(I))
1435 return NV;
1436 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001437 }
1438
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001439 // If this is 'udiv X, (Cond ? C1, C2)' where C1&C2 are powers of two,
1440 // transform this into: '(Cond ? (udiv X, C1) : (udiv X, C2))'.
1441 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1442 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
1443 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
1444 if (STO->getValue() == 0) { // Couldn't be this argument.
1445 I.setOperand(1, SFO);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001446 return &I;
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001447 } else if (SFO->getValue() == 0) {
Chris Lattner89dc4f12005-06-16 04:55:52 +00001448 I.setOperand(1, STO);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001449 return &I;
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001450 }
1451
Chris Lattner42362612005-04-08 04:03:26 +00001452 uint64_t TVA = STO->getValue(), FVA = SFO->getValue();
Chris Lattner22d00a82005-08-02 19:16:58 +00001453 if (isPowerOf2_64(TVA) && isPowerOf2_64(FVA)) {
1454 unsigned TSA = Log2_64(TVA), FSA = Log2_64(FVA);
Chris Lattner42362612005-04-08 04:03:26 +00001455 Constant *TC = ConstantUInt::get(Type::UByteTy, TSA);
1456 Instruction *TSI = new ShiftInst(Instruction::Shr, Op0,
1457 TC, SI->getName()+".t");
1458 TSI = InsertNewInstBefore(TSI, I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001459
Chris Lattner42362612005-04-08 04:03:26 +00001460 Constant *FC = ConstantUInt::get(Type::UByteTy, FSA);
1461 Instruction *FSI = new ShiftInst(Instruction::Shr, Op0,
1462 FC, SI->getName()+".f");
1463 FSI = InsertNewInstBefore(FSI, I);
1464 return new SelectInst(SI->getOperand(0), TSI, FSI);
1465 }
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001466 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001467
Chris Lattner3082c5a2003-02-18 19:28:33 +00001468 // 0 / X == 0, we don't need to preserve faults!
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001469 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattner3082c5a2003-02-18 19:28:33 +00001470 if (LHS->equalsInt(0))
1471 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1472
Chris Lattnerdd0c1742005-11-05 07:40:31 +00001473 if (I.getType()->isSigned()) {
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001474 // If the sign bits of both operands are zero (i.e. we can prove they are
Chris Lattnerdd0c1742005-11-05 07:40:31 +00001475 // unsigned inputs), turn this into a udiv.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001476 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
1477 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Chris Lattnerdd0c1742005-11-05 07:40:31 +00001478 const Type *NTy = Op0->getType()->getUnsignedVersion();
1479 Instruction *LHS = new CastInst(Op0, NTy, Op0->getName());
1480 InsertNewInstBefore(LHS, I);
1481 Value *RHS;
1482 if (Constant *R = dyn_cast<Constant>(Op1))
1483 RHS = ConstantExpr::getCast(R, NTy);
1484 else
1485 RHS = InsertNewInstBefore(new CastInst(Op1, NTy, Op1->getName()), I);
1486 Instruction *Div = BinaryOperator::createDiv(LHS, RHS, I.getName());
1487 InsertNewInstBefore(Div, I);
1488 return new CastInst(Div, I.getType());
1489 }
Chris Lattner2e90b732006-02-05 07:54:04 +00001490 } else {
1491 // Known to be an unsigned division.
1492 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
1493 // Turn A / (C1 << N), where C1 is "1<<C2" into A >> (N+C2) [udiv only].
1494 if (RHSI->getOpcode() == Instruction::Shl &&
1495 isa<ConstantUInt>(RHSI->getOperand(0))) {
1496 unsigned C1 = cast<ConstantUInt>(RHSI->getOperand(0))->getRawValue();
1497 if (isPowerOf2_64(C1)) {
1498 unsigned C2 = Log2_64(C1);
1499 Value *Add = RHSI->getOperand(1);
1500 if (C2) {
1501 Constant *C2V = ConstantUInt::get(Add->getType(), C2);
1502 Add = InsertNewInstBefore(BinaryOperator::createAdd(Add, C2V,
1503 "tmp"), I);
1504 }
1505 return new ShiftInst(Instruction::Shr, Op0, Add);
1506 }
1507 }
1508 }
Chris Lattnerdd0c1742005-11-05 07:40:31 +00001509 }
1510
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001511 return 0;
1512}
1513
1514
Chris Lattner113f4f42002-06-25 16:13:24 +00001515Instruction *InstCombiner::visitRem(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001516 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere9ff0ea2005-11-05 07:28:37 +00001517 if (I.getType()->isSigned()) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001518 if (Value *RHSNeg = dyn_castNegVal(Op1))
Chris Lattner98c6bdf2004-07-06 07:11:42 +00001519 if (!isa<ConstantSInt>(RHSNeg) ||
Chris Lattner8e726062004-08-09 21:05:48 +00001520 cast<ConstantSInt>(RHSNeg)->getValue() > 0) {
Chris Lattner7fd5f072004-07-06 07:01:22 +00001521 // X % -Y -> X % Y
1522 AddUsesToWorkList(I);
1523 I.setOperand(1, RHSNeg);
1524 return &I;
1525 }
Chris Lattnere9ff0ea2005-11-05 07:28:37 +00001526
1527 // If the top bits of both operands are zero (i.e. we can prove they are
1528 // unsigned inputs), turn this into a urem.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001529 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
1530 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Chris Lattnere9ff0ea2005-11-05 07:28:37 +00001531 const Type *NTy = Op0->getType()->getUnsignedVersion();
1532 Instruction *LHS = new CastInst(Op0, NTy, Op0->getName());
1533 InsertNewInstBefore(LHS, I);
1534 Value *RHS;
1535 if (Constant *R = dyn_cast<Constant>(Op1))
1536 RHS = ConstantExpr::getCast(R, NTy);
1537 else
1538 RHS = InsertNewInstBefore(new CastInst(Op1, NTy, Op1->getName()), I);
1539 Instruction *Rem = BinaryOperator::createRem(LHS, RHS, I.getName());
1540 InsertNewInstBefore(Rem, I);
1541 return new CastInst(Rem, I.getType());
1542 }
1543 }
Chris Lattner7fd5f072004-07-06 07:01:22 +00001544
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001545 if (isa<UndefValue>(Op0)) // undef % X -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00001546 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001547 if (isa<UndefValue>(Op1))
1548 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Chris Lattner81a7a232004-10-16 18:11:37 +00001549
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001550 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00001551 if (RHS->equalsInt(1)) // X % 1 == 0
1552 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1553
1554 // Check to see if this is an unsigned remainder with an exact power of 2,
1555 // if so, convert to a bitwise and.
1556 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
1557 if (uint64_t Val = C->getValue()) // Don't break X % 0 (divide by zero)
Chris Lattnerd9e58132004-05-07 15:35:56 +00001558 if (!(Val & (Val-1))) // Power of 2
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001559 return BinaryOperator::createAnd(Op0,
1560 ConstantUInt::get(I.getType(), Val-1));
1561
1562 if (!RHS->isNullValue()) {
1563 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00001564 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001565 return R;
1566 if (isa<PHINode>(Op0))
1567 if (Instruction *NV = FoldOpIntoPhi(I))
1568 return NV;
1569 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001570 }
1571
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001572 // If this is 'urem X, (Cond ? C1, C2)' where C1&C2 are powers of two,
1573 // transform this into: '(Cond ? (urem X, C1) : (urem X, C2))'.
1574 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1575 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
1576 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
1577 if (STO->getValue() == 0) { // Couldn't be this argument.
1578 I.setOperand(1, SFO);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001579 return &I;
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001580 } else if (SFO->getValue() == 0) {
1581 I.setOperand(1, STO);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001582 return &I;
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001583 }
1584
1585 if (!(STO->getValue() & (STO->getValue()-1)) &&
1586 !(SFO->getValue() & (SFO->getValue()-1))) {
1587 Value *TrueAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
1588 SubOne(STO), SI->getName()+".t"), I);
1589 Value *FalseAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
1590 SubOne(SFO), SI->getName()+".f"), I);
1591 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
1592 }
1593 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001594
Chris Lattner3082c5a2003-02-18 19:28:33 +00001595 // 0 % X == 0, we don't need to preserve faults!
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001596 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattner3082c5a2003-02-18 19:28:33 +00001597 if (LHS->equalsInt(0))
Chris Lattnere6794492002-08-12 21:17:25 +00001598 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1599
Chris Lattner2e90b732006-02-05 07:54:04 +00001600
1601 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
1602 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1) [urem only].
1603 if (I.getType()->isUnsigned() &&
1604 RHSI->getOpcode() == Instruction::Shl &&
1605 isa<ConstantUInt>(RHSI->getOperand(0))) {
1606 unsigned C1 = cast<ConstantUInt>(RHSI->getOperand(0))->getRawValue();
1607 if (isPowerOf2_64(C1)) {
1608 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
1609 Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
1610 "tmp"), I);
1611 return BinaryOperator::createAnd(Op0, Add);
1612 }
1613 }
1614 }
1615
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001616 return 0;
1617}
1618
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001619// isMaxValueMinusOne - return true if this is Max-1
Chris Lattnere6794492002-08-12 21:17:25 +00001620static bool isMaxValueMinusOne(const ConstantInt *C) {
Chris Lattner77defba2006-02-07 07:00:41 +00001621 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
1622 return CU->getValue() == C->getType()->getIntegralTypeMask()-1;
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001623
1624 const ConstantSInt *CS = cast<ConstantSInt>(C);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001625
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001626 // Calculate 0111111111..11111
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001627 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001628 int64_t Val = INT64_MAX; // All ones
1629 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
1630 return CS->getValue() == Val-1;
1631}
1632
1633// isMinValuePlusOne - return true if this is Min+1
Chris Lattnere6794492002-08-12 21:17:25 +00001634static bool isMinValuePlusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001635 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
1636 return CU->getValue() == 1;
1637
1638 const ConstantSInt *CS = cast<ConstantSInt>(C);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001639
1640 // Calculate 1111111111000000000000
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001641 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001642 int64_t Val = -1; // All ones
1643 Val <<= TypeBits-1; // Shift over to the right spot
1644 return CS->getValue() == Val+1;
1645}
1646
Chris Lattner35167c32004-06-09 07:59:58 +00001647// isOneBitSet - Return true if there is exactly one bit set in the specified
1648// constant.
1649static bool isOneBitSet(const ConstantInt *CI) {
1650 uint64_t V = CI->getRawValue();
1651 return V && (V & (V-1)) == 0;
1652}
1653
Chris Lattner8fc5af42004-09-23 21:46:38 +00001654#if 0 // Currently unused
1655// isLowOnes - Return true if the constant is of the form 0+1+.
1656static bool isLowOnes(const ConstantInt *CI) {
1657 uint64_t V = CI->getRawValue();
1658
1659 // There won't be bits set in parts that the type doesn't contain.
1660 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
1661
1662 uint64_t U = V+1; // If it is low ones, this should be a power of two.
1663 return U && V && (U & V) == 0;
1664}
1665#endif
1666
1667// isHighOnes - Return true if the constant is of the form 1+0+.
1668// This is the same as lowones(~X).
1669static bool isHighOnes(const ConstantInt *CI) {
1670 uint64_t V = ~CI->getRawValue();
Chris Lattner2c14cf72005-08-07 07:03:10 +00001671 if (~V == 0) return false; // 0's does not match "1+"
Chris Lattner8fc5af42004-09-23 21:46:38 +00001672
1673 // There won't be bits set in parts that the type doesn't contain.
1674 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
1675
1676 uint64_t U = V+1; // If it is low ones, this should be a power of two.
1677 return U && V && (U & V) == 0;
1678}
1679
1680
Chris Lattner3ac7c262003-08-13 20:16:26 +00001681/// getSetCondCode - Encode a setcc opcode into a three bit mask. These bits
1682/// are carefully arranged to allow folding of expressions such as:
1683///
1684/// (A < B) | (A > B) --> (A != B)
1685///
1686/// Bit value '4' represents that the comparison is true if A > B, bit value '2'
1687/// represents that the comparison is true if A == B, and bit value '1' is true
1688/// if A < B.
1689///
1690static unsigned getSetCondCode(const SetCondInst *SCI) {
1691 switch (SCI->getOpcode()) {
1692 // False -> 0
1693 case Instruction::SetGT: return 1;
1694 case Instruction::SetEQ: return 2;
1695 case Instruction::SetGE: return 3;
1696 case Instruction::SetLT: return 4;
1697 case Instruction::SetNE: return 5;
1698 case Instruction::SetLE: return 6;
1699 // True -> 7
1700 default:
1701 assert(0 && "Invalid SetCC opcode!");
1702 return 0;
1703 }
1704}
1705
1706/// getSetCCValue - This is the complement of getSetCondCode, which turns an
1707/// opcode and two operands into either a constant true or false, or a brand new
1708/// SetCC instruction.
1709static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
1710 switch (Opcode) {
1711 case 0: return ConstantBool::False;
1712 case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
1713 case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
1714 case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
1715 case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
1716 case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
1717 case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
1718 case 7: return ConstantBool::True;
1719 default: assert(0 && "Illegal SetCCCode!"); return 0;
1720 }
1721}
1722
1723// FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
1724struct FoldSetCCLogical {
1725 InstCombiner &IC;
1726 Value *LHS, *RHS;
1727 FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
1728 : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
1729 bool shouldApply(Value *V) const {
1730 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
1731 return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
1732 SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
1733 return false;
1734 }
1735 Instruction *apply(BinaryOperator &Log) const {
1736 SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
1737 if (SCI->getOperand(0) != LHS) {
1738 assert(SCI->getOperand(1) == LHS);
1739 SCI->swapOperands(); // Swap the LHS and RHS of the SetCC
1740 }
1741
1742 unsigned LHSCode = getSetCondCode(SCI);
1743 unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
1744 unsigned Code;
1745 switch (Log.getOpcode()) {
1746 case Instruction::And: Code = LHSCode & RHSCode; break;
1747 case Instruction::Or: Code = LHSCode | RHSCode; break;
1748 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner2caaaba2003-09-22 20:33:34 +00001749 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattner3ac7c262003-08-13 20:16:26 +00001750 }
1751
1752 Value *RV = getSetCCValue(Code, LHS, RHS);
1753 if (Instruction *I = dyn_cast<Instruction>(RV))
1754 return I;
1755 // Otherwise, it's a constant boolean value...
1756 return IC.ReplaceInstUsesWith(Log, RV);
1757 }
1758};
1759
Chris Lattnerba1cb382003-09-19 17:17:26 +00001760// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
1761// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
1762// guaranteed to be either a shift instruction or a binary operator.
1763Instruction *InstCombiner::OptAndOp(Instruction *Op,
1764 ConstantIntegral *OpRHS,
1765 ConstantIntegral *AndRHS,
1766 BinaryOperator &TheAnd) {
1767 Value *X = Op->getOperand(0);
Chris Lattnerfcf21a72004-01-12 19:47:05 +00001768 Constant *Together = 0;
1769 if (!isa<ShiftInst>(Op))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001770 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001771
Chris Lattnerba1cb382003-09-19 17:17:26 +00001772 switch (Op->getOpcode()) {
1773 case Instruction::Xor:
Chris Lattner86102b82005-01-01 16:22:27 +00001774 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001775 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
1776 std::string OpName = Op->getName(); Op->setName("");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001777 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001778 InsertNewInstBefore(And, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001779 return BinaryOperator::createXor(And, Together);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001780 }
1781 break;
1782 case Instruction::Or:
Chris Lattner86102b82005-01-01 16:22:27 +00001783 if (Together == AndRHS) // (X | C) & C --> C
1784 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001785
Chris Lattner86102b82005-01-01 16:22:27 +00001786 if (Op->hasOneUse() && Together != OpRHS) {
1787 // (X | C1) & C2 --> (X | (C1&C2)) & C2
1788 std::string Op0Name = Op->getName(); Op->setName("");
1789 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
1790 InsertNewInstBefore(Or, TheAnd);
1791 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001792 }
1793 break;
1794 case Instruction::Add:
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001795 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001796 // Adding a one to a single bit bit-field should be turned into an XOR
1797 // of the bit. First thing to check is to see if this AND is with a
1798 // single bit constant.
Chris Lattner35167c32004-06-09 07:59:58 +00001799 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getRawValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00001800
1801 // Clear bits that are not part of the constant.
Chris Lattner77defba2006-02-07 07:00:41 +00001802 AndRHSV &= AndRHS->getType()->getIntegralTypeMask();
Chris Lattnerba1cb382003-09-19 17:17:26 +00001803
1804 // If there is only one bit set...
Chris Lattner35167c32004-06-09 07:59:58 +00001805 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001806 // Ok, at this point, we know that we are masking the result of the
1807 // ADD down to exactly one bit. If the constant we are adding has
1808 // no bits set below this bit, then we can eliminate the ADD.
Chris Lattner35167c32004-06-09 07:59:58 +00001809 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getRawValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001810
Chris Lattnerba1cb382003-09-19 17:17:26 +00001811 // Check to see if any bits below the one bit set in AndRHSV are set.
1812 if ((AddRHS & (AndRHSV-1)) == 0) {
1813 // If not, the only thing that can effect the output of the AND is
1814 // the bit specified by AndRHSV. If that bit is set, the effect of
1815 // the XOR is to toggle the bit. If it is clear, then the ADD has
1816 // no effect.
1817 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
1818 TheAnd.setOperand(0, X);
1819 return &TheAnd;
1820 } else {
1821 std::string Name = Op->getName(); Op->setName("");
1822 // Pull the XOR out of the AND.
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001823 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001824 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001825 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001826 }
1827 }
1828 }
1829 }
1830 break;
Chris Lattner2da29172003-09-19 19:05:02 +00001831
1832 case Instruction::Shl: {
1833 // We know that the AND will not produce any of the bits shifted in, so if
1834 // the anded constant includes them, clear them now!
1835 //
1836 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00001837 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
1838 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001839
Chris Lattner7e794272004-09-24 15:21:34 +00001840 if (CI == ShlMask) { // Masking out bits that the shift already masks
1841 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
1842 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner2da29172003-09-19 19:05:02 +00001843 TheAnd.setOperand(1, CI);
1844 return &TheAnd;
1845 }
1846 break;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001847 }
Chris Lattner2da29172003-09-19 19:05:02 +00001848 case Instruction::Shr:
1849 // We know that the AND will not produce any of the bits shifted in, so if
1850 // the anded constant includes them, clear them now! This only applies to
1851 // unsigned shifts, because a signed shr may bring in set bits!
1852 //
1853 if (AndRHS->getType()->isUnsigned()) {
1854 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00001855 Constant *ShrMask = ConstantExpr::getShr(AllOne, OpRHS);
1856 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
1857
1858 if (CI == ShrMask) { // Masking out bits that the shift already masks.
1859 return ReplaceInstUsesWith(TheAnd, Op);
1860 } else if (CI != AndRHS) {
1861 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
Chris Lattner2da29172003-09-19 19:05:02 +00001862 return &TheAnd;
1863 }
Chris Lattner7e794272004-09-24 15:21:34 +00001864 } else { // Signed shr.
1865 // See if this is shifting in some sign extension, then masking it out
1866 // with an and.
1867 if (Op->hasOneUse()) {
1868 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
1869 Constant *ShrMask = ConstantExpr::getUShr(AllOne, OpRHS);
1870 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
Chris Lattner5c3c21e2004-10-22 04:53:16 +00001871 if (CI == AndRHS) { // Masking out bits shifted in.
Chris Lattner7e794272004-09-24 15:21:34 +00001872 // Make the argument unsigned.
1873 Value *ShVal = Op->getOperand(0);
1874 ShVal = InsertCastBefore(ShVal,
1875 ShVal->getType()->getUnsignedVersion(),
1876 TheAnd);
1877 ShVal = InsertNewInstBefore(new ShiftInst(Instruction::Shr, ShVal,
1878 OpRHS, Op->getName()),
1879 TheAnd);
Chris Lattner70c20392004-10-27 05:57:15 +00001880 Value *AndRHS2 = ConstantExpr::getCast(AndRHS, ShVal->getType());
1881 ShVal = InsertNewInstBefore(BinaryOperator::createAnd(ShVal, AndRHS2,
1882 TheAnd.getName()),
1883 TheAnd);
Chris Lattner7e794272004-09-24 15:21:34 +00001884 return new CastInst(ShVal, Op->getType());
1885 }
1886 }
Chris Lattner2da29172003-09-19 19:05:02 +00001887 }
1888 break;
Chris Lattnerba1cb382003-09-19 17:17:26 +00001889 }
1890 return 0;
1891}
1892
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001893
Chris Lattner6862fbd2004-09-29 17:40:11 +00001894/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
1895/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
1896/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. IB is the location to
1897/// insert new instructions.
1898Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
1899 bool Inside, Instruction &IB) {
1900 assert(cast<ConstantBool>(ConstantExpr::getSetLE(Lo, Hi))->getValue() &&
1901 "Lo is not <= Hi in range emission code!");
1902 if (Inside) {
1903 if (Lo == Hi) // Trivially false.
1904 return new SetCondInst(Instruction::SetNE, V, V);
1905 if (cast<ConstantIntegral>(Lo)->isMinValue())
1906 return new SetCondInst(Instruction::SetLT, V, Hi);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001907
Chris Lattner6862fbd2004-09-29 17:40:11 +00001908 Constant *AddCST = ConstantExpr::getNeg(Lo);
1909 Instruction *Add = BinaryOperator::createAdd(V, AddCST,V->getName()+".off");
1910 InsertNewInstBefore(Add, IB);
1911 // Convert to unsigned for the comparison.
1912 const Type *UnsType = Add->getType()->getUnsignedVersion();
1913 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
1914 AddCST = ConstantExpr::getAdd(AddCST, Hi);
1915 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1916 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
1917 }
1918
1919 if (Lo == Hi) // Trivially true.
1920 return new SetCondInst(Instruction::SetEQ, V, V);
1921
1922 Hi = SubOne(cast<ConstantInt>(Hi));
1923 if (cast<ConstantIntegral>(Lo)->isMinValue()) // V < 0 || V >= Hi ->'V > Hi-1'
1924 return new SetCondInst(Instruction::SetGT, V, Hi);
1925
1926 // Emit X-Lo > Hi-Lo-1
1927 Constant *AddCST = ConstantExpr::getNeg(Lo);
1928 Instruction *Add = BinaryOperator::createAdd(V, AddCST, V->getName()+".off");
1929 InsertNewInstBefore(Add, IB);
1930 // Convert to unsigned for the comparison.
1931 const Type *UnsType = Add->getType()->getUnsignedVersion();
1932 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
1933 AddCST = ConstantExpr::getAdd(AddCST, Hi);
1934 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1935 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
1936}
1937
Chris Lattnerb4b25302005-09-18 07:22:02 +00001938// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
1939// any number of 0s on either side. The 1s are allowed to wrap from LSB to
1940// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
1941// not, since all 1s are not contiguous.
1942static bool isRunOfOnes(ConstantIntegral *Val, unsigned &MB, unsigned &ME) {
1943 uint64_t V = Val->getRawValue();
1944 if (!isShiftedMask_64(V)) return false;
1945
1946 // look for the first zero bit after the run of ones
1947 MB = 64-CountLeadingZeros_64((V - 1) ^ V);
1948 // look for the first non-zero bit
1949 ME = 64-CountLeadingZeros_64(V);
1950 return true;
1951}
1952
1953
1954
1955/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
1956/// where isSub determines whether the operator is a sub. If we can fold one of
1957/// the following xforms:
Chris Lattneraf517572005-09-18 04:24:45 +00001958///
1959/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
1960/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
1961/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
1962///
1963/// return (A +/- B).
1964///
1965Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
1966 ConstantIntegral *Mask, bool isSub,
1967 Instruction &I) {
1968 Instruction *LHSI = dyn_cast<Instruction>(LHS);
1969 if (!LHSI || LHSI->getNumOperands() != 2 ||
1970 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
1971
1972 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
1973
1974 switch (LHSI->getOpcode()) {
1975 default: return 0;
1976 case Instruction::And:
Chris Lattnerb4b25302005-09-18 07:22:02 +00001977 if (ConstantExpr::getAnd(N, Mask) == Mask) {
1978 // If the AndRHS is a power of two minus one (0+1+), this is simple.
1979 if ((Mask->getRawValue() & Mask->getRawValue()+1) == 0)
1980 break;
1981
1982 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
1983 // part, we don't need any explicit masks to take them out of A. If that
1984 // is all N is, ignore it.
1985 unsigned MB, ME;
1986 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001987 uint64_t Mask = RHS->getType()->getIntegralTypeMask();
1988 Mask >>= 64-MB+1;
1989 if (MaskedValueIsZero(RHS, Mask))
Chris Lattnerb4b25302005-09-18 07:22:02 +00001990 break;
1991 }
1992 }
Chris Lattneraf517572005-09-18 04:24:45 +00001993 return 0;
1994 case Instruction::Or:
1995 case Instruction::Xor:
Chris Lattnerb4b25302005-09-18 07:22:02 +00001996 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
1997 if ((Mask->getRawValue() & Mask->getRawValue()+1) == 0 &&
1998 ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattneraf517572005-09-18 04:24:45 +00001999 break;
2000 return 0;
2001 }
2002
2003 Instruction *New;
2004 if (isSub)
2005 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
2006 else
2007 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
2008 return InsertNewInstBefore(New, I);
2009}
2010
Chris Lattner113f4f42002-06-25 16:13:24 +00002011Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002012 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00002013 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002014
Chris Lattner81a7a232004-10-16 18:11:37 +00002015 if (isa<UndefValue>(Op1)) // X & undef -> 0
2016 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2017
Chris Lattner86102b82005-01-01 16:22:27 +00002018 // and X, X = X
2019 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00002020 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002021
Chris Lattner5997cf92006-02-08 03:25:32 +00002022 // See if we can simplify any instructions used by the LHS whose sole
2023 // purpose is to compute bits we don't care about.
2024 if (SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask()))
2025 return &I;
2026
Chris Lattner86102b82005-01-01 16:22:27 +00002027 if (ConstantIntegral *AndRHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00002028 uint64_t AndRHSMask = AndRHS->getZExtValue();
2029 uint64_t TypeMask = Op0->getType()->getIntegralTypeMask();
2030
2031 if (AndRHSMask == TypeMask) // and X, -1 == X
Chris Lattnere6794492002-08-12 21:17:25 +00002032 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00002033 else if (AndRHSMask == 0) // and X, 0 == 0
2034 return ReplaceInstUsesWith(I, AndRHS);
Chris Lattner38a1b002005-10-26 17:18:16 +00002035
2036 // and (and X, c1), c2 -> and (x, c1&c2). Handle this case here, before
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00002037 // calling ComputeMaskedNonZeroBits, to avoid inefficient cases where we
2038 // traipse through many levels of ands.
Chris Lattner38a1b002005-10-26 17:18:16 +00002039 {
Chris Lattner330628a2006-01-06 17:59:59 +00002040 Value *X = 0; ConstantInt *C1 = 0;
Chris Lattner38a1b002005-10-26 17:18:16 +00002041 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))))
2042 return BinaryOperator::createAnd(X, ConstantExpr::getAnd(C1, AndRHS));
2043 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002044
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00002045 // Figure out which of the input bits are not known to be zero, and which
2046 // bits are known to be zero.
Chris Lattner4534dd592006-02-09 07:38:58 +00002047 uint64_t KnownZeroBits, KnownOneBits;
2048 ComputeMaskedBits(Op0, TypeMask, KnownZeroBits, KnownOneBits);
Chris Lattner86102b82005-01-01 16:22:27 +00002049
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00002050 // If the mask is not masking out any bits (i.e. all of the zeros in the
2051 // mask are already known to be zero), there is no reason to do the and in
2052 // the first place.
2053 uint64_t NotAndRHS = AndRHSMask^TypeMask;
Chris Lattner4534dd592006-02-09 07:38:58 +00002054 if ((NotAndRHS & KnownZeroBits) == NotAndRHS)
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00002055 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00002056
Chris Lattner4534dd592006-02-09 07:38:58 +00002057 // If the AND'd bits are all known, turn this AND into a constant.
2058 if ((AndRHSMask & (KnownOneBits|KnownZeroBits)) == AndRHSMask) {
2059 Constant *NewRHS = ConstantUInt::get(Type::ULongTy,
2060 AndRHSMask & KnownOneBits);
2061 return ReplaceInstUsesWith(I, ConstantExpr::getCast(NewRHS, I.getType()));
2062 }
2063
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00002064 // If the AND mask contains bits that are known zero, remove them. A
2065 // special case is when there are no bits in common, in which case we
2066 // implicitly turn this into an AND X, 0, which is later simplified into 0.
Chris Lattner4534dd592006-02-09 07:38:58 +00002067 if ((AndRHSMask & ~KnownZeroBits) != AndRHSMask) {
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00002068 Constant *NewRHS =
Chris Lattner4534dd592006-02-09 07:38:58 +00002069 ConstantUInt::get(Type::ULongTy, AndRHSMask & ~KnownZeroBits);
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00002070 I.setOperand(1, ConstantExpr::getCast(NewRHS, I.getType()));
2071 return &I;
2072 }
Chris Lattner86102b82005-01-01 16:22:27 +00002073
Chris Lattnerba1cb382003-09-19 17:17:26 +00002074 // Optimize a variety of ((val OP C1) & C2) combinations...
2075 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
2076 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner86102b82005-01-01 16:22:27 +00002077 Value *Op0LHS = Op0I->getOperand(0);
2078 Value *Op0RHS = Op0I->getOperand(1);
2079 switch (Op0I->getOpcode()) {
2080 case Instruction::Xor:
2081 case Instruction::Or:
2082 // (X ^ V) & C2 --> (X & C2) iff (V & C2) == 0
2083 // (X | V) & C2 --> (X & C2) iff (V & C2) == 0
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00002084 if (MaskedValueIsZero(Op0LHS, AndRHSMask))
Misha Brukmanb1c93172005-04-21 23:48:37 +00002085 return BinaryOperator::createAnd(Op0RHS, AndRHS);
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00002086 if (MaskedValueIsZero(Op0RHS, AndRHSMask))
Misha Brukmanb1c93172005-04-21 23:48:37 +00002087 return BinaryOperator::createAnd(Op0LHS, AndRHS);
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00002088
2089 // If the mask is only needed on one incoming arm, push it up.
2090 if (Op0I->hasOneUse()) {
2091 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
2092 // Not masking anything out for the LHS, move to RHS.
2093 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
2094 Op0RHS->getName()+".masked");
2095 InsertNewInstBefore(NewRHS, I);
2096 return BinaryOperator::create(
2097 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002098 }
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002099 if (!isa<Constant>(Op0RHS) &&
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00002100 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
2101 // Not masking anything out for the RHS, move to LHS.
2102 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
2103 Op0LHS->getName()+".masked");
2104 InsertNewInstBefore(NewLHS, I);
2105 return BinaryOperator::create(
2106 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
2107 }
2108 }
2109
Chris Lattner86102b82005-01-01 16:22:27 +00002110 break;
2111 case Instruction::And:
2112 // (X & V) & C2 --> 0 iff (V & C2) == 0
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00002113 if (MaskedValueIsZero(Op0LHS, AndRHSMask) ||
2114 MaskedValueIsZero(Op0RHS, AndRHSMask))
Chris Lattner86102b82005-01-01 16:22:27 +00002115 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2116 break;
Chris Lattneraf517572005-09-18 04:24:45 +00002117 case Instruction::Add:
Chris Lattnerb4b25302005-09-18 07:22:02 +00002118 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
2119 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
2120 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
2121 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
2122 return BinaryOperator::createAnd(V, AndRHS);
2123 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
2124 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
Chris Lattneraf517572005-09-18 04:24:45 +00002125 break;
2126
2127 case Instruction::Sub:
Chris Lattnerb4b25302005-09-18 07:22:02 +00002128 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
2129 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
2130 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
2131 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
2132 return BinaryOperator::createAnd(V, AndRHS);
Chris Lattneraf517572005-09-18 04:24:45 +00002133 break;
Chris Lattner86102b82005-01-01 16:22:27 +00002134 }
2135
Chris Lattner16464b32003-07-23 19:25:52 +00002136 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner86102b82005-01-01 16:22:27 +00002137 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerba1cb382003-09-19 17:17:26 +00002138 return Res;
Chris Lattner86102b82005-01-01 16:22:27 +00002139 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
2140 const Type *SrcTy = CI->getOperand(0)->getType();
2141
Chris Lattner2c14cf72005-08-07 07:03:10 +00002142 // If this is an integer truncation or change from signed-to-unsigned, and
2143 // if the source is an and/or with immediate, transform it. This
2144 // frequently occurs for bitfield accesses.
2145 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
2146 if (SrcTy->getPrimitiveSizeInBits() >=
2147 I.getType()->getPrimitiveSizeInBits() &&
2148 CastOp->getNumOperands() == 2)
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00002149 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
Chris Lattner2c14cf72005-08-07 07:03:10 +00002150 if (CastOp->getOpcode() == Instruction::And) {
2151 // Change: and (cast (and X, C1) to T), C2
2152 // into : and (cast X to T), trunc(C1)&C2
2153 // This will folds the two ands together, which may allow other
2154 // simplifications.
2155 Instruction *NewCast =
2156 new CastInst(CastOp->getOperand(0), I.getType(),
2157 CastOp->getName()+".shrunk");
2158 NewCast = InsertNewInstBefore(NewCast, I);
2159
2160 Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
2161 C3 = ConstantExpr::getAnd(C3, AndRHS); // trunc(C1)&C2
2162 return BinaryOperator::createAnd(NewCast, C3);
2163 } else if (CastOp->getOpcode() == Instruction::Or) {
2164 // Change: and (cast (or X, C1) to T), C2
2165 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
2166 Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
2167 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
2168 return ReplaceInstUsesWith(I, AndRHS);
2169 }
2170 }
2171
2172
Chris Lattner86102b82005-01-01 16:22:27 +00002173 // If this is an integer sign or zero extension instruction.
2174 if (SrcTy->isIntegral() &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002175 SrcTy->getPrimitiveSizeInBits() <
2176 CI->getType()->getPrimitiveSizeInBits()) {
Chris Lattner86102b82005-01-01 16:22:27 +00002177
2178 if (SrcTy->isUnsigned()) {
2179 // See if this and is clearing out bits that are known to be zero
2180 // anyway (due to the zero extension).
2181 Constant *Mask = ConstantIntegral::getAllOnesValue(SrcTy);
2182 Mask = ConstantExpr::getZeroExtend(Mask, CI->getType());
2183 Constant *Result = ConstantExpr::getAnd(Mask, AndRHS);
2184 if (Result == Mask) // The "and" isn't doing anything, remove it.
2185 return ReplaceInstUsesWith(I, CI);
2186 if (Result != AndRHS) { // Reduce the and RHS constant.
2187 I.setOperand(1, Result);
2188 return &I;
2189 }
2190
2191 } else {
2192 if (CI->hasOneUse() && SrcTy->isInteger()) {
2193 // We can only do this if all of the sign bits brought in are masked
2194 // out. Compute this by first getting 0000011111, then inverting
2195 // it.
2196 Constant *Mask = ConstantIntegral::getAllOnesValue(SrcTy);
2197 Mask = ConstantExpr::getZeroExtend(Mask, CI->getType());
2198 Mask = ConstantExpr::getNot(Mask); // 1's in the new bits.
2199 if (ConstantExpr::getAnd(Mask, AndRHS)->isNullValue()) {
2200 // If the and is clearing all of the sign bits, change this to a
2201 // zero extension cast. To do this, cast the cast input to
2202 // unsigned, then to the requested size.
2203 Value *CastOp = CI->getOperand(0);
2204 Instruction *NC =
2205 new CastInst(CastOp, CastOp->getType()->getUnsignedVersion(),
2206 CI->getName()+".uns");
2207 NC = InsertNewInstBefore(NC, I);
2208 // Finally, insert a replacement for CI.
2209 NC = new CastInst(NC, CI->getType(), CI->getName());
2210 CI->setName("");
2211 NC = InsertNewInstBefore(NC, I);
2212 WorkList.push_back(CI); // Delete CI later.
2213 I.setOperand(0, NC);
2214 return &I; // The AND operand was modified.
2215 }
2216 }
2217 }
2218 }
Chris Lattner33217db2003-07-23 19:36:21 +00002219 }
Chris Lattner183b3362004-04-09 19:05:30 +00002220
2221 // Try to fold constant and into select arguments.
2222 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00002223 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002224 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002225 if (isa<PHINode>(Op0))
2226 if (Instruction *NV = FoldOpIntoPhi(I))
2227 return NV;
Chris Lattner49b47ae2003-07-23 17:57:01 +00002228 }
2229
Chris Lattnerbb74e222003-03-10 23:06:50 +00002230 Value *Op0NotVal = dyn_castNotVal(Op0);
2231 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002232
Chris Lattner023a4832004-06-18 06:07:51 +00002233 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
2234 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2235
Misha Brukman9c003d82004-07-30 12:50:08 +00002236 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerbb74e222003-03-10 23:06:50 +00002237 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002238 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
2239 I.getName()+".demorgan");
Chris Lattner49b47ae2003-07-23 17:57:01 +00002240 InsertNewInstBefore(Or, I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002241 return BinaryOperator::createNot(Or);
2242 }
2243
Chris Lattner623826c2004-09-28 21:48:02 +00002244 if (SetCondInst *RHS = dyn_cast<SetCondInst>(Op1)) {
2245 // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
Chris Lattner3ac7c262003-08-13 20:16:26 +00002246 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
2247 return R;
2248
Chris Lattner623826c2004-09-28 21:48:02 +00002249 Value *LHSVal, *RHSVal;
2250 ConstantInt *LHSCst, *RHSCst;
2251 Instruction::BinaryOps LHSCC, RHSCC;
2252 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
2253 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
2254 if (LHSVal == RHSVal && // Found (X setcc C1) & (X setcc C2)
2255 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
Misha Brukmanb1c93172005-04-21 23:48:37 +00002256 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
Chris Lattner623826c2004-09-28 21:48:02 +00002257 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
2258 // Ensure that the larger constant is on the RHS.
2259 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
2260 SetCondInst *LHS = cast<SetCondInst>(Op0);
2261 if (cast<ConstantBool>(Cmp)->getValue()) {
2262 std::swap(LHS, RHS);
2263 std::swap(LHSCst, RHSCst);
2264 std::swap(LHSCC, RHSCC);
2265 }
2266
2267 // At this point, we know we have have two setcc instructions
2268 // comparing a value against two constants and and'ing the result
2269 // together. Because of the above check, we know that we only have
2270 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
2271 // FoldSetCCLogical check above), that the two constants are not
2272 // equal.
2273 assert(LHSCst != RHSCst && "Compares not folded above?");
2274
2275 switch (LHSCC) {
2276 default: assert(0 && "Unknown integer condition code!");
2277 case Instruction::SetEQ:
2278 switch (RHSCC) {
2279 default: assert(0 && "Unknown integer condition code!");
2280 case Instruction::SetEQ: // (X == 13 & X == 15) -> false
2281 case Instruction::SetGT: // (X == 13 & X > 15) -> false
2282 return ReplaceInstUsesWith(I, ConstantBool::False);
2283 case Instruction::SetNE: // (X == 13 & X != 15) -> X == 13
2284 case Instruction::SetLT: // (X == 13 & X < 15) -> X == 13
2285 return ReplaceInstUsesWith(I, LHS);
2286 }
2287 case Instruction::SetNE:
2288 switch (RHSCC) {
2289 default: assert(0 && "Unknown integer condition code!");
2290 case Instruction::SetLT:
2291 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X < 14) -> X < 13
2292 return new SetCondInst(Instruction::SetLT, LHSVal, LHSCst);
2293 break; // (X != 13 & X < 15) -> no change
2294 case Instruction::SetEQ: // (X != 13 & X == 15) -> X == 15
2295 case Instruction::SetGT: // (X != 13 & X > 15) -> X > 15
2296 return ReplaceInstUsesWith(I, RHS);
2297 case Instruction::SetNE:
2298 if (LHSCst == SubOne(RHSCst)) {// (X != 13 & X != 14) -> X-13 >u 1
2299 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
2300 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
2301 LHSVal->getName()+".off");
2302 InsertNewInstBefore(Add, I);
2303 const Type *UnsType = Add->getType()->getUnsignedVersion();
2304 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
2305 AddCST = ConstantExpr::getSub(RHSCst, LHSCst);
2306 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2307 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
2308 }
2309 break; // (X != 13 & X != 15) -> no change
2310 }
2311 break;
2312 case Instruction::SetLT:
2313 switch (RHSCC) {
2314 default: assert(0 && "Unknown integer condition code!");
2315 case Instruction::SetEQ: // (X < 13 & X == 15) -> false
2316 case Instruction::SetGT: // (X < 13 & X > 15) -> false
2317 return ReplaceInstUsesWith(I, ConstantBool::False);
2318 case Instruction::SetNE: // (X < 13 & X != 15) -> X < 13
2319 case Instruction::SetLT: // (X < 13 & X < 15) -> X < 13
2320 return ReplaceInstUsesWith(I, LHS);
2321 }
2322 case Instruction::SetGT:
2323 switch (RHSCC) {
2324 default: assert(0 && "Unknown integer condition code!");
2325 case Instruction::SetEQ: // (X > 13 & X == 15) -> X > 13
2326 return ReplaceInstUsesWith(I, LHS);
2327 case Instruction::SetGT: // (X > 13 & X > 15) -> X > 15
2328 return ReplaceInstUsesWith(I, RHS);
2329 case Instruction::SetNE:
2330 if (RHSCst == AddOne(LHSCst)) // (X > 13 & X != 14) -> X > 14
2331 return new SetCondInst(Instruction::SetGT, LHSVal, RHSCst);
2332 break; // (X > 13 & X != 15) -> no change
Chris Lattner6862fbd2004-09-29 17:40:11 +00002333 case Instruction::SetLT: // (X > 13 & X < 15) -> (X-14) <u 1
2334 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, I);
Chris Lattner623826c2004-09-28 21:48:02 +00002335 }
2336 }
2337 }
2338 }
2339
Chris Lattner113f4f42002-06-25 16:13:24 +00002340 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002341}
2342
Chris Lattner113f4f42002-06-25 16:13:24 +00002343Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002344 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00002345 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002346
Chris Lattner81a7a232004-10-16 18:11:37 +00002347 if (isa<UndefValue>(Op1))
2348 return ReplaceInstUsesWith(I, // X | undef -> -1
2349 ConstantIntegral::getAllOnesValue(I.getType()));
2350
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002351 // or X, X = X or X, 0 == X
Chris Lattnere6794492002-08-12 21:17:25 +00002352 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
2353 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002354
2355 // or X, -1 == -1
Chris Lattner8f0d1562003-07-23 18:29:44 +00002356 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner86102b82005-01-01 16:22:27 +00002357 // If X is known to only contain bits that already exist in RHS, just
2358 // replace this instruction with RHS directly.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002359 if (MaskedValueIsZero(Op0,
2360 RHS->getZExtValue()^RHS->getType()->getIntegralTypeMask()))
Chris Lattner86102b82005-01-01 16:22:27 +00002361 return ReplaceInstUsesWith(I, RHS);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002362
Chris Lattner330628a2006-01-06 17:59:59 +00002363 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00002364 // (X & C1) | C2 --> (X | C2) & (C1|C2)
2365 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00002366 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0->getName());
2367 Op0->setName("");
Chris Lattnerd4252a72004-07-30 07:50:03 +00002368 InsertNewInstBefore(Or, I);
2369 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
2370 }
Chris Lattner8f0d1562003-07-23 18:29:44 +00002371
Chris Lattnerd4252a72004-07-30 07:50:03 +00002372 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
2373 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
2374 std::string Op0Name = Op0->getName(); Op0->setName("");
2375 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
2376 InsertNewInstBefore(Or, I);
2377 return BinaryOperator::createXor(Or,
2378 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
Chris Lattner8f0d1562003-07-23 18:29:44 +00002379 }
Chris Lattner183b3362004-04-09 19:05:30 +00002380
2381 // Try to fold constant and into select arguments.
2382 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00002383 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002384 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002385 if (isa<PHINode>(Op0))
2386 if (Instruction *NV = FoldOpIntoPhi(I))
2387 return NV;
Chris Lattner8f0d1562003-07-23 18:29:44 +00002388 }
2389
Chris Lattner330628a2006-01-06 17:59:59 +00002390 Value *A = 0, *B = 0;
2391 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattner4294cec2005-05-07 23:49:08 +00002392
2393 if (match(Op0, m_And(m_Value(A), m_Value(B))))
2394 if (A == Op1 || B == Op1) // (A & ?) | A --> A
2395 return ReplaceInstUsesWith(I, Op1);
2396 if (match(Op1, m_And(m_Value(A), m_Value(B))))
2397 if (A == Op0 || B == Op0) // A | (A & ?) --> A
2398 return ReplaceInstUsesWith(I, Op0);
2399
Chris Lattnerb62f5082005-05-09 04:58:36 +00002400 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
2401 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002402 MaskedValueIsZero(Op1, C1->getZExtValue())) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00002403 Instruction *NOr = BinaryOperator::createOr(A, Op1, Op0->getName());
2404 Op0->setName("");
2405 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
2406 }
2407
2408 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
2409 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002410 MaskedValueIsZero(Op0, C1->getZExtValue())) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00002411 Instruction *NOr = BinaryOperator::createOr(A, Op0, Op1->getName());
2412 Op0->setName("");
2413 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
2414 }
2415
Chris Lattner15212982005-09-18 03:42:07 +00002416 // (A & C1)|(B & C2)
Chris Lattnerd4252a72004-07-30 07:50:03 +00002417 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattner15212982005-09-18 03:42:07 +00002418 match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
2419
2420 if (A == B) // (A & C1)|(A & C2) == A & (C1|C2)
2421 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
2422
2423
Chris Lattner01f56c62005-09-18 06:02:59 +00002424 // If we have: ((V + N) & C1) | (V & C2)
2425 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
2426 // replace with V+N.
2427 if (C1 == ConstantExpr::getNot(C2)) {
Chris Lattner330628a2006-01-06 17:59:59 +00002428 Value *V1 = 0, *V2 = 0;
Chris Lattner01f56c62005-09-18 06:02:59 +00002429 if ((C2->getRawValue() & (C2->getRawValue()+1)) == 0 && // C2 == 0+1+
2430 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
2431 // Add commutes, try both ways.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002432 if (V1 == B && MaskedValueIsZero(V2, C2->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00002433 return ReplaceInstUsesWith(I, A);
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002434 if (V2 == B && MaskedValueIsZero(V1, C2->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00002435 return ReplaceInstUsesWith(I, A);
2436 }
2437 // Or commutes, try both ways.
2438 if ((C1->getRawValue() & (C1->getRawValue()+1)) == 0 &&
2439 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
2440 // Add commutes, try both ways.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002441 if (V1 == A && MaskedValueIsZero(V2, C1->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00002442 return ReplaceInstUsesWith(I, B);
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002443 if (V2 == A && MaskedValueIsZero(V1, C1->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00002444 return ReplaceInstUsesWith(I, B);
Chris Lattner15212982005-09-18 03:42:07 +00002445 }
2446 }
2447 }
Chris Lattner812aab72003-08-12 19:11:07 +00002448
Chris Lattnerd4252a72004-07-30 07:50:03 +00002449 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
2450 if (A == Op1) // ~A | A == -1
Misha Brukmanb1c93172005-04-21 23:48:37 +00002451 return ReplaceInstUsesWith(I,
Chris Lattnerd4252a72004-07-30 07:50:03 +00002452 ConstantIntegral::getAllOnesValue(I.getType()));
2453 } else {
2454 A = 0;
2455 }
Chris Lattner4294cec2005-05-07 23:49:08 +00002456 // Note, A is still live here!
Chris Lattnerd4252a72004-07-30 07:50:03 +00002457 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
2458 if (Op0 == B)
Misha Brukmanb1c93172005-04-21 23:48:37 +00002459 return ReplaceInstUsesWith(I,
Chris Lattnerd4252a72004-07-30 07:50:03 +00002460 ConstantIntegral::getAllOnesValue(I.getType()));
Chris Lattner3e327a42003-03-10 23:13:59 +00002461
Misha Brukman9c003d82004-07-30 12:50:08 +00002462 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattnerd4252a72004-07-30 07:50:03 +00002463 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
2464 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
2465 I.getName()+".demorgan"), I);
2466 return BinaryOperator::createNot(And);
2467 }
Chris Lattner3e327a42003-03-10 23:13:59 +00002468 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00002469
Chris Lattner3ac7c262003-08-13 20:16:26 +00002470 // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002471 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1))) {
Chris Lattner3ac7c262003-08-13 20:16:26 +00002472 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
2473 return R;
2474
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002475 Value *LHSVal, *RHSVal;
2476 ConstantInt *LHSCst, *RHSCst;
2477 Instruction::BinaryOps LHSCC, RHSCC;
2478 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
2479 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
2480 if (LHSVal == RHSVal && // Found (X setcc C1) | (X setcc C2)
2481 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
Misha Brukmanb1c93172005-04-21 23:48:37 +00002482 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002483 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
2484 // Ensure that the larger constant is on the RHS.
2485 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
2486 SetCondInst *LHS = cast<SetCondInst>(Op0);
2487 if (cast<ConstantBool>(Cmp)->getValue()) {
2488 std::swap(LHS, RHS);
2489 std::swap(LHSCst, RHSCst);
2490 std::swap(LHSCC, RHSCC);
2491 }
2492
2493 // At this point, we know we have have two setcc instructions
2494 // comparing a value against two constants and or'ing the result
2495 // together. Because of the above check, we know that we only have
2496 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
2497 // FoldSetCCLogical check above), that the two constants are not
2498 // equal.
2499 assert(LHSCst != RHSCst && "Compares not folded above?");
2500
2501 switch (LHSCC) {
2502 default: assert(0 && "Unknown integer condition code!");
2503 case Instruction::SetEQ:
2504 switch (RHSCC) {
2505 default: assert(0 && "Unknown integer condition code!");
2506 case Instruction::SetEQ:
2507 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
2508 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
2509 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
2510 LHSVal->getName()+".off");
2511 InsertNewInstBefore(Add, I);
2512 const Type *UnsType = Add->getType()->getUnsignedVersion();
2513 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
2514 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
2515 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2516 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
2517 }
2518 break; // (X == 13 | X == 15) -> no change
2519
Chris Lattner5c219462005-04-19 06:04:18 +00002520 case Instruction::SetGT: // (X == 13 | X > 14) -> no change
2521 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002522 case Instruction::SetNE: // (X == 13 | X != 15) -> X != 15
2523 case Instruction::SetLT: // (X == 13 | X < 15) -> X < 15
2524 return ReplaceInstUsesWith(I, RHS);
2525 }
2526 break;
2527 case Instruction::SetNE:
2528 switch (RHSCC) {
2529 default: assert(0 && "Unknown integer condition code!");
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002530 case Instruction::SetEQ: // (X != 13 | X == 15) -> X != 13
2531 case Instruction::SetGT: // (X != 13 | X > 15) -> X != 13
2532 return ReplaceInstUsesWith(I, LHS);
2533 case Instruction::SetNE: // (X != 13 | X != 15) -> true
Chris Lattner2ceb6ee2005-06-17 03:59:17 +00002534 case Instruction::SetLT: // (X != 13 | X < 15) -> true
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002535 return ReplaceInstUsesWith(I, ConstantBool::True);
2536 }
2537 break;
2538 case Instruction::SetLT:
2539 switch (RHSCC) {
2540 default: assert(0 && "Unknown integer condition code!");
2541 case Instruction::SetEQ: // (X < 13 | X == 14) -> no change
2542 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00002543 case Instruction::SetGT: // (X < 13 | X > 15) -> (X-13) > 2
2544 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, I);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002545 case Instruction::SetNE: // (X < 13 | X != 15) -> X != 15
2546 case Instruction::SetLT: // (X < 13 | X < 15) -> X < 15
2547 return ReplaceInstUsesWith(I, RHS);
2548 }
2549 break;
2550 case Instruction::SetGT:
2551 switch (RHSCC) {
2552 default: assert(0 && "Unknown integer condition code!");
2553 case Instruction::SetEQ: // (X > 13 | X == 15) -> X > 13
2554 case Instruction::SetGT: // (X > 13 | X > 15) -> X > 13
2555 return ReplaceInstUsesWith(I, LHS);
2556 case Instruction::SetNE: // (X > 13 | X != 15) -> true
2557 case Instruction::SetLT: // (X > 13 | X < 15) -> true
2558 return ReplaceInstUsesWith(I, ConstantBool::True);
2559 }
2560 }
2561 }
2562 }
Chris Lattner15212982005-09-18 03:42:07 +00002563
Chris Lattner113f4f42002-06-25 16:13:24 +00002564 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002565}
2566
Chris Lattnerc2076352004-02-16 01:20:27 +00002567// XorSelf - Implements: X ^ X --> 0
2568struct XorSelf {
2569 Value *RHS;
2570 XorSelf(Value *rhs) : RHS(rhs) {}
2571 bool shouldApply(Value *LHS) const { return LHS == RHS; }
2572 Instruction *apply(BinaryOperator &Xor) const {
2573 return &Xor;
2574 }
2575};
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002576
2577
Chris Lattner113f4f42002-06-25 16:13:24 +00002578Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002579 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00002580 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002581
Chris Lattner81a7a232004-10-16 18:11:37 +00002582 if (isa<UndefValue>(Op1))
2583 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
2584
Chris Lattnerc2076352004-02-16 01:20:27 +00002585 // xor X, X = 0, even if X is nested in a sequence of Xor's.
2586 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
2587 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattnere6794492002-08-12 21:17:25 +00002588 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc2076352004-02-16 01:20:27 +00002589 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002590
Chris Lattner97638592003-07-23 21:37:07 +00002591 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002592 // xor X, 0 == X
Chris Lattner97638592003-07-23 21:37:07 +00002593 if (RHS->isNullValue())
Chris Lattnere6794492002-08-12 21:17:25 +00002594 return ReplaceInstUsesWith(I, Op0);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002595
Chris Lattner97638592003-07-23 21:37:07 +00002596 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerb8d6e402002-08-20 18:24:26 +00002597 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
Chris Lattner97638592003-07-23 21:37:07 +00002598 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002599 if (RHS == ConstantBool::True && SCI->hasOneUse())
Chris Lattnerb8d6e402002-08-20 18:24:26 +00002600 return new SetCondInst(SCI->getInverseCondition(),
2601 SCI->getOperand(0), SCI->getOperand(1));
Chris Lattnere5806662003-11-04 23:50:51 +00002602
Chris Lattner8f2f5982003-11-05 01:06:05 +00002603 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002604 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
2605 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002606 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
2607 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002608 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002609 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002610 }
Chris Lattner023a4832004-06-18 06:07:51 +00002611
2612 // ~(~X & Y) --> (X | ~Y)
2613 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
2614 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
2615 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
2616 Instruction *NotY =
Misha Brukmanb1c93172005-04-21 23:48:37 +00002617 BinaryOperator::createNot(Op0I->getOperand(1),
Chris Lattner023a4832004-06-18 06:07:51 +00002618 Op0I->getOperand(1)->getName()+".not");
2619 InsertNewInstBefore(NotY, I);
2620 return BinaryOperator::createOr(Op0NotVal, NotY);
2621 }
2622 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002623
Chris Lattner97638592003-07-23 21:37:07 +00002624 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattnere5806662003-11-04 23:50:51 +00002625 switch (Op0I->getOpcode()) {
2626 case Instruction::Add:
Chris Lattner0f68fa62003-11-04 23:37:10 +00002627 // ~(X-c) --> (-c-1)-X
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002628 if (RHS->isAllOnesValue()) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002629 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
2630 return BinaryOperator::createSub(
2631 ConstantExpr::getSub(NegOp0CI,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002632 ConstantInt::get(I.getType(), 1)),
Chris Lattner0f68fa62003-11-04 23:37:10 +00002633 Op0I->getOperand(0));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002634 }
Chris Lattnere5806662003-11-04 23:50:51 +00002635 break;
2636 case Instruction::And:
Chris Lattner97638592003-07-23 21:37:07 +00002637 // (X & C1) ^ C2 --> (X & C1) | C2 iff (C1&C2) == 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002638 if (ConstantExpr::getAnd(RHS, Op0CI)->isNullValue())
2639 return BinaryOperator::createOr(Op0, RHS);
Chris Lattnere5806662003-11-04 23:50:51 +00002640 break;
2641 case Instruction::Or:
Chris Lattner97638592003-07-23 21:37:07 +00002642 // (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002643 if (ConstantExpr::getAnd(RHS, Op0CI) == RHS)
Chris Lattnerc8e7e292004-06-10 02:12:35 +00002644 return BinaryOperator::createAnd(Op0, ConstantExpr::getNot(RHS));
Chris Lattnere5806662003-11-04 23:50:51 +00002645 break;
2646 default: break;
Chris Lattner97638592003-07-23 21:37:07 +00002647 }
Chris Lattnerb8d6e402002-08-20 18:24:26 +00002648 }
Chris Lattner183b3362004-04-09 19:05:30 +00002649
2650 // Try to fold constant and into select arguments.
2651 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00002652 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002653 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002654 if (isa<PHINode>(Op0))
2655 if (Instruction *NV = FoldOpIntoPhi(I))
2656 return NV;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002657 }
2658
Chris Lattnerbb74e222003-03-10 23:06:50 +00002659 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00002660 if (X == Op1)
2661 return ReplaceInstUsesWith(I,
2662 ConstantIntegral::getAllOnesValue(I.getType()));
2663
Chris Lattnerbb74e222003-03-10 23:06:50 +00002664 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00002665 if (X == Op0)
2666 return ReplaceInstUsesWith(I,
2667 ConstantIntegral::getAllOnesValue(I.getType()));
2668
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002669 if (Instruction *Op1I = dyn_cast<Instruction>(Op1))
Chris Lattnerb36d9082004-02-16 03:54:20 +00002670 if (Op1I->getOpcode() == Instruction::Or) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002671 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
2672 cast<BinaryOperator>(Op1I)->swapOperands();
2673 I.swapOperands();
2674 std::swap(Op0, Op1);
2675 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
2676 I.swapOperands();
2677 std::swap(Op0, Op1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002678 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00002679 } else if (Op1I->getOpcode() == Instruction::Xor) {
2680 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
2681 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
2682 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
2683 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
2684 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002685
2686 if (Instruction *Op0I = dyn_cast<Instruction>(Op0))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002687 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002688 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
2689 cast<BinaryOperator>(Op0I)->swapOperands();
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002690 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattner396dbfe2004-06-09 05:08:07 +00002691 Value *NotB = InsertNewInstBefore(BinaryOperator::createNot(Op1,
2692 Op1->getName()+".not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002693 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002694 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00002695 } else if (Op0I->getOpcode() == Instruction::Xor) {
2696 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
2697 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2698 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
2699 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002700 }
2701
Chris Lattner7aa2d472004-08-01 19:42:59 +00002702 // (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattner330628a2006-01-06 17:59:59 +00002703 ConstantInt *C1 = 0, *C2 = 0;
2704 if (match(Op0, m_And(m_Value(), m_ConstantInt(C1))) &&
2705 match(Op1, m_And(m_Value(), m_ConstantInt(C2))) &&
Chris Lattner7aa2d472004-08-01 19:42:59 +00002706 ConstantExpr::getAnd(C1, C2)->isNullValue())
Chris Lattnerd4252a72004-07-30 07:50:03 +00002707 return BinaryOperator::createOr(Op0, Op1);
Chris Lattner7fb29e12003-03-11 00:12:48 +00002708
Chris Lattner3ac7c262003-08-13 20:16:26 +00002709 // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
2710 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
2711 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
2712 return R;
2713
Chris Lattner113f4f42002-06-25 16:13:24 +00002714 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002715}
2716
Chris Lattner6862fbd2004-09-29 17:40:11 +00002717/// MulWithOverflow - Compute Result = In1*In2, returning true if the result
2718/// overflowed for this type.
2719static bool MulWithOverflow(ConstantInt *&Result, ConstantInt *In1,
2720 ConstantInt *In2) {
2721 Result = cast<ConstantInt>(ConstantExpr::getMul(In1, In2));
2722 return !In2->isNullValue() && ConstantExpr::getDiv(Result, In2) != In1;
2723}
2724
2725static bool isPositive(ConstantInt *C) {
2726 return cast<ConstantSInt>(C)->getValue() >= 0;
2727}
2728
2729/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
2730/// overflowed for this type.
2731static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
2732 ConstantInt *In2) {
2733 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
2734
2735 if (In1->getType()->isUnsigned())
2736 return cast<ConstantUInt>(Result)->getValue() <
2737 cast<ConstantUInt>(In1)->getValue();
2738 if (isPositive(In1) != isPositive(In2))
2739 return false;
2740 if (isPositive(In1))
2741 return cast<ConstantSInt>(Result)->getValue() <
2742 cast<ConstantSInt>(In1)->getValue();
2743 return cast<ConstantSInt>(Result)->getValue() >
2744 cast<ConstantSInt>(In1)->getValue();
2745}
2746
Chris Lattner0798af32005-01-13 20:14:25 +00002747/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
2748/// code necessary to compute the offset from the base pointer (without adding
2749/// in the base pointer). Return the result as a signed integer of intptr size.
2750static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
2751 TargetData &TD = IC.getTargetData();
2752 gep_type_iterator GTI = gep_type_begin(GEP);
2753 const Type *UIntPtrTy = TD.getIntPtrType();
2754 const Type *SIntPtrTy = UIntPtrTy->getSignedVersion();
2755 Value *Result = Constant::getNullValue(SIntPtrTy);
2756
2757 // Build a mask for high order bits.
Chris Lattner77defba2006-02-07 07:00:41 +00002758 uint64_t PtrSizeMask = ~0ULL >> (64-TD.getPointerSize()*8);
Chris Lattner0798af32005-01-13 20:14:25 +00002759
Chris Lattner0798af32005-01-13 20:14:25 +00002760 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
2761 Value *Op = GEP->getOperand(i);
Chris Lattnerd35d2102005-01-13 23:26:48 +00002762 uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattner0798af32005-01-13 20:14:25 +00002763 Constant *Scale = ConstantExpr::getCast(ConstantUInt::get(UIntPtrTy, Size),
2764 SIntPtrTy);
2765 if (Constant *OpC = dyn_cast<Constant>(Op)) {
2766 if (!OpC->isNullValue()) {
Chris Lattner4cb9fa32005-01-13 20:40:58 +00002767 OpC = ConstantExpr::getCast(OpC, SIntPtrTy);
Chris Lattner0798af32005-01-13 20:14:25 +00002768 Scale = ConstantExpr::getMul(OpC, Scale);
2769 if (Constant *RC = dyn_cast<Constant>(Result))
2770 Result = ConstantExpr::getAdd(RC, Scale);
2771 else {
2772 // Emit an add instruction.
2773 Result = IC.InsertNewInstBefore(
2774 BinaryOperator::createAdd(Result, Scale,
2775 GEP->getName()+".offs"), I);
2776 }
2777 }
2778 } else {
Chris Lattner7aa41cf2005-01-14 17:17:59 +00002779 // Convert to correct type.
2780 Op = IC.InsertNewInstBefore(new CastInst(Op, SIntPtrTy,
2781 Op->getName()+".c"), I);
2782 if (Size != 1)
Chris Lattner4cb9fa32005-01-13 20:40:58 +00002783 // We'll let instcombine(mul) convert this to a shl if possible.
2784 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
2785 GEP->getName()+".idx"), I);
Chris Lattner0798af32005-01-13 20:14:25 +00002786
2787 // Emit an add instruction.
Chris Lattner4cb9fa32005-01-13 20:40:58 +00002788 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
Chris Lattner0798af32005-01-13 20:14:25 +00002789 GEP->getName()+".offs"), I);
2790 }
2791 }
2792 return Result;
2793}
2794
2795/// FoldGEPSetCC - Fold comparisons between a GEP instruction and something
2796/// else. At this point we know that the GEP is on the LHS of the comparison.
2797Instruction *InstCombiner::FoldGEPSetCC(User *GEPLHS, Value *RHS,
2798 Instruction::BinaryOps Cond,
2799 Instruction &I) {
2800 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattner81e84172005-01-13 22:25:21 +00002801
2802 if (CastInst *CI = dyn_cast<CastInst>(RHS))
2803 if (isa<PointerType>(CI->getOperand(0)->getType()))
2804 RHS = CI->getOperand(0);
2805
Chris Lattner0798af32005-01-13 20:14:25 +00002806 Value *PtrBase = GEPLHS->getOperand(0);
2807 if (PtrBase == RHS) {
2808 // As an optimization, we don't actually have to compute the actual value of
2809 // OFFSET if this is a seteq or setne comparison, just return whether each
2810 // index is zero or not.
Chris Lattner81e84172005-01-13 22:25:21 +00002811 if (Cond == Instruction::SetEQ || Cond == Instruction::SetNE) {
2812 Instruction *InVal = 0;
Chris Lattnercd517ff2005-01-28 19:32:01 +00002813 gep_type_iterator GTI = gep_type_begin(GEPLHS);
2814 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattner81e84172005-01-13 22:25:21 +00002815 bool EmitIt = true;
2816 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
2817 if (isa<UndefValue>(C)) // undef index -> undef.
2818 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2819 if (C->isNullValue())
2820 EmitIt = false;
Chris Lattnercd517ff2005-01-28 19:32:01 +00002821 else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
2822 EmitIt = false; // This is indexing into a zero sized array?
Misha Brukmanb1c93172005-04-21 23:48:37 +00002823 } else if (isa<ConstantInt>(C))
Chris Lattner81e84172005-01-13 22:25:21 +00002824 return ReplaceInstUsesWith(I, // No comparison is needed here.
2825 ConstantBool::get(Cond == Instruction::SetNE));
2826 }
2827
2828 if (EmitIt) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00002829 Instruction *Comp =
Chris Lattner81e84172005-01-13 22:25:21 +00002830 new SetCondInst(Cond, GEPLHS->getOperand(i),
2831 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
2832 if (InVal == 0)
2833 InVal = Comp;
2834 else {
2835 InVal = InsertNewInstBefore(InVal, I);
2836 InsertNewInstBefore(Comp, I);
2837 if (Cond == Instruction::SetNE) // True if any are unequal
2838 InVal = BinaryOperator::createOr(InVal, Comp);
2839 else // True if all are equal
2840 InVal = BinaryOperator::createAnd(InVal, Comp);
2841 }
2842 }
2843 }
2844
2845 if (InVal)
2846 return InVal;
2847 else
2848 ReplaceInstUsesWith(I, // No comparison is needed here, all indexes = 0
2849 ConstantBool::get(Cond == Instruction::SetEQ));
2850 }
Chris Lattner0798af32005-01-13 20:14:25 +00002851
2852 // Only lower this if the setcc is the only user of the GEP or if we expect
2853 // the result to fold to a constant!
2854 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
2855 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
2856 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
2857 return new SetCondInst(Cond, Offset,
2858 Constant::getNullValue(Offset->getType()));
2859 }
2860 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera21bf8d2005-04-25 20:17:30 +00002861 // If the base pointers are different, but the indices are the same, just
2862 // compare the base pointer.
2863 if (PtrBase != GEPRHS->getOperand(0)) {
2864 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00002865 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattnerbd43b9d2005-04-26 14:40:41 +00002866 GEPRHS->getOperand(0)->getType();
Chris Lattnera21bf8d2005-04-25 20:17:30 +00002867 if (IndicesTheSame)
2868 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
2869 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
2870 IndicesTheSame = false;
2871 break;
2872 }
2873
2874 // If all indices are the same, just compare the base pointers.
2875 if (IndicesTheSame)
2876 return new SetCondInst(Cond, GEPLHS->getOperand(0),
2877 GEPRHS->getOperand(0));
2878
2879 // Otherwise, the base pointers are different and the indices are
2880 // different, bail out.
Chris Lattner0798af32005-01-13 20:14:25 +00002881 return 0;
Chris Lattnera21bf8d2005-04-25 20:17:30 +00002882 }
Chris Lattner0798af32005-01-13 20:14:25 +00002883
Chris Lattner81e84172005-01-13 22:25:21 +00002884 // If one of the GEPs has all zero indices, recurse.
2885 bool AllZeros = true;
2886 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
2887 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
2888 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
2889 AllZeros = false;
2890 break;
2891 }
2892 if (AllZeros)
2893 return FoldGEPSetCC(GEPRHS, GEPLHS->getOperand(0),
2894 SetCondInst::getSwappedCondition(Cond), I);
Chris Lattner4fa89822005-01-14 00:20:05 +00002895
2896 // If the other GEP has all zero indices, recurse.
Chris Lattner81e84172005-01-13 22:25:21 +00002897 AllZeros = true;
2898 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
2899 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
2900 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
2901 AllZeros = false;
2902 break;
2903 }
2904 if (AllZeros)
2905 return FoldGEPSetCC(GEPLHS, GEPRHS->getOperand(0), Cond, I);
2906
Chris Lattner4fa89822005-01-14 00:20:05 +00002907 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
2908 // If the GEPs only differ by one index, compare it.
2909 unsigned NumDifferences = 0; // Keep track of # differences.
2910 unsigned DiffOperand = 0; // The operand that differs.
2911 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
2912 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002913 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
2914 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00002915 // Irreconcilable differences.
Chris Lattner4fa89822005-01-14 00:20:05 +00002916 NumDifferences = 2;
2917 break;
2918 } else {
2919 if (NumDifferences++) break;
2920 DiffOperand = i;
2921 }
2922 }
2923
2924 if (NumDifferences == 0) // SAME GEP?
2925 return ReplaceInstUsesWith(I, // No comparison is needed here.
2926 ConstantBool::get(Cond == Instruction::SetEQ));
2927 else if (NumDifferences == 1) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00002928 Value *LHSV = GEPLHS->getOperand(DiffOperand);
2929 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Chris Lattner247aef82005-07-18 23:07:33 +00002930
2931 // Convert the operands to signed values to make sure to perform a
2932 // signed comparison.
2933 const Type *NewTy = LHSV->getType()->getSignedVersion();
2934 if (LHSV->getType() != NewTy)
2935 LHSV = InsertNewInstBefore(new CastInst(LHSV, NewTy,
2936 LHSV->getName()), I);
2937 if (RHSV->getType() != NewTy)
2938 RHSV = InsertNewInstBefore(new CastInst(RHSV, NewTy,
2939 RHSV->getName()), I);
2940 return new SetCondInst(Cond, LHSV, RHSV);
Chris Lattner4fa89822005-01-14 00:20:05 +00002941 }
2942 }
2943
Chris Lattner0798af32005-01-13 20:14:25 +00002944 // Only lower this if the setcc is the only user of the GEP or if we expect
2945 // the result to fold to a constant!
2946 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
2947 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
2948 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
2949 Value *L = EmitGEPOffset(GEPLHS, I, *this);
2950 Value *R = EmitGEPOffset(GEPRHS, I, *this);
2951 return new SetCondInst(Cond, L, R);
2952 }
2953 }
2954 return 0;
2955}
2956
2957
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002958Instruction *InstCombiner::visitSetCondInst(SetCondInst &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002959 bool Changed = SimplifyCommutative(I);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002960 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2961 const Type *Ty = Op0->getType();
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002962
2963 // setcc X, X
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002964 if (Op0 == Op1)
2965 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
Chris Lattner1fc23f32002-05-09 20:11:54 +00002966
Chris Lattner81a7a232004-10-16 18:11:37 +00002967 if (isa<UndefValue>(Op1)) // X setcc undef -> undef
2968 return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
2969
Chris Lattner15ff1e12004-11-14 07:33:16 +00002970 // setcc <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
2971 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanb1c93172005-04-21 23:48:37 +00002972 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
2973 isa<ConstantPointerNull>(Op0)) &&
2974 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner15ff1e12004-11-14 07:33:16 +00002975 isa<ConstantPointerNull>(Op1)))
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002976 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
2977
2978 // setcc's with boolean values can always be turned into bitwise operations
2979 if (Ty == Type::BoolTy) {
Chris Lattner4456da62004-08-11 00:50:51 +00002980 switch (I.getOpcode()) {
2981 default: assert(0 && "Invalid setcc instruction!");
2982 case Instruction::SetEQ: { // seteq bool %A, %B -> ~(A^B)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002983 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002984 InsertNewInstBefore(Xor, I);
Chris Lattner16930792003-11-03 04:25:02 +00002985 return BinaryOperator::createNot(Xor);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002986 }
Chris Lattner4456da62004-08-11 00:50:51 +00002987 case Instruction::SetNE:
2988 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002989
Chris Lattner4456da62004-08-11 00:50:51 +00002990 case Instruction::SetGT:
2991 std::swap(Op0, Op1); // Change setgt -> setlt
2992 // FALL THROUGH
2993 case Instruction::SetLT: { // setlt bool A, B -> ~X & Y
2994 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
2995 InsertNewInstBefore(Not, I);
2996 return BinaryOperator::createAnd(Not, Op1);
2997 }
2998 case Instruction::SetGE:
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002999 std::swap(Op0, Op1); // Change setge -> setle
Chris Lattner4456da62004-08-11 00:50:51 +00003000 // FALL THROUGH
3001 case Instruction::SetLE: { // setle bool %A, %B -> ~A | B
3002 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
3003 InsertNewInstBefore(Not, I);
3004 return BinaryOperator::createOr(Not, Op1);
3005 }
3006 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003007 }
3008
Chris Lattner2dd01742004-06-09 04:24:29 +00003009 // See if we are doing a comparison between a constant and an instruction that
3010 // can be folded into the comparison.
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003011 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00003012 // Check to see if we are comparing against the minimum or maximum value...
3013 if (CI->isMinValue()) {
3014 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
3015 return ReplaceInstUsesWith(I, ConstantBool::False);
3016 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
3017 return ReplaceInstUsesWith(I, ConstantBool::True);
3018 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
3019 return BinaryOperator::createSetEQ(Op0, Op1);
3020 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
3021 return BinaryOperator::createSetNE(Op0, Op1);
3022
3023 } else if (CI->isMaxValue()) {
3024 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
3025 return ReplaceInstUsesWith(I, ConstantBool::False);
3026 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
3027 return ReplaceInstUsesWith(I, ConstantBool::True);
3028 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
3029 return BinaryOperator::createSetEQ(Op0, Op1);
3030 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
3031 return BinaryOperator::createSetNE(Op0, Op1);
3032
3033 // Comparing against a value really close to min or max?
3034 } else if (isMinValuePlusOne(CI)) {
3035 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
3036 return BinaryOperator::createSetEQ(Op0, SubOne(CI));
3037 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
3038 return BinaryOperator::createSetNE(Op0, SubOne(CI));
3039
3040 } else if (isMaxValueMinusOne(CI)) {
3041 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
3042 return BinaryOperator::createSetEQ(Op0, AddOne(CI));
3043 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
3044 return BinaryOperator::createSetNE(Op0, AddOne(CI));
3045 }
3046
3047 // If we still have a setle or setge instruction, turn it into the
3048 // appropriate setlt or setgt instruction. Since the border cases have
3049 // already been handled above, this requires little checking.
3050 //
3051 if (I.getOpcode() == Instruction::SetLE)
3052 return BinaryOperator::createSetLT(Op0, AddOne(CI));
3053 if (I.getOpcode() == Instruction::SetGE)
3054 return BinaryOperator::createSetGT(Op0, SubOne(CI));
3055
Chris Lattnere1e10e12004-05-25 06:32:08 +00003056 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003057 switch (LHSI->getOpcode()) {
3058 case Instruction::And:
3059 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
3060 LHSI->getOperand(0)->hasOneUse()) {
3061 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
3062 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
3063 // happens a LOT in code produced by the C front-end, for bitfield
3064 // access.
3065 ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
3066 ConstantUInt *ShAmt;
3067 ShAmt = Shift ? dyn_cast<ConstantUInt>(Shift->getOperand(1)) : 0;
3068 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
3069 const Type *Ty = LHSI->getType();
Misha Brukmanb1c93172005-04-21 23:48:37 +00003070
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003071 // We can fold this as long as we can't shift unknown bits
3072 // into the mask. This can only happen with signed shift
3073 // rights, as they sign-extend.
3074 if (ShAmt) {
3075 bool CanFold = Shift->getOpcode() != Instruction::Shr ||
Chris Lattner6afc02f2004-09-28 17:54:07 +00003076 Shift->getType()->isUnsigned();
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003077 if (!CanFold) {
3078 // To test for the bad case of the signed shr, see if any
3079 // of the bits shifted in could be tested after the mask.
Chris Lattnerc53cb9d2005-06-17 01:29:28 +00003080 int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getValue();
3081 if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
3082
3083 Constant *OShAmt = ConstantUInt::get(Type::UByteTy, ShAmtVal);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003084 Constant *ShVal =
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003085 ConstantExpr::getShl(ConstantInt::getAllOnesValue(Ty), OShAmt);
3086 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
3087 CanFold = true;
3088 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003089
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003090 if (CanFold) {
Chris Lattner6afc02f2004-09-28 17:54:07 +00003091 Constant *NewCst;
3092 if (Shift->getOpcode() == Instruction::Shl)
3093 NewCst = ConstantExpr::getUShr(CI, ShAmt);
3094 else
3095 NewCst = ConstantExpr::getShl(CI, ShAmt);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003096
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003097 // Check to see if we are shifting out any of the bits being
3098 // compared.
3099 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
3100 // If we shifted bits out, the fold is not going to work out.
3101 // As a special case, check to see if this means that the
3102 // result is always true or false now.
3103 if (I.getOpcode() == Instruction::SetEQ)
3104 return ReplaceInstUsesWith(I, ConstantBool::False);
3105 if (I.getOpcode() == Instruction::SetNE)
3106 return ReplaceInstUsesWith(I, ConstantBool::True);
3107 } else {
3108 I.setOperand(1, NewCst);
Chris Lattner6afc02f2004-09-28 17:54:07 +00003109 Constant *NewAndCST;
3110 if (Shift->getOpcode() == Instruction::Shl)
3111 NewAndCST = ConstantExpr::getUShr(AndCST, ShAmt);
3112 else
3113 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
3114 LHSI->setOperand(1, NewAndCST);
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003115 LHSI->setOperand(0, Shift->getOperand(0));
3116 WorkList.push_back(Shift); // Shift is dead.
3117 AddUsesToWorkList(I);
3118 return &I;
Chris Lattner1638de42004-07-21 19:50:44 +00003119 }
3120 }
Chris Lattner35167c32004-06-09 07:59:58 +00003121 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003122 }
3123 break;
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003124
Chris Lattner272d5ca2004-09-28 18:22:15 +00003125 case Instruction::Shl: // (setcc (shl X, ShAmt), CI)
3126 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
3127 switch (I.getOpcode()) {
3128 default: break;
3129 case Instruction::SetEQ:
3130 case Instruction::SetNE: {
Chris Lattner19b57f52005-06-15 20:53:31 +00003131 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
3132
3133 // Check that the shift amount is in range. If not, don't perform
3134 // undefined shifts. When the shift is visited it will be
3135 // simplified.
3136 if (ShAmt->getValue() >= TypeBits)
3137 break;
3138
Chris Lattner272d5ca2004-09-28 18:22:15 +00003139 // If we are comparing against bits always shifted out, the
3140 // comparison cannot succeed.
Misha Brukmanb1c93172005-04-21 23:48:37 +00003141 Constant *Comp =
Chris Lattner272d5ca2004-09-28 18:22:15 +00003142 ConstantExpr::getShl(ConstantExpr::getShr(CI, ShAmt), ShAmt);
3143 if (Comp != CI) {// Comparing against a bit that we know is zero.
3144 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
3145 Constant *Cst = ConstantBool::get(IsSetNE);
3146 return ReplaceInstUsesWith(I, Cst);
3147 }
3148
3149 if (LHSI->hasOneUse()) {
3150 // Otherwise strength reduce the shift into an and.
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00003151 unsigned ShAmtVal = (unsigned)ShAmt->getValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00003152 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
3153
3154 Constant *Mask;
3155 if (CI->getType()->isUnsigned()) {
3156 Mask = ConstantUInt::get(CI->getType(), Val);
3157 } else if (ShAmtVal != 0) {
3158 Mask = ConstantSInt::get(CI->getType(), Val);
3159 } else {
3160 Mask = ConstantInt::getAllOnesValue(CI->getType());
3161 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003162
Chris Lattner272d5ca2004-09-28 18:22:15 +00003163 Instruction *AndI =
3164 BinaryOperator::createAnd(LHSI->getOperand(0),
3165 Mask, LHSI->getName()+".mask");
3166 Value *And = InsertNewInstBefore(AndI, I);
3167 return new SetCondInst(I.getOpcode(), And,
3168 ConstantExpr::getUShr(CI, ShAmt));
3169 }
3170 }
3171 }
3172 }
3173 break;
3174
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003175 case Instruction::Shr: // (setcc (shr X, ShAmt), CI)
Chris Lattner1023b872004-09-27 16:18:50 +00003176 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
Chris Lattner1023b872004-09-27 16:18:50 +00003177 switch (I.getOpcode()) {
3178 default: break;
3179 case Instruction::SetEQ:
3180 case Instruction::SetNE: {
Chris Lattner19b57f52005-06-15 20:53:31 +00003181
3182 // Check that the shift amount is in range. If not, don't perform
3183 // undefined shifts. When the shift is visited it will be
3184 // simplified.
Chris Lattner104002b2005-06-16 01:52:07 +00003185 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
Chris Lattner19b57f52005-06-15 20:53:31 +00003186 if (ShAmt->getValue() >= TypeBits)
3187 break;
3188
Chris Lattner1023b872004-09-27 16:18:50 +00003189 // If we are comparing against bits always shifted out, the
3190 // comparison cannot succeed.
Misha Brukmanb1c93172005-04-21 23:48:37 +00003191 Constant *Comp =
Chris Lattner1023b872004-09-27 16:18:50 +00003192 ConstantExpr::getShr(ConstantExpr::getShl(CI, ShAmt), ShAmt);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003193
Chris Lattner1023b872004-09-27 16:18:50 +00003194 if (Comp != CI) {// Comparing against a bit that we know is zero.
3195 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
3196 Constant *Cst = ConstantBool::get(IsSetNE);
3197 return ReplaceInstUsesWith(I, Cst);
3198 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003199
Chris Lattner1023b872004-09-27 16:18:50 +00003200 if (LHSI->hasOneUse() || CI->isNullValue()) {
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00003201 unsigned ShAmtVal = (unsigned)ShAmt->getValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00003202
Chris Lattner1023b872004-09-27 16:18:50 +00003203 // Otherwise strength reduce the shift into an and.
3204 uint64_t Val = ~0ULL; // All ones.
3205 Val <<= ShAmtVal; // Shift over to the right spot.
3206
3207 Constant *Mask;
3208 if (CI->getType()->isUnsigned()) {
Chris Lattner2f1457f2005-04-24 17:46:05 +00003209 Val &= ~0ULL >> (64-TypeBits);
Chris Lattner1023b872004-09-27 16:18:50 +00003210 Mask = ConstantUInt::get(CI->getType(), Val);
3211 } else {
3212 Mask = ConstantSInt::get(CI->getType(), Val);
3213 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003214
Chris Lattner1023b872004-09-27 16:18:50 +00003215 Instruction *AndI =
3216 BinaryOperator::createAnd(LHSI->getOperand(0),
3217 Mask, LHSI->getName()+".mask");
3218 Value *And = InsertNewInstBefore(AndI, I);
3219 return new SetCondInst(I.getOpcode(), And,
3220 ConstantExpr::getShl(CI, ShAmt));
3221 }
3222 break;
3223 }
3224 }
3225 }
3226 break;
Chris Lattner7e794272004-09-24 15:21:34 +00003227
Chris Lattner6862fbd2004-09-29 17:40:11 +00003228 case Instruction::Div:
3229 // Fold: (div X, C1) op C2 -> range check
3230 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
3231 // Fold this div into the comparison, producing a range check.
3232 // Determine, based on the divide type, what the range is being
3233 // checked. If there is an overflow on the low or high side, remember
3234 // it, otherwise compute the range [low, hi) bounding the new value.
3235 bool LoOverflow = false, HiOverflow = 0;
3236 ConstantInt *LoBound = 0, *HiBound = 0;
3237
3238 ConstantInt *Prod;
3239 bool ProdOV = MulWithOverflow(Prod, CI, DivRHS);
3240
Chris Lattnera92af962004-10-11 19:40:04 +00003241 Instruction::BinaryOps Opcode = I.getOpcode();
3242
Chris Lattner6862fbd2004-09-29 17:40:11 +00003243 if (DivRHS->isNullValue()) { // Don't hack on divide by zeros.
3244 } else if (LHSI->getType()->isUnsigned()) { // udiv
3245 LoBound = Prod;
3246 LoOverflow = ProdOV;
3247 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
3248 } else if (isPositive(DivRHS)) { // Divisor is > 0.
3249 if (CI->isNullValue()) { // (X / pos) op 0
3250 // Can't overflow.
3251 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
3252 HiBound = DivRHS;
3253 } else if (isPositive(CI)) { // (X / pos) op pos
3254 LoBound = Prod;
3255 LoOverflow = ProdOV;
3256 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
3257 } else { // (X / pos) op neg
3258 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
3259 LoOverflow = AddWithOverflow(LoBound, Prod,
3260 cast<ConstantInt>(DivRHSH));
3261 HiBound = Prod;
3262 HiOverflow = ProdOV;
3263 }
3264 } else { // Divisor is < 0.
3265 if (CI->isNullValue()) { // (X / neg) op 0
3266 LoBound = AddOne(DivRHS);
3267 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner73bcba52005-06-17 02:05:55 +00003268 if (HiBound == DivRHS)
3269 LoBound = 0; // - INTMIN = INTMIN
Chris Lattner6862fbd2004-09-29 17:40:11 +00003270 } else if (isPositive(CI)) { // (X / neg) op pos
3271 HiOverflow = LoOverflow = ProdOV;
3272 if (!LoOverflow)
3273 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
3274 HiBound = AddOne(Prod);
3275 } else { // (X / neg) op neg
3276 LoBound = Prod;
3277 LoOverflow = HiOverflow = ProdOV;
3278 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
3279 }
Chris Lattner0b41e862004-10-08 19:15:44 +00003280
Chris Lattnera92af962004-10-11 19:40:04 +00003281 // Dividing by a negate swaps the condition.
3282 Opcode = SetCondInst::getSwappedCondition(Opcode);
Chris Lattner6862fbd2004-09-29 17:40:11 +00003283 }
3284
3285 if (LoBound) {
3286 Value *X = LHSI->getOperand(0);
Chris Lattnera92af962004-10-11 19:40:04 +00003287 switch (Opcode) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00003288 default: assert(0 && "Unhandled setcc opcode!");
3289 case Instruction::SetEQ:
3290 if (LoOverflow && HiOverflow)
3291 return ReplaceInstUsesWith(I, ConstantBool::False);
3292 else if (HiOverflow)
3293 return new SetCondInst(Instruction::SetGE, X, LoBound);
3294 else if (LoOverflow)
3295 return new SetCondInst(Instruction::SetLT, X, HiBound);
3296 else
3297 return InsertRangeTest(X, LoBound, HiBound, true, I);
3298 case Instruction::SetNE:
3299 if (LoOverflow && HiOverflow)
3300 return ReplaceInstUsesWith(I, ConstantBool::True);
3301 else if (HiOverflow)
3302 return new SetCondInst(Instruction::SetLT, X, LoBound);
3303 else if (LoOverflow)
3304 return new SetCondInst(Instruction::SetGE, X, HiBound);
3305 else
3306 return InsertRangeTest(X, LoBound, HiBound, false, I);
3307 case Instruction::SetLT:
3308 if (LoOverflow)
3309 return ReplaceInstUsesWith(I, ConstantBool::False);
3310 return new SetCondInst(Instruction::SetLT, X, LoBound);
3311 case Instruction::SetGT:
3312 if (HiOverflow)
3313 return ReplaceInstUsesWith(I, ConstantBool::False);
3314 return new SetCondInst(Instruction::SetGE, X, HiBound);
3315 }
3316 }
3317 }
3318 break;
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003319 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003320
Chris Lattnerd492a0b2003-07-23 17:02:11 +00003321 // Simplify seteq and setne instructions...
3322 if (I.getOpcode() == Instruction::SetEQ ||
3323 I.getOpcode() == Instruction::SetNE) {
3324 bool isSetNE = I.getOpcode() == Instruction::SetNE;
3325
Chris Lattnercfbce7c2003-07-23 17:26:36 +00003326 // If the first operand is (and|or|xor) with a constant, and the second
Chris Lattnerd492a0b2003-07-23 17:02:11 +00003327 // operand is a constant, simplify a bit.
Chris Lattnerc992add2003-08-13 05:33:12 +00003328 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
3329 switch (BO->getOpcode()) {
Chris Lattner23b47b62004-07-06 07:38:18 +00003330 case Instruction::Rem:
3331 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
3332 if (CI->isNullValue() && isa<ConstantSInt>(BO->getOperand(1)) &&
3333 BO->hasOneUse() &&
Chris Lattner22d00a82005-08-02 19:16:58 +00003334 cast<ConstantSInt>(BO->getOperand(1))->getValue() > 1) {
3335 int64_t V = cast<ConstantSInt>(BO->getOperand(1))->getValue();
3336 if (isPowerOf2_64(V)) {
3337 unsigned L2 = Log2_64(V);
Chris Lattner23b47b62004-07-06 07:38:18 +00003338 const Type *UTy = BO->getType()->getUnsignedVersion();
3339 Value *NewX = InsertNewInstBefore(new CastInst(BO->getOperand(0),
3340 UTy, "tmp"), I);
3341 Constant *RHSCst = ConstantUInt::get(UTy, 1ULL << L2);
3342 Value *NewRem =InsertNewInstBefore(BinaryOperator::createRem(NewX,
3343 RHSCst, BO->getName()), I);
3344 return BinaryOperator::create(I.getOpcode(), NewRem,
3345 Constant::getNullValue(UTy));
3346 }
Chris Lattner22d00a82005-08-02 19:16:58 +00003347 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003348 break;
Chris Lattner23b47b62004-07-06 07:38:18 +00003349
Chris Lattnerc992add2003-08-13 05:33:12 +00003350 case Instruction::Add:
Chris Lattner6e079362004-06-27 22:51:36 +00003351 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
3352 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerb121ae12004-09-21 21:35:23 +00003353 if (BO->hasOneUse())
3354 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
3355 ConstantExpr::getSub(CI, BOp1C));
Chris Lattner6e079362004-06-27 22:51:36 +00003356 } else if (CI->isNullValue()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00003357 // Replace ((add A, B) != 0) with (A != -B) if A or B is
3358 // efficiently invertible, or if the add has just this one use.
3359 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003360
Chris Lattnerc992add2003-08-13 05:33:12 +00003361 if (Value *NegVal = dyn_castNegVal(BOp1))
3362 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
3363 else if (Value *NegVal = dyn_castNegVal(BOp0))
3364 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00003365 else if (BO->hasOneUse()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00003366 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
3367 BO->setName("");
3368 InsertNewInstBefore(Neg, I);
3369 return new SetCondInst(I.getOpcode(), BOp0, Neg);
3370 }
3371 }
3372 break;
3373 case Instruction::Xor:
3374 // For the xor case, we can xor two constants together, eliminating
3375 // the explicit xor.
3376 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
3377 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003378 ConstantExpr::getXor(CI, BOC));
Chris Lattnerc992add2003-08-13 05:33:12 +00003379
3380 // FALLTHROUGH
3381 case Instruction::Sub:
3382 // Replace (([sub|xor] A, B) != 0) with (A != B)
3383 if (CI->isNullValue())
3384 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
3385 BO->getOperand(1));
3386 break;
3387
3388 case Instruction::Or:
3389 // If bits are being or'd in that are not present in the constant we
3390 // are comparing against, then the comparison could never succeed!
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003391 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattnerc8e7e292004-06-10 02:12:35 +00003392 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003393 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00003394 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003395 }
Chris Lattnerc992add2003-08-13 05:33:12 +00003396 break;
3397
3398 case Instruction::And:
3399 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +00003400 // If bits are being compared against that are and'd out, then the
3401 // comparison can never succeed!
Chris Lattnerc8e7e292004-06-10 02:12:35 +00003402 if (!ConstantExpr::getAnd(CI,
3403 ConstantExpr::getNot(BOC))->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00003404 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc992add2003-08-13 05:33:12 +00003405
Chris Lattner35167c32004-06-09 07:59:58 +00003406 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattneree59d4b2004-06-10 02:33:20 +00003407 if (CI == BOC && isOneBitSet(CI))
Chris Lattner35167c32004-06-09 07:59:58 +00003408 return new SetCondInst(isSetNE ? Instruction::SetEQ :
3409 Instruction::SetNE, Op0,
3410 Constant::getNullValue(CI->getType()));
Chris Lattner35167c32004-06-09 07:59:58 +00003411
Chris Lattnerc992add2003-08-13 05:33:12 +00003412 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
3413 // to be a signed value as appropriate.
3414 if (isSignBit(BOC)) {
3415 Value *X = BO->getOperand(0);
3416 // If 'X' is not signed, insert a cast now...
3417 if (!BOC->getType()->isSigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +00003418 const Type *DestTy = BOC->getType()->getSignedVersion();
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003419 X = InsertCastBefore(X, DestTy, I);
Chris Lattnerc992add2003-08-13 05:33:12 +00003420 }
3421 return new SetCondInst(isSetNE ? Instruction::SetLT :
3422 Instruction::SetGE, X,
3423 Constant::getNullValue(X->getType()));
3424 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003425
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003426 // ((X & ~7) == 0) --> X < 8
Chris Lattner8fc5af42004-09-23 21:46:38 +00003427 if (CI->isNullValue() && isHighOnes(BOC)) {
3428 Value *X = BO->getOperand(0);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003429 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattner8fc5af42004-09-23 21:46:38 +00003430
3431 // If 'X' is signed, insert a cast now.
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003432 if (NegX->getType()->isSigned()) {
3433 const Type *DestTy = NegX->getType()->getUnsignedVersion();
3434 X = InsertCastBefore(X, DestTy, I);
3435 NegX = ConstantExpr::getCast(NegX, DestTy);
Chris Lattner8fc5af42004-09-23 21:46:38 +00003436 }
3437
3438 return new SetCondInst(isSetNE ? Instruction::SetGE :
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003439 Instruction::SetLT, X, NegX);
Chris Lattner8fc5af42004-09-23 21:46:38 +00003440 }
3441
Chris Lattnerd492a0b2003-07-23 17:02:11 +00003442 }
Chris Lattnerc992add2003-08-13 05:33:12 +00003443 default: break;
3444 }
3445 }
Chris Lattner2b55ea32004-02-23 07:16:20 +00003446 } else { // Not a SetEQ/SetNE
Misha Brukmanb1c93172005-04-21 23:48:37 +00003447 // If the LHS is a cast from an integral value of the same size,
Chris Lattner2b55ea32004-02-23 07:16:20 +00003448 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
3449 Value *CastOp = Cast->getOperand(0);
3450 const Type *SrcTy = CastOp->getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003451 unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
Chris Lattner2b55ea32004-02-23 07:16:20 +00003452 if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003453 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00003454 assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) &&
Chris Lattner2b55ea32004-02-23 07:16:20 +00003455 "Source and destination signednesses should differ!");
3456 if (Cast->getType()->isSigned()) {
3457 // If this is a signed comparison, check for comparisons in the
3458 // vicinity of zero.
3459 if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
3460 // X < 0 => x > 127
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003461 return BinaryOperator::createSetGT(CastOp,
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003462 ConstantUInt::get(SrcTy, (1ULL << (SrcTySize-1))-1));
Chris Lattner2b55ea32004-02-23 07:16:20 +00003463 else if (I.getOpcode() == Instruction::SetGT &&
3464 cast<ConstantSInt>(CI)->getValue() == -1)
3465 // X > -1 => x < 128
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003466 return BinaryOperator::createSetLT(CastOp,
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003467 ConstantUInt::get(SrcTy, 1ULL << (SrcTySize-1)));
Chris Lattner2b55ea32004-02-23 07:16:20 +00003468 } else {
3469 ConstantUInt *CUI = cast<ConstantUInt>(CI);
3470 if (I.getOpcode() == Instruction::SetLT &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003471 CUI->getValue() == 1ULL << (SrcTySize-1))
Chris Lattner2b55ea32004-02-23 07:16:20 +00003472 // X < 128 => X > -1
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003473 return BinaryOperator::createSetGT(CastOp,
3474 ConstantSInt::get(SrcTy, -1));
Chris Lattner2b55ea32004-02-23 07:16:20 +00003475 else if (I.getOpcode() == Instruction::SetGT &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003476 CUI->getValue() == (1ULL << (SrcTySize-1))-1)
Chris Lattner2b55ea32004-02-23 07:16:20 +00003477 // X > 127 => X < 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003478 return BinaryOperator::createSetLT(CastOp,
3479 Constant::getNullValue(SrcTy));
Chris Lattner2b55ea32004-02-23 07:16:20 +00003480 }
3481 }
3482 }
Chris Lattnere967b342003-06-04 05:10:11 +00003483 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003484 }
3485
Chris Lattner77c32c32005-04-23 15:31:55 +00003486 // Handle setcc with constant RHS's that can be integer, FP or pointer.
3487 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
3488 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
3489 switch (LHSI->getOpcode()) {
Chris Lattnera816eee2005-05-01 04:42:15 +00003490 case Instruction::GetElementPtr:
3491 if (RHSC->isNullValue()) {
3492 // Transform setcc GEP P, int 0, int 0, int 0, null -> setcc P, null
3493 bool isAllZeros = true;
3494 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
3495 if (!isa<Constant>(LHSI->getOperand(i)) ||
3496 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
3497 isAllZeros = false;
3498 break;
3499 }
3500 if (isAllZeros)
3501 return new SetCondInst(I.getOpcode(), LHSI->getOperand(0),
3502 Constant::getNullValue(LHSI->getOperand(0)->getType()));
3503 }
3504 break;
3505
Chris Lattner77c32c32005-04-23 15:31:55 +00003506 case Instruction::PHI:
3507 if (Instruction *NV = FoldOpIntoPhi(I))
3508 return NV;
3509 break;
3510 case Instruction::Select:
3511 // If either operand of the select is a constant, we can fold the
3512 // comparison into the select arms, which will cause one to be
3513 // constant folded and the select turned into a bitwise or.
3514 Value *Op1 = 0, *Op2 = 0;
3515 if (LHSI->hasOneUse()) {
3516 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
3517 // Fold the known value into the constant operand.
3518 Op1 = ConstantExpr::get(I.getOpcode(), C, RHSC);
3519 // Insert a new SetCC of the other select operand.
3520 Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
3521 LHSI->getOperand(2), RHSC,
3522 I.getName()), I);
3523 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
3524 // Fold the known value into the constant operand.
3525 Op2 = ConstantExpr::get(I.getOpcode(), C, RHSC);
3526 // Insert a new SetCC of the other select operand.
3527 Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
3528 LHSI->getOperand(1), RHSC,
3529 I.getName()), I);
3530 }
3531 }
Jeff Cohen82639852005-04-23 21:38:35 +00003532
Chris Lattner77c32c32005-04-23 15:31:55 +00003533 if (Op1)
3534 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
3535 break;
3536 }
3537 }
3538
Chris Lattner0798af32005-01-13 20:14:25 +00003539 // If we can optimize a 'setcc GEP, P' or 'setcc P, GEP', do so now.
3540 if (User *GEP = dyn_castGetElementPtr(Op0))
3541 if (Instruction *NI = FoldGEPSetCC(GEP, Op1, I.getOpcode(), I))
3542 return NI;
3543 if (User *GEP = dyn_castGetElementPtr(Op1))
3544 if (Instruction *NI = FoldGEPSetCC(GEP, Op0,
3545 SetCondInst::getSwappedCondition(I.getOpcode()), I))
3546 return NI;
3547
Chris Lattner16930792003-11-03 04:25:02 +00003548 // Test to see if the operands of the setcc are casted versions of other
3549 // values. If the cast can be stripped off both arguments, we do so now.
Chris Lattner6444c372003-11-03 05:17:03 +00003550 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3551 Value *CastOp0 = CI->getOperand(0);
3552 if (CastOp0->getType()->isLosslesslyConvertibleTo(CI->getType()) &&
Chris Lattner7d2a5392004-03-13 23:54:27 +00003553 (isa<Constant>(Op1) || isa<CastInst>(Op1)) &&
Chris Lattner16930792003-11-03 04:25:02 +00003554 (I.getOpcode() == Instruction::SetEQ ||
3555 I.getOpcode() == Instruction::SetNE)) {
3556 // We keep moving the cast from the left operand over to the right
3557 // operand, where it can often be eliminated completely.
Chris Lattner6444c372003-11-03 05:17:03 +00003558 Op0 = CastOp0;
Misha Brukmanb1c93172005-04-21 23:48:37 +00003559
Chris Lattner16930792003-11-03 04:25:02 +00003560 // If operand #1 is a cast instruction, see if we can eliminate it as
3561 // well.
Chris Lattner6444c372003-11-03 05:17:03 +00003562 if (CastInst *CI2 = dyn_cast<CastInst>(Op1))
3563 if (CI2->getOperand(0)->getType()->isLosslesslyConvertibleTo(
Chris Lattner16930792003-11-03 04:25:02 +00003564 Op0->getType()))
Chris Lattner6444c372003-11-03 05:17:03 +00003565 Op1 = CI2->getOperand(0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003566
Chris Lattner16930792003-11-03 04:25:02 +00003567 // If Op1 is a constant, we can fold the cast into the constant.
3568 if (Op1->getType() != Op0->getType())
3569 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
3570 Op1 = ConstantExpr::getCast(Op1C, Op0->getType());
3571 } else {
3572 // Otherwise, cast the RHS right before the setcc
3573 Op1 = new CastInst(Op1, Op0->getType(), Op1->getName());
3574 InsertNewInstBefore(cast<Instruction>(Op1), I);
3575 }
3576 return BinaryOperator::create(I.getOpcode(), Op0, Op1);
3577 }
3578
Chris Lattner6444c372003-11-03 05:17:03 +00003579 // Handle the special case of: setcc (cast bool to X), <cst>
3580 // This comes up when you have code like
3581 // int X = A < B;
3582 // if (X) ...
3583 // For generality, we handle any zero-extension of any operand comparison
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003584 // with a constant or another cast from the same type.
3585 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
3586 if (Instruction *R = visitSetCondInstWithCastAndCast(I))
3587 return R;
Chris Lattner6444c372003-11-03 05:17:03 +00003588 }
Chris Lattner113f4f42002-06-25 16:13:24 +00003589 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003590}
3591
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003592// visitSetCondInstWithCastAndCast - Handle setcond (cast x to y), (cast/cst).
3593// We only handle extending casts so far.
3594//
3595Instruction *InstCombiner::visitSetCondInstWithCastAndCast(SetCondInst &SCI) {
3596 Value *LHSCIOp = cast<CastInst>(SCI.getOperand(0))->getOperand(0);
3597 const Type *SrcTy = LHSCIOp->getType();
3598 const Type *DestTy = SCI.getOperand(0)->getType();
3599 Value *RHSCIOp;
3600
3601 if (!DestTy->isIntegral() || !SrcTy->isIntegral())
Chris Lattner03f06f12005-01-17 03:20:02 +00003602 return 0;
3603
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003604 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
3605 unsigned DestBits = DestTy->getPrimitiveSizeInBits();
3606 if (SrcBits >= DestBits) return 0; // Only handle extending cast.
3607
3608 // Is this a sign or zero extension?
3609 bool isSignSrc = SrcTy->isSigned();
3610 bool isSignDest = DestTy->isSigned();
3611
3612 if (CastInst *CI = dyn_cast<CastInst>(SCI.getOperand(1))) {
3613 // Not an extension from the same type?
3614 RHSCIOp = CI->getOperand(0);
3615 if (RHSCIOp->getType() != LHSCIOp->getType()) return 0;
3616 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(SCI.getOperand(1))) {
3617 // Compute the constant that would happen if we truncated to SrcTy then
3618 // reextended to DestTy.
3619 Constant *Res = ConstantExpr::getCast(CI, SrcTy);
3620
3621 if (ConstantExpr::getCast(Res, DestTy) == CI) {
3622 RHSCIOp = Res;
3623 } else {
3624 // If the value cannot be represented in the shorter type, we cannot emit
3625 // a simple comparison.
3626 if (SCI.getOpcode() == Instruction::SetEQ)
3627 return ReplaceInstUsesWith(SCI, ConstantBool::False);
3628 if (SCI.getOpcode() == Instruction::SetNE)
3629 return ReplaceInstUsesWith(SCI, ConstantBool::True);
3630
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003631 // Evaluate the comparison for LT.
3632 Value *Result;
3633 if (DestTy->isSigned()) {
3634 // We're performing a signed comparison.
3635 if (isSignSrc) {
3636 // Signed extend and signed comparison.
3637 if (cast<ConstantSInt>(CI)->getValue() < 0) // X < (small) --> false
3638 Result = ConstantBool::False;
3639 else
3640 Result = ConstantBool::True; // X < (large) --> true
3641 } else {
3642 // Unsigned extend and signed comparison.
3643 if (cast<ConstantSInt>(CI)->getValue() < 0)
3644 Result = ConstantBool::False;
3645 else
3646 Result = ConstantBool::True;
3647 }
3648 } else {
3649 // We're performing an unsigned comparison.
3650 if (!isSignSrc) {
3651 // Unsigned extend & compare -> always true.
3652 Result = ConstantBool::True;
3653 } else {
3654 // We're performing an unsigned comp with a sign extended value.
3655 // This is true if the input is >= 0. [aka >s -1]
3656 Constant *NegOne = ConstantIntegral::getAllOnesValue(SrcTy);
3657 Result = InsertNewInstBefore(BinaryOperator::createSetGT(LHSCIOp,
3658 NegOne, SCI.getName()), SCI);
3659 }
Reid Spencer279fa252004-11-28 21:31:15 +00003660 }
Chris Lattner03f06f12005-01-17 03:20:02 +00003661
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00003662 // Finally, return the value computed.
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003663 if (SCI.getOpcode() == Instruction::SetLT) {
3664 return ReplaceInstUsesWith(SCI, Result);
3665 } else {
3666 assert(SCI.getOpcode()==Instruction::SetGT &&"SetCC should be folded!");
3667 if (Constant *CI = dyn_cast<Constant>(Result))
3668 return ReplaceInstUsesWith(SCI, ConstantExpr::getNot(CI));
3669 else
3670 return BinaryOperator::createNot(Result);
3671 }
Chris Lattner03f06f12005-01-17 03:20:02 +00003672 }
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003673 } else {
3674 return 0;
Reid Spencer279fa252004-11-28 21:31:15 +00003675 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003676
Chris Lattner252a8452005-06-16 03:00:08 +00003677 // Okay, just insert a compare of the reduced operands now!
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003678 return BinaryOperator::create(SCI.getOpcode(), LHSCIOp, RHSCIOp);
3679}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003680
Chris Lattnere8d6c602003-03-10 19:16:08 +00003681Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00003682 assert(I.getOperand(1)->getType() == Type::UByteTy);
3683 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003684 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003685
3686 // shl X, 0 == X and shr X, 0 == X
3687 // shl 0, X == 0 and shr 0, X == 0
3688 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
Chris Lattnere6794492002-08-12 21:17:25 +00003689 Op0 == Constant::getNullValue(Op0->getType()))
3690 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003691
Chris Lattner81a7a232004-10-16 18:11:37 +00003692 if (isa<UndefValue>(Op0)) { // undef >>s X -> undef
3693 if (!isLeftShift && I.getType()->isSigned())
Chris Lattner67f05452004-10-16 23:28:04 +00003694 return ReplaceInstUsesWith(I, Op0);
Chris Lattner81a7a232004-10-16 18:11:37 +00003695 else // undef << X -> 0 AND undef >>u X -> 0
3696 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3697 }
3698 if (isa<UndefValue>(Op1)) {
Chris Lattner18aa4d82005-07-20 18:49:28 +00003699 if (isLeftShift || I.getType()->isUnsigned())// X << undef, X >>u undef -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00003700 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3701 else
3702 return ReplaceInstUsesWith(I, Op0); // X >>s undef -> X
3703 }
3704
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003705 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
3706 if (!isLeftShift)
3707 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
3708 if (CSI->isAllOnesValue())
3709 return ReplaceInstUsesWith(I, CSI);
3710
Chris Lattner183b3362004-04-09 19:05:30 +00003711 // Try to fold constant and into select arguments.
3712 if (isa<Constant>(Op0))
3713 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00003714 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003715 return R;
3716
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00003717 // See if we can turn a signed shr into an unsigned shr.
3718 if (!isLeftShift && I.getType()->isSigned()) {
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003719 if (MaskedValueIsZero(Op0,
3720 1ULL << (I.getType()->getPrimitiveSizeInBits()-1))) {
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00003721 Value *V = InsertCastBefore(Op0, I.getType()->getUnsignedVersion(), I);
3722 V = InsertNewInstBefore(new ShiftInst(Instruction::Shr, V, Op1,
3723 I.getName()), I);
3724 return new CastInst(V, I.getType());
3725 }
3726 }
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00003727
Chris Lattner14553932006-01-06 07:12:35 +00003728 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1))
3729 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
3730 return Res;
3731 return 0;
3732}
3733
3734Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantUInt *Op1,
3735 ShiftInst &I) {
3736 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattnerb3309392006-01-06 07:22:22 +00003737 bool isSignedShift = Op0->getType()->isSigned();
3738 bool isUnsignedShift = !isSignedShift;
Chris Lattner14553932006-01-06 07:12:35 +00003739
3740 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
3741 // of a signed value.
3742 //
3743 unsigned TypeBits = Op0->getType()->getPrimitiveSizeInBits();
3744 if (Op1->getValue() >= TypeBits) {
Chris Lattnerb3309392006-01-06 07:22:22 +00003745 if (isUnsignedShift || isLeftShift)
Chris Lattner14553932006-01-06 07:12:35 +00003746 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
3747 else {
3748 I.setOperand(1, ConstantUInt::get(Type::UByteTy, TypeBits-1));
3749 return &I;
Chris Lattnerf5ce2542004-02-23 20:30:06 +00003750 }
Chris Lattner14553932006-01-06 07:12:35 +00003751 }
3752
3753 // ((X*C1) << C2) == (X * (C1 << C2))
3754 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
3755 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
3756 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
3757 return BinaryOperator::createMul(BO->getOperand(0),
3758 ConstantExpr::getShl(BOOp, Op1));
3759
3760 // Try to fold constant and into select arguments.
3761 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3762 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3763 return R;
3764 if (isa<PHINode>(Op0))
3765 if (Instruction *NV = FoldOpIntoPhi(I))
3766 return NV;
3767
3768 if (Op0->hasOneUse()) {
3769 // If this is a SHL of a sign-extending cast, see if we can turn the input
3770 // into a zero extending cast (a simple strength reduction).
3771 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3772 const Type *SrcTy = CI->getOperand(0)->getType();
3773 if (isLeftShift && SrcTy->isInteger() && SrcTy->isSigned() &&
3774 SrcTy->getPrimitiveSizeInBits() <
3775 CI->getType()->getPrimitiveSizeInBits()) {
3776 // We can change it to a zero extension if we are shifting out all of
3777 // the sign extended bits. To check this, form a mask of all of the
3778 // sign extend bits, then shift them left and see if we have anything
3779 // left.
3780 Constant *Mask = ConstantIntegral::getAllOnesValue(SrcTy); // 1111
3781 Mask = ConstantExpr::getZeroExtend(Mask, CI->getType()); // 00001111
3782 Mask = ConstantExpr::getNot(Mask); // 1's in the sign bits: 11110000
3783 if (ConstantExpr::getShl(Mask, Op1)->isNullValue()) {
3784 // If the shift is nuking all of the sign bits, change this to a
3785 // zero extension cast. To do this, cast the cast input to
3786 // unsigned, then to the requested size.
3787 Value *CastOp = CI->getOperand(0);
3788 Instruction *NC =
3789 new CastInst(CastOp, CastOp->getType()->getUnsignedVersion(),
3790 CI->getName()+".uns");
3791 NC = InsertNewInstBefore(NC, I);
3792 // Finally, insert a replacement for CI.
3793 NC = new CastInst(NC, CI->getType(), CI->getName());
3794 CI->setName("");
3795 NC = InsertNewInstBefore(NC, I);
3796 WorkList.push_back(CI); // Delete CI later.
3797 I.setOperand(0, NC);
3798 return &I; // The SHL operand was modified.
Chris Lattner86102b82005-01-01 16:22:27 +00003799 }
3800 }
Chris Lattner14553932006-01-06 07:12:35 +00003801 }
3802
3803 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
3804 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
3805 Value *V1, *V2;
3806 ConstantInt *CC;
3807 switch (Op0BO->getOpcode()) {
Chris Lattner27cb9db2005-09-18 05:12:10 +00003808 default: break;
3809 case Instruction::Add:
3810 case Instruction::And:
3811 case Instruction::Or:
3812 case Instruction::Xor:
3813 // These operators commute.
3814 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00003815 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
3816 match(Op0BO->getOperand(1),
Chris Lattner14553932006-01-06 07:12:35 +00003817 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Chris Lattner797dee72005-09-18 06:30:59 +00003818 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00003819 Op0BO->getOperand(0), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00003820 Op0BO->getName());
3821 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00003822 Instruction *X =
3823 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
3824 Op0BO->getOperand(1)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00003825 InsertNewInstBefore(X, I); // (X + (Y << C))
3826 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner14553932006-01-06 07:12:35 +00003827 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner797dee72005-09-18 06:30:59 +00003828 return BinaryOperator::createAnd(X, C2);
3829 }
Chris Lattner14553932006-01-06 07:12:35 +00003830
Chris Lattner797dee72005-09-18 06:30:59 +00003831 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
3832 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
3833 match(Op0BO->getOperand(1),
3834 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner14553932006-01-06 07:12:35 +00003835 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner24cd2fa2006-02-09 07:41:14 +00003836 cast<BinaryOperator>(Op0BO->getOperand(1))->getOperand(0)->hasOneUse()) {
Chris Lattner797dee72005-09-18 06:30:59 +00003837 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00003838 Op0BO->getOperand(0), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00003839 Op0BO->getName());
3840 InsertNewInstBefore(YS, I); // (Y << C)
3841 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00003842 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00003843 V1->getName()+".mask");
3844 InsertNewInstBefore(XM, I); // X & (CC << C)
3845
3846 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
3847 }
Chris Lattner14553932006-01-06 07:12:35 +00003848
Chris Lattner797dee72005-09-18 06:30:59 +00003849 // FALL THROUGH.
Chris Lattner27cb9db2005-09-18 05:12:10 +00003850 case Instruction::Sub:
3851 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00003852 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
3853 match(Op0BO->getOperand(0),
Chris Lattner14553932006-01-06 07:12:35 +00003854 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Chris Lattner797dee72005-09-18 06:30:59 +00003855 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00003856 Op0BO->getOperand(1), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00003857 Op0BO->getName());
3858 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00003859 Instruction *X =
3860 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
3861 Op0BO->getOperand(0)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00003862 InsertNewInstBefore(X, I); // (X + (Y << C))
3863 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner14553932006-01-06 07:12:35 +00003864 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner797dee72005-09-18 06:30:59 +00003865 return BinaryOperator::createAnd(X, C2);
3866 }
Chris Lattner14553932006-01-06 07:12:35 +00003867
Chris Lattner797dee72005-09-18 06:30:59 +00003868 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
3869 match(Op0BO->getOperand(0),
3870 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner14553932006-01-06 07:12:35 +00003871 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner24cd2fa2006-02-09 07:41:14 +00003872 cast<BinaryOperator>(Op0BO->getOperand(0))
3873 ->getOperand(0)->hasOneUse()) {
Chris Lattner797dee72005-09-18 06:30:59 +00003874 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00003875 Op0BO->getOperand(1), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00003876 Op0BO->getName());
3877 InsertNewInstBefore(YS, I); // (Y << C)
3878 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00003879 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00003880 V1->getName()+".mask");
3881 InsertNewInstBefore(XM, I); // X & (CC << C)
3882
3883 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
3884 }
Chris Lattner14553932006-01-06 07:12:35 +00003885
Chris Lattner27cb9db2005-09-18 05:12:10 +00003886 break;
Chris Lattner14553932006-01-06 07:12:35 +00003887 }
3888
3889
3890 // If the operand is an bitwise operator with a constant RHS, and the
3891 // shift is the only use, we can pull it out of the shift.
3892 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
3893 bool isValid = true; // Valid only for And, Or, Xor
3894 bool highBitSet = false; // Transform if high bit of constant set?
3895
3896 switch (Op0BO->getOpcode()) {
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003897 default: isValid = false; break; // Do not perform transform!
Chris Lattner44bd3922004-10-08 03:46:20 +00003898 case Instruction::Add:
3899 isValid = isLeftShift;
3900 break;
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003901 case Instruction::Or:
3902 case Instruction::Xor:
3903 highBitSet = false;
3904 break;
3905 case Instruction::And:
3906 highBitSet = true;
3907 break;
Chris Lattner14553932006-01-06 07:12:35 +00003908 }
3909
3910 // If this is a signed shift right, and the high bit is modified
3911 // by the logical operation, do not perform the transformation.
3912 // The highBitSet boolean indicates the value of the high bit of
3913 // the constant which would cause it to be modified for this
3914 // operation.
3915 //
Chris Lattnerb3309392006-01-06 07:22:22 +00003916 if (isValid && !isLeftShift && isSignedShift) {
Chris Lattner14553932006-01-06 07:12:35 +00003917 uint64_t Val = Op0C->getRawValue();
3918 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
3919 }
3920
3921 if (isValid) {
3922 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
3923
3924 Instruction *NewShift =
3925 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), Op1,
3926 Op0BO->getName());
3927 Op0BO->setName("");
3928 InsertNewInstBefore(NewShift, I);
3929
3930 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
3931 NewRHS);
3932 }
3933 }
3934 }
3935 }
3936
Chris Lattnereb372a02006-01-06 07:52:12 +00003937 // Find out if this is a shift of a shift by a constant.
3938 ShiftInst *ShiftOp = 0;
Chris Lattner14553932006-01-06 07:12:35 +00003939 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
Chris Lattnereb372a02006-01-06 07:52:12 +00003940 ShiftOp = Op0SI;
3941 else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3942 // If this is a noop-integer case of a shift instruction, use the shift.
3943 if (CI->getOperand(0)->getType()->isInteger() &&
3944 CI->getOperand(0)->getType()->getPrimitiveSizeInBits() ==
3945 CI->getType()->getPrimitiveSizeInBits() &&
3946 isa<ShiftInst>(CI->getOperand(0))) {
3947 ShiftOp = cast<ShiftInst>(CI->getOperand(0));
3948 }
3949 }
3950
3951 if (ShiftOp && isa<ConstantUInt>(ShiftOp->getOperand(1))) {
3952 // Find the operands and properties of the input shift. Note that the
3953 // signedness of the input shift may differ from the current shift if there
3954 // is a noop cast between the two.
3955 bool isShiftOfLeftShift = ShiftOp->getOpcode() == Instruction::Shl;
3956 bool isShiftOfSignedShift = ShiftOp->getType()->isSigned();
Chris Lattner9cbfbc22006-01-07 01:32:28 +00003957 bool isShiftOfUnsignedShift = !isShiftOfSignedShift;
Chris Lattnereb372a02006-01-06 07:52:12 +00003958
3959 ConstantUInt *ShiftAmt1C = cast<ConstantUInt>(ShiftOp->getOperand(1));
3960
3961 unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getValue();
3962 unsigned ShiftAmt2 = (unsigned)Op1->getValue();
3963
3964 // Check for (A << c1) << c2 and (A >> c1) >> c2.
3965 if (isLeftShift == isShiftOfLeftShift) {
3966 // Do not fold these shifts if the first one is signed and the second one
3967 // is unsigned and this is a right shift. Further, don't do any folding
3968 // on them.
3969 if (isShiftOfSignedShift && isUnsignedShift && !isLeftShift)
3970 return 0;
Chris Lattner14553932006-01-06 07:12:35 +00003971
Chris Lattnereb372a02006-01-06 07:52:12 +00003972 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
3973 if (Amt > Op0->getType()->getPrimitiveSizeInBits())
3974 Amt = Op0->getType()->getPrimitiveSizeInBits();
Chris Lattner14553932006-01-06 07:12:35 +00003975
Chris Lattnereb372a02006-01-06 07:52:12 +00003976 Value *Op = ShiftOp->getOperand(0);
3977 if (isShiftOfSignedShift != isSignedShift)
3978 Op = InsertNewInstBefore(new CastInst(Op, I.getType(), "tmp"), I);
3979 return new ShiftInst(I.getOpcode(), Op,
3980 ConstantUInt::get(Type::UByteTy, Amt));
3981 }
3982
3983 // Check for (A << c1) >> c2 or (A >> c1) << c2. If we are dealing with
3984 // signed types, we can only support the (A >> c1) << c2 configuration,
3985 // because it can not turn an arbitrary bit of A into a sign bit.
3986 if (isUnsignedShift || isLeftShift) {
3987 // Calculate bitmask for what gets shifted off the edge.
3988 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
3989 if (isLeftShift)
3990 C = ConstantExpr::getShl(C, ShiftAmt1C);
3991 else
Chris Lattner9cbfbc22006-01-07 01:32:28 +00003992 C = ConstantExpr::getUShr(C, ShiftAmt1C);
Chris Lattnereb372a02006-01-06 07:52:12 +00003993
3994 Value *Op = ShiftOp->getOperand(0);
3995 if (isShiftOfSignedShift != isSignedShift)
3996 Op = InsertNewInstBefore(new CastInst(Op, I.getType(),Op->getName()),I);
3997
3998 Instruction *Mask =
3999 BinaryOperator::createAnd(Op, C, Op->getName()+".mask");
4000 InsertNewInstBefore(Mask, I);
4001
4002 // Figure out what flavor of shift we should use...
Chris Lattner9cbfbc22006-01-07 01:32:28 +00004003 if (ShiftAmt1 == ShiftAmt2) {
Chris Lattnereb372a02006-01-06 07:52:12 +00004004 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
Chris Lattner9cbfbc22006-01-07 01:32:28 +00004005 } else if (ShiftAmt1 < ShiftAmt2) {
Chris Lattnereb372a02006-01-06 07:52:12 +00004006 return new ShiftInst(I.getOpcode(), Mask,
4007 ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00004008 } else if (isShiftOfUnsignedShift || isShiftOfLeftShift) {
4009 if (isShiftOfUnsignedShift && !isShiftOfLeftShift && isSignedShift) {
4010 // Make sure to emit an unsigned shift right, not a signed one.
4011 Mask = InsertNewInstBefore(new CastInst(Mask,
4012 Mask->getType()->getUnsignedVersion(),
4013 Op->getName()), I);
4014 Mask = new ShiftInst(Instruction::Shr, Mask,
Chris Lattnereb372a02006-01-06 07:52:12 +00004015 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00004016 InsertNewInstBefore(Mask, I);
4017 return new CastInst(Mask, I.getType());
4018 } else {
4019 return new ShiftInst(ShiftOp->getOpcode(), Mask,
4020 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
4021 }
4022 } else {
4023 // (X >>s C1) << C2 where C1 > C2 === (X >>s (C1-C2)) & mask
4024 Op = InsertNewInstBefore(new CastInst(Mask,
4025 I.getType()->getSignedVersion(),
4026 Mask->getName()), I);
4027 Instruction *Shift =
4028 new ShiftInst(ShiftOp->getOpcode(), Op,
4029 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
4030 InsertNewInstBefore(Shift, I);
4031
4032 C = ConstantIntegral::getAllOnesValue(Shift->getType());
4033 C = ConstantExpr::getShl(C, Op1);
4034 Mask = BinaryOperator::createAnd(Shift, C, Op->getName()+".mask");
4035 InsertNewInstBefore(Mask, I);
4036 return new CastInst(Mask, I.getType());
Chris Lattnereb372a02006-01-06 07:52:12 +00004037 }
4038 } else {
Chris Lattner9cbfbc22006-01-07 01:32:28 +00004039 // We can handle signed (X << C1) >>s C2 if it's a sign extend. In
Chris Lattnereb372a02006-01-06 07:52:12 +00004040 // this case, C1 == C2 and C1 is 8, 16, or 32.
4041 if (ShiftAmt1 == ShiftAmt2) {
4042 const Type *SExtType = 0;
4043 switch (ShiftAmt1) {
4044 case 8 : SExtType = Type::SByteTy; break;
4045 case 16: SExtType = Type::ShortTy; break;
4046 case 32: SExtType = Type::IntTy; break;
4047 }
4048
4049 if (SExtType) {
4050 Instruction *NewTrunc = new CastInst(ShiftOp->getOperand(0),
4051 SExtType, "sext");
4052 InsertNewInstBefore(NewTrunc, I);
4053 return new CastInst(NewTrunc, I.getType());
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00004054 }
Chris Lattner27cb9db2005-09-18 05:12:10 +00004055 }
Chris Lattner86102b82005-01-01 16:22:27 +00004056 }
Chris Lattnereb372a02006-01-06 07:52:12 +00004057 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004058 return 0;
4059}
4060
Chris Lattner4e2dbc62004-07-20 00:59:32 +00004061enum CastType {
4062 Noop = 0,
4063 Truncate = 1,
4064 Signext = 2,
4065 Zeroext = 3
4066};
4067
4068/// getCastType - In the future, we will split the cast instruction into these
4069/// various types. Until then, we have to do the analysis here.
4070static CastType getCastType(const Type *Src, const Type *Dest) {
4071 assert(Src->isIntegral() && Dest->isIntegral() &&
4072 "Only works on integral types!");
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004073 unsigned SrcSize = Src->getPrimitiveSizeInBits();
4074 unsigned DestSize = Dest->getPrimitiveSizeInBits();
Chris Lattner4e2dbc62004-07-20 00:59:32 +00004075
4076 if (SrcSize == DestSize) return Noop;
4077 if (SrcSize > DestSize) return Truncate;
4078 if (Src->isSigned()) return Signext;
4079 return Zeroext;
4080}
4081
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004082
Chris Lattner48a44f72002-05-02 17:06:02 +00004083// isEliminableCastOfCast - Return true if it is valid to eliminate the CI
4084// instruction.
4085//
Chris Lattnere154abf2006-01-19 07:40:22 +00004086static bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
4087 const Type *DstTy, TargetData *TD) {
Chris Lattner48a44f72002-05-02 17:06:02 +00004088
Chris Lattner650b6da2002-08-02 20:00:25 +00004089 // It is legal to eliminate the instruction if casting A->B->A if the sizes
Misha Brukmanb1c93172005-04-21 23:48:37 +00004090 // are identical and the bits don't get reinterpreted (for example
Chris Lattner1638de42004-07-21 19:50:44 +00004091 // int->float->int would not be allowed).
Misha Brukmane5838c42003-05-20 18:45:36 +00004092 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
Chris Lattner650b6da2002-08-02 20:00:25 +00004093 return true;
Chris Lattner48a44f72002-05-02 17:06:02 +00004094
Chris Lattner4fbad962004-07-21 04:27:24 +00004095 // If we are casting between pointer and integer types, treat pointers as
4096 // integers of the appropriate size for the code below.
4097 if (isa<PointerType>(SrcTy)) SrcTy = TD->getIntPtrType();
4098 if (isa<PointerType>(MidTy)) MidTy = TD->getIntPtrType();
4099 if (isa<PointerType>(DstTy)) DstTy = TD->getIntPtrType();
Chris Lattner11ffd592004-07-20 05:21:00 +00004100
Chris Lattner48a44f72002-05-02 17:06:02 +00004101 // Allow free casting and conversion of sizes as long as the sign doesn't
4102 // change...
Chris Lattnerb0b412e2002-09-03 01:08:28 +00004103 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
Chris Lattner4e2dbc62004-07-20 00:59:32 +00004104 CastType FirstCast = getCastType(SrcTy, MidTy);
4105 CastType SecondCast = getCastType(MidTy, DstTy);
Chris Lattner650b6da2002-08-02 20:00:25 +00004106
Chris Lattner4e2dbc62004-07-20 00:59:32 +00004107 // Capture the effect of these two casts. If the result is a legal cast,
4108 // the CastType is stored here, otherwise a special code is used.
4109 static const unsigned CastResult[] = {
4110 // First cast is noop
4111 0, 1, 2, 3,
4112 // First cast is a truncate
4113 1, 1, 4, 4, // trunc->extend is not safe to eliminate
4114 // First cast is a sign ext
Chris Lattner1638de42004-07-21 19:50:44 +00004115 2, 5, 2, 4, // signext->zeroext never ok
Chris Lattner4e2dbc62004-07-20 00:59:32 +00004116 // First cast is a zero ext
Chris Lattner1638de42004-07-21 19:50:44 +00004117 3, 5, 3, 3,
Chris Lattner4e2dbc62004-07-20 00:59:32 +00004118 };
4119
4120 unsigned Result = CastResult[FirstCast*4+SecondCast];
4121 switch (Result) {
4122 default: assert(0 && "Illegal table value!");
4123 case 0:
4124 case 1:
4125 case 2:
4126 case 3:
4127 // FIXME: in the future, when LLVM has explicit sign/zeroextends and
4128 // truncates, we could eliminate more casts.
4129 return (unsigned)getCastType(SrcTy, DstTy) == Result;
4130 case 4:
4131 return false; // Not possible to eliminate this here.
4132 case 5:
Chris Lattner1638de42004-07-21 19:50:44 +00004133 // Sign or zero extend followed by truncate is always ok if the result
4134 // is a truncate or noop.
4135 CastType ResultCast = getCastType(SrcTy, DstTy);
4136 if (ResultCast == Noop || ResultCast == Truncate)
4137 return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00004138 // Otherwise we are still growing the value, we are only safe if the
Chris Lattner1638de42004-07-21 19:50:44 +00004139 // result will match the sign/zeroextendness of the result.
4140 return ResultCast == FirstCast;
Chris Lattner3732aca2002-08-15 16:15:25 +00004141 }
Chris Lattner650b6da2002-08-02 20:00:25 +00004142 }
Chris Lattnere154abf2006-01-19 07:40:22 +00004143
4144 // If this is a cast from 'float -> double -> integer', cast from
4145 // 'float -> integer' directly, as the value isn't changed by the
4146 // float->double conversion.
4147 if (SrcTy->isFloatingPoint() && MidTy->isFloatingPoint() &&
4148 DstTy->isIntegral() &&
4149 SrcTy->getPrimitiveSize() < MidTy->getPrimitiveSize())
4150 return true;
4151
Chris Lattner48a44f72002-05-02 17:06:02 +00004152 return false;
4153}
4154
Chris Lattner11ffd592004-07-20 05:21:00 +00004155static bool ValueRequiresCast(const Value *V, const Type *Ty, TargetData *TD) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00004156 if (V->getType() == Ty || isa<Constant>(V)) return false;
4157 if (const CastInst *CI = dyn_cast<CastInst>(V))
Chris Lattner11ffd592004-07-20 05:21:00 +00004158 if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty,
4159 TD))
Chris Lattnerdfae8be2003-07-24 17:35:25 +00004160 return false;
4161 return true;
4162}
4163
4164/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
4165/// InsertBefore instruction. This is specialized a bit to avoid inserting
4166/// casts that are known to not do anything...
4167///
4168Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
4169 Instruction *InsertBefore) {
4170 if (V->getType() == DestTy) return V;
4171 if (Constant *C = dyn_cast<Constant>(V))
4172 return ConstantExpr::getCast(C, DestTy);
4173
4174 CastInst *CI = new CastInst(V, DestTy, V->getName());
4175 InsertNewInstBefore(CI, *InsertBefore);
4176 return CI;
4177}
Chris Lattner48a44f72002-05-02 17:06:02 +00004178
Chris Lattner8f663e82005-10-29 04:36:15 +00004179/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
4180/// expression. If so, decompose it, returning some value X, such that Val is
4181/// X*Scale+Offset.
4182///
4183static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
4184 unsigned &Offset) {
4185 assert(Val->getType() == Type::UIntTy && "Unexpected allocation size type!");
4186 if (ConstantUInt *CI = dyn_cast<ConstantUInt>(Val)) {
4187 Offset = CI->getValue();
4188 Scale = 1;
4189 return ConstantUInt::get(Type::UIntTy, 0);
4190 } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
4191 if (I->getNumOperands() == 2) {
4192 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(I->getOperand(1))) {
4193 if (I->getOpcode() == Instruction::Shl) {
4194 // This is a value scaled by '1 << the shift amt'.
4195 Scale = 1U << CUI->getValue();
4196 Offset = 0;
4197 return I->getOperand(0);
4198 } else if (I->getOpcode() == Instruction::Mul) {
4199 // This value is scaled by 'CUI'.
4200 Scale = CUI->getValue();
4201 Offset = 0;
4202 return I->getOperand(0);
4203 } else if (I->getOpcode() == Instruction::Add) {
4204 // We have X+C. Check to see if we really have (X*C2)+C1, where C1 is
4205 // divisible by C2.
4206 unsigned SubScale;
4207 Value *SubVal = DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
4208 Offset);
4209 Offset += CUI->getValue();
4210 if (SubScale > 1 && (Offset % SubScale == 0)) {
4211 Scale = SubScale;
4212 return SubVal;
4213 }
4214 }
4215 }
4216 }
4217 }
4218
4219 // Otherwise, we can't look past this.
4220 Scale = 1;
4221 Offset = 0;
4222 return Val;
4223}
4224
4225
Chris Lattner216be912005-10-24 06:03:58 +00004226/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
4227/// try to eliminate the cast by moving the type information into the alloc.
4228Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
4229 AllocationInst &AI) {
4230 const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
Chris Lattnerbb171802005-10-27 05:53:56 +00004231 if (!PTy) return 0; // Not casting the allocation to a pointer type.
Chris Lattner216be912005-10-24 06:03:58 +00004232
Chris Lattnerac87beb2005-10-24 06:22:12 +00004233 // Remove any uses of AI that are dead.
4234 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
4235 std::vector<Instruction*> DeadUsers;
4236 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
4237 Instruction *User = cast<Instruction>(*UI++);
4238 if (isInstructionTriviallyDead(User)) {
4239 while (UI != E && *UI == User)
4240 ++UI; // If this instruction uses AI more than once, don't break UI.
4241
4242 // Add operands to the worklist.
4243 AddUsesToWorkList(*User);
4244 ++NumDeadInst;
4245 DEBUG(std::cerr << "IC: DCE: " << *User);
4246
4247 User->eraseFromParent();
4248 removeFromWorkList(User);
4249 }
4250 }
4251
Chris Lattner216be912005-10-24 06:03:58 +00004252 // Get the type really allocated and the type casted to.
4253 const Type *AllocElTy = AI.getAllocatedType();
4254 const Type *CastElTy = PTy->getElementType();
4255 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00004256
4257 unsigned AllocElTyAlign = TD->getTypeSize(AllocElTy);
4258 unsigned CastElTyAlign = TD->getTypeSize(CastElTy);
4259 if (CastElTyAlign < AllocElTyAlign) return 0;
4260
Chris Lattner46705b22005-10-24 06:35:18 +00004261 // If the allocation has multiple uses, only promote it if we are strictly
4262 // increasing the alignment of the resultant allocation. If we keep it the
4263 // same, we open the door to infinite loops of various kinds.
4264 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
4265
Chris Lattner216be912005-10-24 06:03:58 +00004266 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
4267 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattnerbb171802005-10-27 05:53:56 +00004268 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00004269
Chris Lattner8270c332005-10-29 03:19:53 +00004270 // See if we can satisfy the modulus by pulling a scale out of the array
4271 // size argument.
Chris Lattner8f663e82005-10-29 04:36:15 +00004272 unsigned ArraySizeScale, ArrayOffset;
4273 Value *NumElements = // See if the array size is a decomposable linear expr.
4274 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
4275
Chris Lattner8270c332005-10-29 03:19:53 +00004276 // If we can now satisfy the modulus, by using a non-1 scale, we really can
4277 // do the xform.
Chris Lattner8f663e82005-10-29 04:36:15 +00004278 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
4279 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattnerb3ecf962005-10-27 06:12:00 +00004280
Chris Lattner8270c332005-10-29 03:19:53 +00004281 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
4282 Value *Amt = 0;
4283 if (Scale == 1) {
4284 Amt = NumElements;
4285 } else {
4286 Amt = ConstantUInt::get(Type::UIntTy, Scale);
4287 if (ConstantUInt *CI = dyn_cast<ConstantUInt>(NumElements))
4288 Amt = ConstantExpr::getMul(CI, cast<ConstantUInt>(Amt));
4289 else if (Scale != 1) {
4290 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
4291 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattnerb3ecf962005-10-27 06:12:00 +00004292 }
Chris Lattnerbb171802005-10-27 05:53:56 +00004293 }
4294
Chris Lattner8f663e82005-10-29 04:36:15 +00004295 if (unsigned Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
4296 Value *Off = ConstantUInt::get(Type::UIntTy, Offset);
4297 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
4298 Amt = InsertNewInstBefore(Tmp, AI);
4299 }
4300
Chris Lattner216be912005-10-24 06:03:58 +00004301 std::string Name = AI.getName(); AI.setName("");
4302 AllocationInst *New;
4303 if (isa<MallocInst>(AI))
Nate Begeman848622f2005-11-05 09:21:28 +00004304 New = new MallocInst(CastElTy, Amt, AI.getAlignment(), Name);
Chris Lattner216be912005-10-24 06:03:58 +00004305 else
Nate Begeman848622f2005-11-05 09:21:28 +00004306 New = new AllocaInst(CastElTy, Amt, AI.getAlignment(), Name);
Chris Lattner216be912005-10-24 06:03:58 +00004307 InsertNewInstBefore(New, AI);
Chris Lattner46705b22005-10-24 06:35:18 +00004308
4309 // If the allocation has multiple uses, insert a cast and change all things
4310 // that used it to use the new cast. This will also hack on CI, but it will
4311 // die soon.
4312 if (!AI.hasOneUse()) {
4313 AddUsesToWorkList(AI);
4314 CastInst *NewCast = new CastInst(New, AI.getType(), "tmpcast");
4315 InsertNewInstBefore(NewCast, AI);
4316 AI.replaceAllUsesWith(NewCast);
4317 }
Chris Lattner216be912005-10-24 06:03:58 +00004318 return ReplaceInstUsesWith(CI, New);
4319}
4320
4321
Chris Lattner48a44f72002-05-02 17:06:02 +00004322// CastInst simplification
Chris Lattner260ab202002-04-18 17:39:14 +00004323//
Chris Lattner113f4f42002-06-25 16:13:24 +00004324Instruction *InstCombiner::visitCastInst(CastInst &CI) {
Chris Lattner55d4bda2003-06-23 21:59:52 +00004325 Value *Src = CI.getOperand(0);
4326
Chris Lattner48a44f72002-05-02 17:06:02 +00004327 // If the user is casting a value to the same type, eliminate this cast
4328 // instruction...
Chris Lattner55d4bda2003-06-23 21:59:52 +00004329 if (CI.getType() == Src->getType())
4330 return ReplaceInstUsesWith(CI, Src);
Chris Lattner48a44f72002-05-02 17:06:02 +00004331
Chris Lattner81a7a232004-10-16 18:11:37 +00004332 if (isa<UndefValue>(Src)) // cast undef -> undef
4333 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
4334
Chris Lattner48a44f72002-05-02 17:06:02 +00004335 // If casting the result of another cast instruction, try to eliminate this
4336 // one!
4337 //
Chris Lattner86102b82005-01-01 16:22:27 +00004338 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
4339 Value *A = CSrc->getOperand(0);
4340 if (isEliminableCastOfCast(A->getType(), CSrc->getType(),
4341 CI.getType(), TD)) {
Chris Lattner48a44f72002-05-02 17:06:02 +00004342 // This instruction now refers directly to the cast's src operand. This
4343 // has a good chance of making CSrc dead.
Chris Lattner113f4f42002-06-25 16:13:24 +00004344 CI.setOperand(0, CSrc->getOperand(0));
4345 return &CI;
Chris Lattner48a44f72002-05-02 17:06:02 +00004346 }
4347
Chris Lattner650b6da2002-08-02 20:00:25 +00004348 // If this is an A->B->A cast, and we are dealing with integral types, try
4349 // to convert this into a logical 'and' instruction.
4350 //
Misha Brukmanb1c93172005-04-21 23:48:37 +00004351 if (A->getType()->isInteger() &&
Chris Lattnerb0b412e2002-09-03 01:08:28 +00004352 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
Chris Lattner86102b82005-01-01 16:22:27 +00004353 CSrc->getType()->isUnsigned() && // B->A cast must zero extend
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004354 CSrc->getType()->getPrimitiveSizeInBits() <
4355 CI.getType()->getPrimitiveSizeInBits()&&
4356 A->getType()->getPrimitiveSizeInBits() ==
4357 CI.getType()->getPrimitiveSizeInBits()) {
Chris Lattner650b6da2002-08-02 20:00:25 +00004358 assert(CSrc->getType() != Type::ULongTy &&
4359 "Cannot have type bigger than ulong!");
Chris Lattner77defba2006-02-07 07:00:41 +00004360 uint64_t AndValue = CSrc->getType()->getIntegralTypeMask();
Chris Lattner86102b82005-01-01 16:22:27 +00004361 Constant *AndOp = ConstantUInt::get(A->getType()->getUnsignedVersion(),
4362 AndValue);
4363 AndOp = ConstantExpr::getCast(AndOp, A->getType());
4364 Instruction *And = BinaryOperator::createAnd(CSrc->getOperand(0), AndOp);
4365 if (And->getType() != CI.getType()) {
4366 And->setName(CSrc->getName()+".mask");
4367 InsertNewInstBefore(And, CI);
4368 And = new CastInst(And, CI.getType());
4369 }
4370 return And;
Chris Lattner650b6da2002-08-02 20:00:25 +00004371 }
4372 }
Chris Lattner2590e512006-02-07 06:56:34 +00004373
Chris Lattner03841652004-05-25 04:29:21 +00004374 // If this is a cast to bool, turn it into the appropriate setne instruction.
4375 if (CI.getType() == Type::BoolTy)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004376 return BinaryOperator::createSetNE(CI.getOperand(0),
Chris Lattner03841652004-05-25 04:29:21 +00004377 Constant::getNullValue(CI.getOperand(0)->getType()));
4378
Chris Lattner2590e512006-02-07 06:56:34 +00004379 // See if we can simplify any instructions used by the LHS whose sole
4380 // purpose is to compute bits we don't care about.
4381 if (CI.getType()->isInteger() && CI.getOperand(0)->getType()->isIntegral() &&
4382 SimplifyDemandedBits(&CI, CI.getType()->getIntegralTypeMask()))
4383 return &CI;
4384
Chris Lattnerd0d51602003-06-21 23:12:02 +00004385 // If casting the result of a getelementptr instruction with no offset, turn
4386 // this into a cast of the original pointer!
4387 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00004388 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattnerd0d51602003-06-21 23:12:02 +00004389 bool AllZeroOperands = true;
4390 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
4391 if (!isa<Constant>(GEP->getOperand(i)) ||
4392 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
4393 AllZeroOperands = false;
4394 break;
4395 }
4396 if (AllZeroOperands) {
4397 CI.setOperand(0, GEP->getOperand(0));
4398 return &CI;
4399 }
4400 }
4401
Chris Lattnerf4ad1652003-11-02 05:57:39 +00004402 // If we are casting a malloc or alloca to a pointer to a type of the same
4403 // size, rewrite the allocation instruction to allocate the "right" type.
4404 //
4405 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattner216be912005-10-24 06:03:58 +00004406 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
4407 return V;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00004408
Chris Lattner86102b82005-01-01 16:22:27 +00004409 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
4410 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
4411 return NV;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00004412 if (isa<PHINode>(Src))
4413 if (Instruction *NV = FoldOpIntoPhi(CI))
4414 return NV;
4415
Chris Lattnerdfae8be2003-07-24 17:35:25 +00004416 // If the source value is an instruction with only this use, we can attempt to
4417 // propagate the cast into the instruction. Also, only handle integral types
4418 // for now.
4419 if (Instruction *SrcI = dyn_cast<Instruction>(Src))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00004420 if (SrcI->hasOneUse() && Src->getType()->isIntegral() &&
Chris Lattnerdfae8be2003-07-24 17:35:25 +00004421 CI.getType()->isInteger()) { // Don't mess with casts to bool here
4422 const Type *DestTy = CI.getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004423 unsigned SrcBitSize = Src->getType()->getPrimitiveSizeInBits();
4424 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
Chris Lattnerdfae8be2003-07-24 17:35:25 +00004425
4426 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
4427 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
4428
4429 switch (SrcI->getOpcode()) {
4430 case Instruction::Add:
4431 case Instruction::Mul:
4432 case Instruction::And:
4433 case Instruction::Or:
4434 case Instruction::Xor:
4435 // If we are discarding information, or just changing the sign, rewrite.
4436 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
4437 // Don't insert two casts if they cannot be eliminated. We allow two
4438 // casts to be inserted if the sizes are the same. This could only be
4439 // converting signedness, which is a noop.
Chris Lattner11ffd592004-07-20 05:21:00 +00004440 if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy,TD) ||
4441 !ValueRequiresCast(Op0, DestTy, TD)) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00004442 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
4443 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
4444 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
4445 ->getOpcode(), Op0c, Op1c);
4446 }
4447 }
Chris Lattner72086162005-05-06 02:07:39 +00004448
4449 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
4450 if (SrcBitSize == 1 && SrcI->getOpcode() == Instruction::Xor &&
4451 Op1 == ConstantBool::True &&
4452 (!Op0->hasOneUse() || !isa<SetCondInst>(Op0))) {
4453 Value *New = InsertOperandCastBefore(Op0, DestTy, &CI);
4454 return BinaryOperator::createXor(New,
4455 ConstantInt::get(CI.getType(), 1));
4456 }
Chris Lattnerdfae8be2003-07-24 17:35:25 +00004457 break;
4458 case Instruction::Shl:
4459 // Allow changing the sign of the source operand. Do not allow changing
4460 // the size of the shift, UNLESS the shift amount is a constant. We
4461 // mush not change variable sized shifts to a smaller size, because it
4462 // is undefined to shift more bits out than exist in the value.
4463 if (DestBitSize == SrcBitSize ||
4464 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
4465 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
4466 return new ShiftInst(Instruction::Shl, Op0c, Op1);
4467 }
4468 break;
Chris Lattner87380412005-05-06 04:18:52 +00004469 case Instruction::Shr:
4470 // If this is a signed shr, and if all bits shifted in are about to be
4471 // truncated off, turn it into an unsigned shr to allow greater
4472 // simplifications.
4473 if (DestBitSize < SrcBitSize && Src->getType()->isSigned() &&
4474 isa<ConstantInt>(Op1)) {
4475 unsigned ShiftAmt = cast<ConstantUInt>(Op1)->getValue();
4476 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
4477 // Convert to unsigned.
4478 Value *N1 = InsertOperandCastBefore(Op0,
4479 Op0->getType()->getUnsignedVersion(), &CI);
4480 // Insert the new shift, which is now unsigned.
4481 N1 = InsertNewInstBefore(new ShiftInst(Instruction::Shr, N1,
4482 Op1, Src->getName()), CI);
4483 return new CastInst(N1, CI.getType());
4484 }
4485 }
4486 break;
4487
Chris Lattner809dfac2005-05-04 19:10:26 +00004488 case Instruction::SetNE:
Chris Lattner809dfac2005-05-04 19:10:26 +00004489 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4c2d3782005-05-06 01:53:19 +00004490 if (Op1C->getRawValue() == 0) {
4491 // If the input only has the low bit set, simplify directly.
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00004492 Constant *Not1 =
Chris Lattner809dfac2005-05-04 19:10:26 +00004493 ConstantExpr::getNot(ConstantInt::get(Op0->getType(), 1));
Chris Lattner4c2d3782005-05-06 01:53:19 +00004494 // cast (X != 0) to int --> X if X&~1 == 0
Chris Lattnerc3ebf402006-02-07 07:27:52 +00004495 if (MaskedValueIsZero(Op0,
4496 cast<ConstantIntegral>(Not1)->getZExtValue())) {
Chris Lattner809dfac2005-05-04 19:10:26 +00004497 if (CI.getType() == Op0->getType())
4498 return ReplaceInstUsesWith(CI, Op0);
4499 else
4500 return new CastInst(Op0, CI.getType());
4501 }
Chris Lattner4c2d3782005-05-06 01:53:19 +00004502
4503 // If the input is an and with a single bit, shift then simplify.
4504 ConstantInt *AndRHS;
4505 if (match(Op0, m_And(m_Value(), m_ConstantInt(AndRHS))))
4506 if (AndRHS->getRawValue() &&
4507 (AndRHS->getRawValue() & (AndRHS->getRawValue()-1)) == 0) {
Chris Lattner22d00a82005-08-02 19:16:58 +00004508 unsigned ShiftAmt = Log2_64(AndRHS->getRawValue());
Chris Lattner4c2d3782005-05-06 01:53:19 +00004509 // Perform an unsigned shr by shiftamt. Convert input to
4510 // unsigned if it is signed.
4511 Value *In = Op0;
4512 if (In->getType()->isSigned())
4513 In = InsertNewInstBefore(new CastInst(In,
4514 In->getType()->getUnsignedVersion(), In->getName()),CI);
4515 // Insert the shift to put the result in the low bit.
4516 In = InsertNewInstBefore(new ShiftInst(Instruction::Shr, In,
4517 ConstantInt::get(Type::UByteTy, ShiftAmt),
4518 In->getName()+".lobit"), CI);
Chris Lattner4c2d3782005-05-06 01:53:19 +00004519 if (CI.getType() == In->getType())
4520 return ReplaceInstUsesWith(CI, In);
4521 else
4522 return new CastInst(In, CI.getType());
4523 }
4524 }
4525 }
4526 break;
4527 case Instruction::SetEQ:
4528 // We if we are just checking for a seteq of a single bit and casting it
4529 // to an integer. If so, shift the bit to the appropriate place then
4530 // cast to integer to avoid the comparison.
4531 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
4532 // Is Op1C a power of two or zero?
4533 if ((Op1C->getRawValue() & Op1C->getRawValue()-1) == 0) {
4534 // cast (X == 1) to int -> X iff X has only the low bit set.
4535 if (Op1C->getRawValue() == 1) {
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00004536 Constant *Not1 =
Chris Lattner4c2d3782005-05-06 01:53:19 +00004537 ConstantExpr::getNot(ConstantInt::get(Op0->getType(), 1));
Chris Lattnerc3ebf402006-02-07 07:27:52 +00004538 if (MaskedValueIsZero(Op0,
4539 cast<ConstantIntegral>(Not1)->getZExtValue())) {
Chris Lattner4c2d3782005-05-06 01:53:19 +00004540 if (CI.getType() == Op0->getType())
4541 return ReplaceInstUsesWith(CI, Op0);
4542 else
4543 return new CastInst(Op0, CI.getType());
4544 }
4545 }
Chris Lattner809dfac2005-05-04 19:10:26 +00004546 }
4547 }
4548 break;
Chris Lattnerdfae8be2003-07-24 17:35:25 +00004549 }
4550 }
Chris Lattnerbb171802005-10-27 05:53:56 +00004551
Chris Lattner260ab202002-04-18 17:39:14 +00004552 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +00004553}
4554
Chris Lattner56e4d3d2004-04-09 23:46:01 +00004555/// GetSelectFoldableOperands - We want to turn code that looks like this:
4556/// %C = or %A, %B
4557/// %D = select %cond, %C, %A
4558/// into:
4559/// %C = select %cond, %B, 0
4560/// %D = or %A, %C
4561///
4562/// Assuming that the specified instruction is an operand to the select, return
4563/// a bitmask indicating which operands of this instruction are foldable if they
4564/// equal the other incoming value of the select.
4565///
4566static unsigned GetSelectFoldableOperands(Instruction *I) {
4567 switch (I->getOpcode()) {
4568 case Instruction::Add:
4569 case Instruction::Mul:
4570 case Instruction::And:
4571 case Instruction::Or:
4572 case Instruction::Xor:
4573 return 3; // Can fold through either operand.
4574 case Instruction::Sub: // Can only fold on the amount subtracted.
4575 case Instruction::Shl: // Can only fold on the shift amount.
4576 case Instruction::Shr:
Misha Brukmanb1c93172005-04-21 23:48:37 +00004577 return 1;
Chris Lattner56e4d3d2004-04-09 23:46:01 +00004578 default:
4579 return 0; // Cannot fold
4580 }
4581}
4582
4583/// GetSelectFoldableConstant - For the same transformation as the previous
4584/// function, return the identity constant that goes into the select.
4585static Constant *GetSelectFoldableConstant(Instruction *I) {
4586 switch (I->getOpcode()) {
4587 default: assert(0 && "This cannot happen!"); abort();
4588 case Instruction::Add:
4589 case Instruction::Sub:
4590 case Instruction::Or:
4591 case Instruction::Xor:
4592 return Constant::getNullValue(I->getType());
4593 case Instruction::Shl:
4594 case Instruction::Shr:
4595 return Constant::getNullValue(Type::UByteTy);
4596 case Instruction::And:
4597 return ConstantInt::getAllOnesValue(I->getType());
4598 case Instruction::Mul:
4599 return ConstantInt::get(I->getType(), 1);
4600 }
4601}
4602
Chris Lattner411336f2005-01-19 21:50:18 +00004603/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
4604/// have the same opcode and only one use each. Try to simplify this.
4605Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
4606 Instruction *FI) {
4607 if (TI->getNumOperands() == 1) {
4608 // If this is a non-volatile load or a cast from the same type,
4609 // merge.
4610 if (TI->getOpcode() == Instruction::Cast) {
4611 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
4612 return 0;
4613 } else {
4614 return 0; // unknown unary op.
4615 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004616
Chris Lattner411336f2005-01-19 21:50:18 +00004617 // Fold this by inserting a select from the input values.
4618 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
4619 FI->getOperand(0), SI.getName()+".v");
4620 InsertNewInstBefore(NewSI, SI);
4621 return new CastInst(NewSI, TI->getType());
4622 }
4623
4624 // Only handle binary operators here.
4625 if (!isa<ShiftInst>(TI) && !isa<BinaryOperator>(TI))
4626 return 0;
4627
4628 // Figure out if the operations have any operands in common.
4629 Value *MatchOp, *OtherOpT, *OtherOpF;
4630 bool MatchIsOpZero;
4631 if (TI->getOperand(0) == FI->getOperand(0)) {
4632 MatchOp = TI->getOperand(0);
4633 OtherOpT = TI->getOperand(1);
4634 OtherOpF = FI->getOperand(1);
4635 MatchIsOpZero = true;
4636 } else if (TI->getOperand(1) == FI->getOperand(1)) {
4637 MatchOp = TI->getOperand(1);
4638 OtherOpT = TI->getOperand(0);
4639 OtherOpF = FI->getOperand(0);
4640 MatchIsOpZero = false;
4641 } else if (!TI->isCommutative()) {
4642 return 0;
4643 } else if (TI->getOperand(0) == FI->getOperand(1)) {
4644 MatchOp = TI->getOperand(0);
4645 OtherOpT = TI->getOperand(1);
4646 OtherOpF = FI->getOperand(0);
4647 MatchIsOpZero = true;
4648 } else if (TI->getOperand(1) == FI->getOperand(0)) {
4649 MatchOp = TI->getOperand(1);
4650 OtherOpT = TI->getOperand(0);
4651 OtherOpF = FI->getOperand(1);
4652 MatchIsOpZero = true;
4653 } else {
4654 return 0;
4655 }
4656
4657 // If we reach here, they do have operations in common.
4658 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
4659 OtherOpF, SI.getName()+".v");
4660 InsertNewInstBefore(NewSI, SI);
4661
4662 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
4663 if (MatchIsOpZero)
4664 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
4665 else
4666 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
4667 } else {
4668 if (MatchIsOpZero)
4669 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), MatchOp, NewSI);
4670 else
4671 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), NewSI, MatchOp);
4672 }
4673}
4674
Chris Lattnerb909e8b2004-03-12 05:52:32 +00004675Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattner533bc492004-03-30 19:37:13 +00004676 Value *CondVal = SI.getCondition();
4677 Value *TrueVal = SI.getTrueValue();
4678 Value *FalseVal = SI.getFalseValue();
4679
4680 // select true, X, Y -> X
4681 // select false, X, Y -> Y
4682 if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
Chris Lattnerb909e8b2004-03-12 05:52:32 +00004683 if (C == ConstantBool::True)
Chris Lattner533bc492004-03-30 19:37:13 +00004684 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerb909e8b2004-03-12 05:52:32 +00004685 else {
4686 assert(C == ConstantBool::False);
Chris Lattner533bc492004-03-30 19:37:13 +00004687 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattnerb909e8b2004-03-12 05:52:32 +00004688 }
Chris Lattner533bc492004-03-30 19:37:13 +00004689
4690 // select C, X, X -> X
4691 if (TrueVal == FalseVal)
4692 return ReplaceInstUsesWith(SI, TrueVal);
4693
Chris Lattner81a7a232004-10-16 18:11:37 +00004694 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
4695 return ReplaceInstUsesWith(SI, FalseVal);
4696 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
4697 return ReplaceInstUsesWith(SI, TrueVal);
4698 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
4699 if (isa<Constant>(TrueVal))
4700 return ReplaceInstUsesWith(SI, TrueVal);
4701 else
4702 return ReplaceInstUsesWith(SI, FalseVal);
4703 }
4704
Chris Lattner1c631e82004-04-08 04:43:23 +00004705 if (SI.getType() == Type::BoolTy)
4706 if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
4707 if (C == ConstantBool::True) {
4708 // Change: A = select B, true, C --> A = or B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004709 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00004710 } else {
4711 // Change: A = select B, false, C --> A = and !B, C
4712 Value *NotCond =
4713 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
4714 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004715 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00004716 }
4717 } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
4718 if (C == ConstantBool::False) {
4719 // Change: A = select B, C, false --> A = and B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004720 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00004721 } else {
4722 // Change: A = select B, C, true --> A = or !B, C
4723 Value *NotCond =
4724 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
4725 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004726 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00004727 }
4728 }
4729
Chris Lattner183b3362004-04-09 19:05:30 +00004730 // Selecting between two integer constants?
4731 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
4732 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
4733 // select C, 1, 0 -> cast C to int
4734 if (FalseValC->isNullValue() && TrueValC->getRawValue() == 1) {
4735 return new CastInst(CondVal, SI.getType());
4736 } else if (TrueValC->isNullValue() && FalseValC->getRawValue() == 1) {
4737 // select C, 0, 1 -> cast !C to int
4738 Value *NotCond =
4739 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattnercf7baf32004-04-09 18:19:44 +00004740 "not."+CondVal->getName()), SI);
Chris Lattner183b3362004-04-09 19:05:30 +00004741 return new CastInst(NotCond, SI.getType());
Chris Lattnercf7baf32004-04-09 18:19:44 +00004742 }
Chris Lattner35167c32004-06-09 07:59:58 +00004743
4744 // If one of the constants is zero (we know they can't both be) and we
4745 // have a setcc instruction with zero, and we have an 'and' with the
4746 // non-constant value, eliminate this whole mess. This corresponds to
4747 // cases like this: ((X & 27) ? 27 : 0)
4748 if (TrueValC->isNullValue() || FalseValC->isNullValue())
4749 if (Instruction *IC = dyn_cast<Instruction>(SI.getCondition()))
4750 if ((IC->getOpcode() == Instruction::SetEQ ||
4751 IC->getOpcode() == Instruction::SetNE) &&
4752 isa<ConstantInt>(IC->getOperand(1)) &&
4753 cast<Constant>(IC->getOperand(1))->isNullValue())
4754 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
4755 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00004756 isa<ConstantInt>(ICA->getOperand(1)) &&
4757 (ICA->getOperand(1) == TrueValC ||
4758 ICA->getOperand(1) == FalseValC) &&
Chris Lattner35167c32004-06-09 07:59:58 +00004759 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
4760 // Okay, now we know that everything is set up, we just don't
4761 // know whether we have a setne or seteq and whether the true or
4762 // false val is the zero.
4763 bool ShouldNotVal = !TrueValC->isNullValue();
4764 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
4765 Value *V = ICA;
4766 if (ShouldNotVal)
4767 V = InsertNewInstBefore(BinaryOperator::create(
4768 Instruction::Xor, V, ICA->getOperand(1)), SI);
4769 return ReplaceInstUsesWith(SI, V);
4770 }
Chris Lattner533bc492004-03-30 19:37:13 +00004771 }
Chris Lattner623fba12004-04-10 22:21:27 +00004772
4773 // See if we are selecting two values based on a comparison of the two values.
4774 if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
4775 if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
4776 // Transform (X == Y) ? X : Y -> Y
4777 if (SCI->getOpcode() == Instruction::SetEQ)
4778 return ReplaceInstUsesWith(SI, FalseVal);
4779 // Transform (X != Y) ? X : Y -> X
4780 if (SCI->getOpcode() == Instruction::SetNE)
4781 return ReplaceInstUsesWith(SI, TrueVal);
4782 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
4783
4784 } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
4785 // Transform (X == Y) ? Y : X -> X
4786 if (SCI->getOpcode() == Instruction::SetEQ)
Chris Lattner24cf0202004-04-11 01:39:19 +00004787 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattner623fba12004-04-10 22:21:27 +00004788 // Transform (X != Y) ? Y : X -> Y
4789 if (SCI->getOpcode() == Instruction::SetNE)
Chris Lattner24cf0202004-04-11 01:39:19 +00004790 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner623fba12004-04-10 22:21:27 +00004791 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
4792 }
4793 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004794
Chris Lattnera04c9042005-01-13 22:52:24 +00004795 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
4796 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
4797 if (TI->hasOneUse() && FI->hasOneUse()) {
4798 bool isInverse = false;
4799 Instruction *AddOp = 0, *SubOp = 0;
4800
Chris Lattner411336f2005-01-19 21:50:18 +00004801 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
4802 if (TI->getOpcode() == FI->getOpcode())
4803 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
4804 return IV;
4805
4806 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
4807 // even legal for FP.
Chris Lattnera04c9042005-01-13 22:52:24 +00004808 if (TI->getOpcode() == Instruction::Sub &&
4809 FI->getOpcode() == Instruction::Add) {
4810 AddOp = FI; SubOp = TI;
4811 } else if (FI->getOpcode() == Instruction::Sub &&
4812 TI->getOpcode() == Instruction::Add) {
4813 AddOp = TI; SubOp = FI;
4814 }
4815
4816 if (AddOp) {
4817 Value *OtherAddOp = 0;
4818 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
4819 OtherAddOp = AddOp->getOperand(1);
4820 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
4821 OtherAddOp = AddOp->getOperand(0);
4822 }
4823
4824 if (OtherAddOp) {
4825 // So at this point we know we have:
4826 // select C, (add X, Y), (sub X, ?)
4827 // We can do the transform profitably if either 'Y' = '?' or '?' is
4828 // a constant.
4829 if (SubOp->getOperand(1) == AddOp ||
4830 isa<Constant>(SubOp->getOperand(1))) {
4831 Value *NegVal;
4832 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
4833 NegVal = ConstantExpr::getNeg(C);
4834 } else {
4835 NegVal = InsertNewInstBefore(
4836 BinaryOperator::createNeg(SubOp->getOperand(1)), SI);
4837 }
4838
Chris Lattner51726c42005-01-14 17:35:12 +00004839 Value *NewTrueOp = OtherAddOp;
Chris Lattnera04c9042005-01-13 22:52:24 +00004840 Value *NewFalseOp = NegVal;
4841 if (AddOp != TI)
4842 std::swap(NewTrueOp, NewFalseOp);
4843 Instruction *NewSel =
4844 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
Misha Brukmanb1c93172005-04-21 23:48:37 +00004845
Chris Lattnera04c9042005-01-13 22:52:24 +00004846 NewSel = InsertNewInstBefore(NewSel, SI);
Chris Lattner51726c42005-01-14 17:35:12 +00004847 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
Chris Lattnera04c9042005-01-13 22:52:24 +00004848 }
4849 }
4850 }
4851 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004852
Chris Lattner56e4d3d2004-04-09 23:46:01 +00004853 // See if we can fold the select into one of our operands.
4854 if (SI.getType()->isInteger()) {
4855 // See the comment above GetSelectFoldableOperands for a description of the
4856 // transformation we are doing here.
4857 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
4858 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
4859 !isa<Constant>(FalseVal))
4860 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
4861 unsigned OpToFold = 0;
4862 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
4863 OpToFold = 1;
4864 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
4865 OpToFold = 2;
4866 }
4867
4868 if (OpToFold) {
4869 Constant *C = GetSelectFoldableConstant(TVI);
4870 std::string Name = TVI->getName(); TVI->setName("");
4871 Instruction *NewSel =
4872 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
4873 Name);
4874 InsertNewInstBefore(NewSel, SI);
4875 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
4876 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
4877 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
4878 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
4879 else {
4880 assert(0 && "Unknown instruction!!");
4881 }
4882 }
4883 }
Chris Lattner6862fbd2004-09-29 17:40:11 +00004884
Chris Lattner56e4d3d2004-04-09 23:46:01 +00004885 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
4886 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
4887 !isa<Constant>(TrueVal))
4888 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
4889 unsigned OpToFold = 0;
4890 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
4891 OpToFold = 1;
4892 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
4893 OpToFold = 2;
4894 }
4895
4896 if (OpToFold) {
4897 Constant *C = GetSelectFoldableConstant(FVI);
4898 std::string Name = FVI->getName(); FVI->setName("");
4899 Instruction *NewSel =
4900 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
4901 Name);
4902 InsertNewInstBefore(NewSel, SI);
4903 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
4904 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
4905 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
4906 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
4907 else {
4908 assert(0 && "Unknown instruction!!");
4909 }
4910 }
4911 }
4912 }
Chris Lattnerd6f636a2005-04-24 07:30:14 +00004913
4914 if (BinaryOperator::isNot(CondVal)) {
4915 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
4916 SI.setOperand(1, FalseVal);
4917 SI.setOperand(2, TrueVal);
4918 return &SI;
4919 }
4920
Chris Lattnerb909e8b2004-03-12 05:52:32 +00004921 return 0;
4922}
4923
4924
Chris Lattnerc66b2232006-01-13 20:11:04 +00004925/// visitCallInst - CallInst simplification. This mostly only handles folding
4926/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
4927/// the heavy lifting.
4928///
Chris Lattner970c33a2003-06-19 17:00:31 +00004929Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattnerc66b2232006-01-13 20:11:04 +00004930 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
4931 if (!II) return visitCallSite(&CI);
4932
Chris Lattner51ea1272004-02-28 05:22:00 +00004933 // Intrinsics cannot occur in an invoke, so handle them here instead of in
4934 // visitCallSite.
Chris Lattnerc66b2232006-01-13 20:11:04 +00004935 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner00648e12004-10-12 04:52:52 +00004936 bool Changed = false;
4937
4938 // memmove/cpy/set of zero bytes is a noop.
4939 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
4940 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
4941
4942 // FIXME: Increase alignment here.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004943
Chris Lattner00648e12004-10-12 04:52:52 +00004944 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
4945 if (CI->getRawValue() == 1) {
4946 // Replace the instruction with just byte operations. We would
4947 // transform other cases to loads/stores, but we don't know if
4948 // alignment is sufficient.
4949 }
Chris Lattner51ea1272004-02-28 05:22:00 +00004950 }
4951
Chris Lattner00648e12004-10-12 04:52:52 +00004952 // If we have a memmove and the source operation is a constant global,
4953 // then the source and dest pointers can't alias, so we can change this
4954 // into a call to memcpy.
Chris Lattnerc66b2232006-01-13 20:11:04 +00004955 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II))
Chris Lattner00648e12004-10-12 04:52:52 +00004956 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
4957 if (GVSrc->isConstant()) {
4958 Module *M = CI.getParent()->getParent()->getParent();
4959 Function *MemCpy = M->getOrInsertFunction("llvm.memcpy",
4960 CI.getCalledFunction()->getFunctionType());
4961 CI.setOperand(0, MemCpy);
4962 Changed = true;
4963 }
4964
Chris Lattnerc66b2232006-01-13 20:11:04 +00004965 if (Changed) return II;
4966 } else if (DbgStopPointInst *SPI = dyn_cast<DbgStopPointInst>(II)) {
Chris Lattner95307542004-11-18 21:41:39 +00004967 // If this stoppoint is at the same source location as the previous
4968 // stoppoint in the chain, it is not needed.
4969 if (DbgStopPointInst *PrevSPI =
4970 dyn_cast<DbgStopPointInst>(SPI->getChain()))
4971 if (SPI->getLineNo() == PrevSPI->getLineNo() &&
4972 SPI->getColNo() == PrevSPI->getColNo()) {
4973 SPI->replaceAllUsesWith(PrevSPI);
4974 return EraseInstFromFunction(CI);
4975 }
Chris Lattner503221f2006-01-13 21:28:09 +00004976 } else {
4977 switch (II->getIntrinsicID()) {
4978 default: break;
4979 case Intrinsic::stackrestore: {
4980 // If the save is right next to the restore, remove the restore. This can
4981 // happen when variable allocas are DCE'd.
4982 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
4983 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
4984 BasicBlock::iterator BI = SS;
4985 if (&*++BI == II)
4986 return EraseInstFromFunction(CI);
4987 }
4988 }
4989
4990 // If the stack restore is in a return/unwind block and if there are no
4991 // allocas or calls between the restore and the return, nuke the restore.
4992 TerminatorInst *TI = II->getParent()->getTerminator();
4993 if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
4994 BasicBlock::iterator BI = II;
4995 bool CannotRemove = false;
4996 for (++BI; &*BI != TI; ++BI) {
4997 if (isa<AllocaInst>(BI) ||
4998 (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
4999 CannotRemove = true;
5000 break;
5001 }
5002 }
5003 if (!CannotRemove)
5004 return EraseInstFromFunction(CI);
5005 }
5006 break;
5007 }
5008 }
Chris Lattner00648e12004-10-12 04:52:52 +00005009 }
5010
Chris Lattnerc66b2232006-01-13 20:11:04 +00005011 return visitCallSite(II);
Chris Lattner970c33a2003-06-19 17:00:31 +00005012}
5013
5014// InvokeInst simplification
5015//
5016Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattneraec3d942003-10-07 22:32:43 +00005017 return visitCallSite(&II);
Chris Lattner970c33a2003-06-19 17:00:31 +00005018}
5019
Chris Lattneraec3d942003-10-07 22:32:43 +00005020// visitCallSite - Improvements for call and invoke instructions.
5021//
5022Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00005023 bool Changed = false;
5024
5025 // If the callee is a constexpr cast of a function, attempt to move the cast
5026 // to the arguments of the call/invoke.
Chris Lattneraec3d942003-10-07 22:32:43 +00005027 if (transformConstExprCastCall(CS)) return 0;
5028
Chris Lattner75b4d1d2003-10-07 22:54:13 +00005029 Value *Callee = CS.getCalledValue();
Chris Lattner81a7a232004-10-16 18:11:37 +00005030
Chris Lattner61d9d812005-05-13 07:09:09 +00005031 if (Function *CalleeF = dyn_cast<Function>(Callee))
5032 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
5033 Instruction *OldCall = CS.getInstruction();
5034 // If the call and callee calling conventions don't match, this call must
5035 // be unreachable, as the call is undefined.
5036 new StoreInst(ConstantBool::True,
5037 UndefValue::get(PointerType::get(Type::BoolTy)), OldCall);
5038 if (!OldCall->use_empty())
5039 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
5040 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
5041 return EraseInstFromFunction(*OldCall);
5042 return 0;
5043 }
5044
Chris Lattner8ba9ec92004-10-18 02:59:09 +00005045 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
5046 // This instruction is not reachable, just remove it. We insert a store to
5047 // undef so that we know that this code is not reachable, despite the fact
5048 // that we can't modify the CFG here.
5049 new StoreInst(ConstantBool::True,
5050 UndefValue::get(PointerType::get(Type::BoolTy)),
5051 CS.getInstruction());
5052
5053 if (!CS.getInstruction()->use_empty())
5054 CS.getInstruction()->
5055 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
5056
5057 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
5058 // Don't break the CFG, insert a dummy cond branch.
5059 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
5060 ConstantBool::True, II);
Chris Lattner81a7a232004-10-16 18:11:37 +00005061 }
Chris Lattner8ba9ec92004-10-18 02:59:09 +00005062 return EraseInstFromFunction(*CS.getInstruction());
5063 }
Chris Lattner81a7a232004-10-16 18:11:37 +00005064
Chris Lattner75b4d1d2003-10-07 22:54:13 +00005065 const PointerType *PTy = cast<PointerType>(Callee->getType());
5066 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
5067 if (FTy->isVarArg()) {
5068 // See if we can optimize any arguments passed through the varargs area of
5069 // the call.
5070 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
5071 E = CS.arg_end(); I != E; ++I)
5072 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
5073 // If this cast does not effect the value passed through the varargs
5074 // area, we can eliminate the use of the cast.
5075 Value *Op = CI->getOperand(0);
5076 if (CI->getType()->isLosslesslyConvertibleTo(Op->getType())) {
5077 *I = Op;
5078 Changed = true;
5079 }
5080 }
5081 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005082
Chris Lattner75b4d1d2003-10-07 22:54:13 +00005083 return Changed ? CS.getInstruction() : 0;
Chris Lattneraec3d942003-10-07 22:32:43 +00005084}
5085
Chris Lattner970c33a2003-06-19 17:00:31 +00005086// transformConstExprCastCall - If the callee is a constexpr cast of a function,
5087// attempt to move the cast to the arguments of the call/invoke.
5088//
5089bool InstCombiner::transformConstExprCastCall(CallSite CS) {
5090 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
5091 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Chris Lattnerf3edc492004-07-18 18:59:44 +00005092 if (CE->getOpcode() != Instruction::Cast || !isa<Function>(CE->getOperand(0)))
Chris Lattner970c33a2003-06-19 17:00:31 +00005093 return false;
Reid Spencer87436872004-07-18 00:38:32 +00005094 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner970c33a2003-06-19 17:00:31 +00005095 Instruction *Caller = CS.getInstruction();
5096
5097 // Okay, this is a cast from a function to a different type. Unless doing so
5098 // would cause a type conversion of one of our arguments, change this call to
5099 // be a direct call with arguments casted to the appropriate types.
5100 //
5101 const FunctionType *FT = Callee->getFunctionType();
5102 const Type *OldRetTy = Caller->getType();
5103
Chris Lattner1f7942f2004-01-14 06:06:08 +00005104 // Check to see if we are changing the return type...
5105 if (OldRetTy != FT->getReturnType()) {
5106 if (Callee->isExternal() &&
5107 !OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()) &&
5108 !Caller->use_empty())
5109 return false; // Cannot transform this return value...
5110
5111 // If the callsite is an invoke instruction, and the return value is used by
5112 // a PHI node in a successor, we cannot change the return type of the call
5113 // because there is no place to put the cast instruction (without breaking
5114 // the critical edge). Bail out in this case.
5115 if (!Caller->use_empty())
5116 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
5117 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
5118 UI != E; ++UI)
5119 if (PHINode *PN = dyn_cast<PHINode>(*UI))
5120 if (PN->getParent() == II->getNormalDest() ||
Chris Lattnerfae8ab32004-02-08 21:44:31 +00005121 PN->getParent() == II->getUnwindDest())
Chris Lattner1f7942f2004-01-14 06:06:08 +00005122 return false;
5123 }
Chris Lattner970c33a2003-06-19 17:00:31 +00005124
5125 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
5126 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005127
Chris Lattner970c33a2003-06-19 17:00:31 +00005128 CallSite::arg_iterator AI = CS.arg_begin();
5129 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
5130 const Type *ParamTy = FT->getParamType(i);
5131 bool isConvertible = (*AI)->getType()->isLosslesslyConvertibleTo(ParamTy);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005132 if (Callee->isExternal() && !isConvertible) return false;
Chris Lattner970c33a2003-06-19 17:00:31 +00005133 }
5134
5135 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
5136 Callee->isExternal())
5137 return false; // Do not delete arguments unless we have a function body...
5138
5139 // Okay, we decided that this is a safe thing to do: go ahead and start
5140 // inserting cast instructions as necessary...
5141 std::vector<Value*> Args;
5142 Args.reserve(NumActualArgs);
5143
5144 AI = CS.arg_begin();
5145 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
5146 const Type *ParamTy = FT->getParamType(i);
5147 if ((*AI)->getType() == ParamTy) {
5148 Args.push_back(*AI);
5149 } else {
Chris Lattner1c631e82004-04-08 04:43:23 +00005150 Args.push_back(InsertNewInstBefore(new CastInst(*AI, ParamTy, "tmp"),
5151 *Caller));
Chris Lattner970c33a2003-06-19 17:00:31 +00005152 }
5153 }
5154
5155 // If the function takes more arguments than the call was taking, add them
5156 // now...
5157 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
5158 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
5159
5160 // If we are removing arguments to the function, emit an obnoxious warning...
5161 if (FT->getNumParams() < NumActualArgs)
5162 if (!FT->isVarArg()) {
5163 std::cerr << "WARNING: While resolving call to function '"
5164 << Callee->getName() << "' arguments were dropped!\n";
5165 } else {
5166 // Add all of the arguments in their promoted form to the arg list...
5167 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
5168 const Type *PTy = getPromotedType((*AI)->getType());
5169 if (PTy != (*AI)->getType()) {
5170 // Must promote to pass through va_arg area!
5171 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
5172 InsertNewInstBefore(Cast, *Caller);
5173 Args.push_back(Cast);
5174 } else {
5175 Args.push_back(*AI);
5176 }
5177 }
5178 }
5179
5180 if (FT->getReturnType() == Type::VoidTy)
5181 Caller->setName(""); // Void type should not have a name...
5182
5183 Instruction *NC;
5184 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattnerfae8ab32004-02-08 21:44:31 +00005185 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattner970c33a2003-06-19 17:00:31 +00005186 Args, Caller->getName(), Caller);
Chris Lattner05c703e2005-05-14 12:25:32 +00005187 cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00005188 } else {
5189 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
Chris Lattner6aacb0f2005-05-06 06:48:21 +00005190 if (cast<CallInst>(Caller)->isTailCall())
5191 cast<CallInst>(NC)->setTailCall();
Chris Lattner05c703e2005-05-14 12:25:32 +00005192 cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00005193 }
5194
5195 // Insert a cast of the return type as necessary...
5196 Value *NV = NC;
5197 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
5198 if (NV->getType() != Type::VoidTy) {
5199 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
Chris Lattner686767f2003-10-30 00:46:41 +00005200
5201 // If this is an invoke instruction, we should insert it after the first
5202 // non-phi, instruction in the normal successor block.
5203 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
5204 BasicBlock::iterator I = II->getNormalDest()->begin();
5205 while (isa<PHINode>(I)) ++I;
5206 InsertNewInstBefore(NC, *I);
5207 } else {
5208 // Otherwise, it's a call, just insert cast right after the call instr
5209 InsertNewInstBefore(NC, *Caller);
5210 }
Chris Lattner51ea1272004-02-28 05:22:00 +00005211 AddUsersToWorkList(*Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00005212 } else {
Chris Lattnere29d6342004-10-17 21:22:38 +00005213 NV = UndefValue::get(Caller->getType());
Chris Lattner970c33a2003-06-19 17:00:31 +00005214 }
5215 }
5216
5217 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
5218 Caller->replaceAllUsesWith(NV);
5219 Caller->getParent()->getInstList().erase(Caller);
5220 removeFromWorkList(Caller);
5221 return true;
5222}
5223
5224
Chris Lattner7515cab2004-11-14 19:13:23 +00005225// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
5226// operator and they all are only used by the PHI, PHI together their
5227// inputs, and do the operation once, to the result of the PHI.
5228Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
5229 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
5230
5231 // Scan the instruction, looking for input operations that can be folded away.
5232 // If all input operands to the phi are the same instruction (e.g. a cast from
5233 // the same type or "+42") we can pull the operation through the PHI, reducing
5234 // code size and simplifying code.
5235 Constant *ConstantOp = 0;
5236 const Type *CastSrcTy = 0;
5237 if (isa<CastInst>(FirstInst)) {
5238 CastSrcTy = FirstInst->getOperand(0)->getType();
5239 } else if (isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst)) {
5240 // Can fold binop or shift if the RHS is a constant.
5241 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
5242 if (ConstantOp == 0) return 0;
5243 } else {
5244 return 0; // Cannot fold this operation.
5245 }
5246
5247 // Check to see if all arguments are the same operation.
5248 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
5249 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
5250 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
5251 if (!I->hasOneUse() || I->getOpcode() != FirstInst->getOpcode())
5252 return 0;
5253 if (CastSrcTy) {
5254 if (I->getOperand(0)->getType() != CastSrcTy)
5255 return 0; // Cast operation must match.
5256 } else if (I->getOperand(1) != ConstantOp) {
5257 return 0;
5258 }
5259 }
5260
5261 // Okay, they are all the same operation. Create a new PHI node of the
5262 // correct type, and PHI together all of the LHS's of the instructions.
5263 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
5264 PN.getName()+".in");
Chris Lattnerd8e20182005-01-29 00:39:08 +00005265 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattner46dd5a62004-11-14 19:29:34 +00005266
5267 Value *InVal = FirstInst->getOperand(0);
5268 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00005269
5270 // Add all operands to the new PHI.
Chris Lattner46dd5a62004-11-14 19:29:34 +00005271 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
5272 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
5273 if (NewInVal != InVal)
5274 InVal = 0;
5275 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
5276 }
5277
5278 Value *PhiVal;
5279 if (InVal) {
5280 // The new PHI unions all of the same values together. This is really
5281 // common, so we handle it intelligently here for compile-time speed.
5282 PhiVal = InVal;
5283 delete NewPN;
5284 } else {
5285 InsertNewInstBefore(NewPN, PN);
5286 PhiVal = NewPN;
5287 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005288
Chris Lattner7515cab2004-11-14 19:13:23 +00005289 // Insert and return the new operation.
5290 if (isa<CastInst>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00005291 return new CastInst(PhiVal, PN.getType());
Chris Lattner7515cab2004-11-14 19:13:23 +00005292 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00005293 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00005294 else
5295 return new ShiftInst(cast<ShiftInst>(FirstInst)->getOpcode(),
Chris Lattner46dd5a62004-11-14 19:29:34 +00005296 PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00005297}
Chris Lattner48a44f72002-05-02 17:06:02 +00005298
Chris Lattner71536432005-01-17 05:10:15 +00005299/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
5300/// that is dead.
5301static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
5302 if (PN->use_empty()) return true;
5303 if (!PN->hasOneUse()) return false;
5304
5305 // Remember this node, and if we find the cycle, return.
5306 if (!PotentiallyDeadPHIs.insert(PN).second)
5307 return true;
5308
5309 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
5310 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005311
Chris Lattner71536432005-01-17 05:10:15 +00005312 return false;
5313}
5314
Chris Lattnerbbbdd852002-05-06 18:06:38 +00005315// PHINode simplification
5316//
Chris Lattner113f4f42002-06-25 16:13:24 +00005317Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Chris Lattner9f9c2602005-08-05 01:04:30 +00005318 if (Value *V = PN.hasConstantValue())
5319 return ReplaceInstUsesWith(PN, V);
Chris Lattner4db2d222004-02-16 05:07:08 +00005320
5321 // If the only user of this instruction is a cast instruction, and all of the
5322 // incoming values are constants, change this PHI to merge together the casted
5323 // constants.
5324 if (PN.hasOneUse())
5325 if (CastInst *CI = dyn_cast<CastInst>(PN.use_back()))
5326 if (CI->getType() != PN.getType()) { // noop casts will be folded
5327 bool AllConstant = true;
5328 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
5329 if (!isa<Constant>(PN.getIncomingValue(i))) {
5330 AllConstant = false;
5331 break;
5332 }
5333 if (AllConstant) {
5334 // Make a new PHI with all casted values.
5335 PHINode *New = new PHINode(CI->getType(), PN.getName(), &PN);
5336 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
5337 Constant *OldArg = cast<Constant>(PN.getIncomingValue(i));
5338 New->addIncoming(ConstantExpr::getCast(OldArg, New->getType()),
5339 PN.getIncomingBlock(i));
5340 }
5341
5342 // Update the cast instruction.
5343 CI->setOperand(0, New);
5344 WorkList.push_back(CI); // revisit the cast instruction to fold.
5345 WorkList.push_back(New); // Make sure to revisit the new Phi
5346 return &PN; // PN is now dead!
5347 }
5348 }
Chris Lattner7515cab2004-11-14 19:13:23 +00005349
5350 // If all PHI operands are the same operation, pull them through the PHI,
5351 // reducing code size.
5352 if (isa<Instruction>(PN.getIncomingValue(0)) &&
5353 PN.getIncomingValue(0)->hasOneUse())
5354 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
5355 return Result;
5356
Chris Lattner71536432005-01-17 05:10:15 +00005357 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
5358 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
5359 // PHI)... break the cycle.
5360 if (PN.hasOneUse())
5361 if (PHINode *PU = dyn_cast<PHINode>(PN.use_back())) {
5362 std::set<PHINode*> PotentiallyDeadPHIs;
5363 PotentiallyDeadPHIs.insert(&PN);
5364 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
5365 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
5366 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005367
Chris Lattner91daeb52003-12-19 05:58:40 +00005368 return 0;
Chris Lattnerbbbdd852002-05-06 18:06:38 +00005369}
5370
Chris Lattner69193f92004-04-05 01:30:19 +00005371static Value *InsertSignExtendToPtrTy(Value *V, const Type *DTy,
5372 Instruction *InsertPoint,
5373 InstCombiner *IC) {
5374 unsigned PS = IC->getTargetData().getPointerSize();
5375 const Type *VTy = V->getType();
Chris Lattner69193f92004-04-05 01:30:19 +00005376 if (!VTy->isSigned() && VTy->getPrimitiveSize() < PS)
5377 // We must insert a cast to ensure we sign-extend.
5378 V = IC->InsertNewInstBefore(new CastInst(V, VTy->getSignedVersion(),
5379 V->getName()), *InsertPoint);
5380 return IC->InsertNewInstBefore(new CastInst(V, DTy, V->getName()),
5381 *InsertPoint);
5382}
5383
Chris Lattner48a44f72002-05-02 17:06:02 +00005384
Chris Lattner113f4f42002-06-25 16:13:24 +00005385Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner5f667a62004-05-07 22:09:22 +00005386 Value *PtrOp = GEP.getOperand(0);
Chris Lattner471bd762003-05-22 19:07:21 +00005387 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner113f4f42002-06-25 16:13:24 +00005388 // If so, eliminate the noop.
Chris Lattner8d0bacb2004-02-22 05:25:17 +00005389 if (GEP.getNumOperands() == 1)
Chris Lattner5f667a62004-05-07 22:09:22 +00005390 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner8d0bacb2004-02-22 05:25:17 +00005391
Chris Lattner81a7a232004-10-16 18:11:37 +00005392 if (isa<UndefValue>(GEP.getOperand(0)))
5393 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
5394
Chris Lattner8d0bacb2004-02-22 05:25:17 +00005395 bool HasZeroPointerIndex = false;
5396 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
5397 HasZeroPointerIndex = C->isNullValue();
5398
5399 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner5f667a62004-05-07 22:09:22 +00005400 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner48a44f72002-05-02 17:06:02 +00005401
Chris Lattner69193f92004-04-05 01:30:19 +00005402 // Eliminate unneeded casts for indices.
5403 bool MadeChange = false;
Chris Lattner2b2412d2004-04-07 18:38:20 +00005404 gep_type_iterator GTI = gep_type_begin(GEP);
5405 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
5406 if (isa<SequentialType>(*GTI)) {
5407 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
5408 Value *Src = CI->getOperand(0);
5409 const Type *SrcTy = Src->getType();
5410 const Type *DestTy = CI->getType();
5411 if (Src->getType()->isInteger()) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005412 if (SrcTy->getPrimitiveSizeInBits() ==
5413 DestTy->getPrimitiveSizeInBits()) {
Chris Lattner2b2412d2004-04-07 18:38:20 +00005414 // We can always eliminate a cast from ulong or long to the other.
5415 // We can always eliminate a cast from uint to int or the other on
5416 // 32-bit pointer platforms.
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005417 if (DestTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()){
Chris Lattner2b2412d2004-04-07 18:38:20 +00005418 MadeChange = true;
5419 GEP.setOperand(i, Src);
5420 }
5421 } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
5422 SrcTy->getPrimitiveSize() == 4) {
5423 // We can always eliminate a cast from int to [u]long. We can
5424 // eliminate a cast from uint to [u]long iff the target is a 32-bit
5425 // pointer target.
Misha Brukmanb1c93172005-04-21 23:48:37 +00005426 if (SrcTy->isSigned() ||
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005427 SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
Chris Lattner2b2412d2004-04-07 18:38:20 +00005428 MadeChange = true;
5429 GEP.setOperand(i, Src);
5430 }
Chris Lattner69193f92004-04-05 01:30:19 +00005431 }
5432 }
5433 }
Chris Lattner2b2412d2004-04-07 18:38:20 +00005434 // If we are using a wider index than needed for this platform, shrink it
5435 // to what we need. If the incoming value needs a cast instruction,
5436 // insert it. This explicit cast can make subsequent optimizations more
5437 // obvious.
5438 Value *Op = GEP.getOperand(i);
5439 if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00005440 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner44d0b952004-07-20 01:48:15 +00005441 GEP.setOperand(i, ConstantExpr::getCast(C,
5442 TD->getIntPtrType()->getSignedVersion()));
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00005443 MadeChange = true;
5444 } else {
Chris Lattner2b2412d2004-04-07 18:38:20 +00005445 Op = InsertNewInstBefore(new CastInst(Op, TD->getIntPtrType(),
5446 Op->getName()), GEP);
5447 GEP.setOperand(i, Op);
5448 MadeChange = true;
5449 }
Chris Lattner44d0b952004-07-20 01:48:15 +00005450
5451 // If this is a constant idx, make sure to canonicalize it to be a signed
5452 // operand, otherwise CSE and other optimizations are pessimized.
5453 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op)) {
5454 GEP.setOperand(i, ConstantExpr::getCast(CUI,
5455 CUI->getType()->getSignedVersion()));
5456 MadeChange = true;
5457 }
Chris Lattner69193f92004-04-05 01:30:19 +00005458 }
5459 if (MadeChange) return &GEP;
5460
Chris Lattnerae7a0d32002-08-02 19:29:35 +00005461 // Combine Indices - If the source pointer to this getelementptr instruction
5462 // is a getelementptr instruction, combine the indices of the two
5463 // getelementptr instructions into a single instruction.
5464 //
Chris Lattner57c67b02004-03-25 22:59:29 +00005465 std::vector<Value*> SrcGEPOperands;
Chris Lattner0798af32005-01-13 20:14:25 +00005466 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner57c67b02004-03-25 22:59:29 +00005467 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
Chris Lattner57c67b02004-03-25 22:59:29 +00005468
5469 if (!SrcGEPOperands.empty()) {
Chris Lattner5f667a62004-05-07 22:09:22 +00005470 // Note that if our source is a gep chain itself that we wait for that
5471 // chain to be resolved before we perform this transformation. This
5472 // avoids us creating a TON of code in some cases.
5473 //
5474 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
5475 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
5476 return 0; // Wait until our source is folded to completion.
5477
Chris Lattnerae7a0d32002-08-02 19:29:35 +00005478 std::vector<Value *> Indices;
Chris Lattner5f667a62004-05-07 22:09:22 +00005479
5480 // Find out whether the last index in the source GEP is a sequential idx.
5481 bool EndsWithSequential = false;
5482 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
5483 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattner8ec5f882004-05-08 22:41:42 +00005484 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005485
Chris Lattnerae7a0d32002-08-02 19:29:35 +00005486 // Can we combine the two pointer arithmetics offsets?
Chris Lattner5f667a62004-05-07 22:09:22 +00005487 if (EndsWithSequential) {
Chris Lattner235af562003-03-05 22:33:14 +00005488 // Replace: gep (gep %P, long B), long A, ...
5489 // With: T = long A+B; gep %P, T, ...
5490 //
Chris Lattner5f667a62004-05-07 22:09:22 +00005491 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner69193f92004-04-05 01:30:19 +00005492 if (SO1 == Constant::getNullValue(SO1->getType())) {
5493 Sum = GO1;
5494 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
5495 Sum = SO1;
5496 } else {
5497 // If they aren't the same type, convert both to an integer of the
5498 // target's pointer size.
5499 if (SO1->getType() != GO1->getType()) {
5500 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
5501 SO1 = ConstantExpr::getCast(SO1C, GO1->getType());
5502 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
5503 GO1 = ConstantExpr::getCast(GO1C, SO1->getType());
5504 } else {
5505 unsigned PS = TD->getPointerSize();
Chris Lattner69193f92004-04-05 01:30:19 +00005506 if (SO1->getType()->getPrimitiveSize() == PS) {
5507 // Convert GO1 to SO1's type.
5508 GO1 = InsertSignExtendToPtrTy(GO1, SO1->getType(), &GEP, this);
5509
5510 } else if (GO1->getType()->getPrimitiveSize() == PS) {
5511 // Convert SO1 to GO1's type.
5512 SO1 = InsertSignExtendToPtrTy(SO1, GO1->getType(), &GEP, this);
5513 } else {
5514 const Type *PT = TD->getIntPtrType();
5515 SO1 = InsertSignExtendToPtrTy(SO1, PT, &GEP, this);
5516 GO1 = InsertSignExtendToPtrTy(GO1, PT, &GEP, this);
5517 }
5518 }
5519 }
Chris Lattner5f667a62004-05-07 22:09:22 +00005520 if (isa<Constant>(SO1) && isa<Constant>(GO1))
5521 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
5522 else {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00005523 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
5524 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner5f667a62004-05-07 22:09:22 +00005525 }
Chris Lattner69193f92004-04-05 01:30:19 +00005526 }
Chris Lattner5f667a62004-05-07 22:09:22 +00005527
5528 // Recycle the GEP we already have if possible.
5529 if (SrcGEPOperands.size() == 2) {
5530 GEP.setOperand(0, SrcGEPOperands[0]);
5531 GEP.setOperand(1, Sum);
5532 return &GEP;
5533 } else {
5534 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
5535 SrcGEPOperands.end()-1);
5536 Indices.push_back(Sum);
5537 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
5538 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005539 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner69193f92004-04-05 01:30:19 +00005540 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00005541 SrcGEPOperands.size() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00005542 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattner57c67b02004-03-25 22:59:29 +00005543 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
5544 SrcGEPOperands.end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +00005545 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
5546 }
5547
5548 if (!Indices.empty())
Chris Lattner57c67b02004-03-25 22:59:29 +00005549 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00005550
Chris Lattner5f667a62004-05-07 22:09:22 +00005551 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattnerc59af1d2002-08-17 22:21:59 +00005552 // GEP of global variable. If all of the indices for this GEP are
5553 // constants, we can promote this to a constexpr instead of an instruction.
5554
5555 // Scan for nonconstants...
5556 std::vector<Constant*> Indices;
5557 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
5558 for (; I != E && isa<Constant>(*I); ++I)
5559 Indices.push_back(cast<Constant>(*I));
5560
5561 if (I == E) { // If they are all constants...
Chris Lattnerf3edc492004-07-18 18:59:44 +00005562 Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
Chris Lattnerc59af1d2002-08-17 22:21:59 +00005563
5564 // Replace all uses of the GEP with the new constexpr...
5565 return ReplaceInstUsesWith(GEP, CE);
5566 }
Chris Lattner567b81f2005-09-13 00:40:14 +00005567 } else if (Value *X = isCast(PtrOp)) { // Is the operand a cast?
5568 if (!isa<PointerType>(X->getType())) {
5569 // Not interesting. Source pointer must be a cast from pointer.
5570 } else if (HasZeroPointerIndex) {
5571 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
5572 // into : GEP [10 x ubyte]* X, long 0, ...
5573 //
5574 // This occurs when the program declares an array extern like "int X[];"
5575 //
5576 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
5577 const PointerType *XTy = cast<PointerType>(X->getType());
5578 if (const ArrayType *XATy =
5579 dyn_cast<ArrayType>(XTy->getElementType()))
5580 if (const ArrayType *CATy =
5581 dyn_cast<ArrayType>(CPTy->getElementType()))
5582 if (CATy->getElementType() == XATy->getElementType()) {
5583 // At this point, we know that the cast source type is a pointer
5584 // to an array of the same type as the destination pointer
5585 // array. Because the array type is never stepped over (there
5586 // is a leading zero) we can fold the cast into this GEP.
5587 GEP.setOperand(0, X);
5588 return &GEP;
5589 }
5590 } else if (GEP.getNumOperands() == 2) {
5591 // Transform things like:
Chris Lattner2a893292005-09-13 18:36:04 +00005592 // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
5593 // into: %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
Chris Lattner567b81f2005-09-13 00:40:14 +00005594 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
5595 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
5596 if (isa<ArrayType>(SrcElTy) &&
5597 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
5598 TD->getTypeSize(ResElTy)) {
5599 Value *V = InsertNewInstBefore(
5600 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
5601 GEP.getOperand(1), GEP.getName()), GEP);
5602 return new CastInst(V, GEP.getType());
Chris Lattner8d0bacb2004-02-22 05:25:17 +00005603 }
Chris Lattner2a893292005-09-13 18:36:04 +00005604
5605 // Transform things like:
5606 // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
5607 // (where tmp = 8*tmp2) into:
5608 // getelementptr [100 x double]* %arr, int 0, int %tmp.2
5609
5610 if (isa<ArrayType>(SrcElTy) &&
5611 (ResElTy == Type::SByteTy || ResElTy == Type::UByteTy)) {
5612 uint64_t ArrayEltSize =
5613 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
5614
5615 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
5616 // allow either a mul, shift, or constant here.
5617 Value *NewIdx = 0;
5618 ConstantInt *Scale = 0;
5619 if (ArrayEltSize == 1) {
5620 NewIdx = GEP.getOperand(1);
5621 Scale = ConstantInt::get(NewIdx->getType(), 1);
5622 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattnera393e4d2005-09-14 17:32:56 +00005623 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner2a893292005-09-13 18:36:04 +00005624 Scale = CI;
5625 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
5626 if (Inst->getOpcode() == Instruction::Shl &&
5627 isa<ConstantInt>(Inst->getOperand(1))) {
5628 unsigned ShAmt =cast<ConstantUInt>(Inst->getOperand(1))->getValue();
5629 if (Inst->getType()->isSigned())
5630 Scale = ConstantSInt::get(Inst->getType(), 1ULL << ShAmt);
5631 else
5632 Scale = ConstantUInt::get(Inst->getType(), 1ULL << ShAmt);
5633 NewIdx = Inst->getOperand(0);
5634 } else if (Inst->getOpcode() == Instruction::Mul &&
5635 isa<ConstantInt>(Inst->getOperand(1))) {
5636 Scale = cast<ConstantInt>(Inst->getOperand(1));
5637 NewIdx = Inst->getOperand(0);
5638 }
5639 }
5640
5641 // If the index will be to exactly the right offset with the scale taken
5642 // out, perform the transformation.
5643 if (Scale && Scale->getRawValue() % ArrayEltSize == 0) {
5644 if (ConstantSInt *C = dyn_cast<ConstantSInt>(Scale))
5645 Scale = ConstantSInt::get(C->getType(),
Chris Lattnera393e4d2005-09-14 17:32:56 +00005646 (int64_t)C->getRawValue() /
5647 (int64_t)ArrayEltSize);
Chris Lattner2a893292005-09-13 18:36:04 +00005648 else
5649 Scale = ConstantUInt::get(Scale->getType(),
5650 Scale->getRawValue() / ArrayEltSize);
5651 if (Scale->getRawValue() != 1) {
5652 Constant *C = ConstantExpr::getCast(Scale, NewIdx->getType());
5653 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
5654 NewIdx = InsertNewInstBefore(Sc, GEP);
5655 }
5656
5657 // Insert the new GEP instruction.
5658 Instruction *Idx =
5659 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
5660 NewIdx, GEP.getName());
5661 Idx = InsertNewInstBefore(Idx, GEP);
5662 return new CastInst(Idx, GEP.getType());
5663 }
5664 }
Chris Lattner8d0bacb2004-02-22 05:25:17 +00005665 }
Chris Lattnerca081252001-12-14 16:52:21 +00005666 }
5667
Chris Lattnerca081252001-12-14 16:52:21 +00005668 return 0;
5669}
5670
Chris Lattner1085bdf2002-11-04 16:18:53 +00005671Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
5672 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
5673 if (AI.isArrayAllocation()) // Check C != 1
5674 if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
5675 const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
Chris Lattnera2620ac2002-11-09 00:49:43 +00005676 AllocationInst *New = 0;
Chris Lattner1085bdf2002-11-04 16:18:53 +00005677
5678 // Create and insert the replacement instruction...
5679 if (isa<MallocInst>(AI))
Nate Begeman848622f2005-11-05 09:21:28 +00005680 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00005681 else {
5682 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman848622f2005-11-05 09:21:28 +00005683 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00005684 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00005685
5686 InsertNewInstBefore(New, AI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005687
Chris Lattner1085bdf2002-11-04 16:18:53 +00005688 // Scan to the end of the allocation instructions, to skip over a block of
5689 // allocas if possible...
5690 //
5691 BasicBlock::iterator It = New;
5692 while (isa<AllocationInst>(*It)) ++It;
5693
5694 // Now that I is pointing to the first non-allocation-inst in the block,
5695 // insert our getelementptr instruction...
5696 //
Chris Lattner809dfac2005-05-04 19:10:26 +00005697 Value *NullIdx = Constant::getNullValue(Type::IntTy);
5698 Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
5699 New->getName()+".sub", It);
Chris Lattner1085bdf2002-11-04 16:18:53 +00005700
5701 // Now make everything use the getelementptr instead of the original
5702 // allocation.
Chris Lattnerabb77c92004-03-19 06:08:10 +00005703 return ReplaceInstUsesWith(AI, V);
Chris Lattner81a7a232004-10-16 18:11:37 +00005704 } else if (isa<UndefValue>(AI.getArraySize())) {
5705 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner1085bdf2002-11-04 16:18:53 +00005706 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00005707
5708 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
5709 // Note that we only do this for alloca's, because malloc should allocate and
5710 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanb1c93172005-04-21 23:48:37 +00005711 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Chris Lattner49df6ce2004-07-02 22:55:47 +00005712 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattnerabb77c92004-03-19 06:08:10 +00005713 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
5714
Chris Lattner1085bdf2002-11-04 16:18:53 +00005715 return 0;
5716}
5717
Chris Lattner8427bff2003-12-07 01:24:23 +00005718Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
5719 Value *Op = FI.getOperand(0);
5720
5721 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
5722 if (CastInst *CI = dyn_cast<CastInst>(Op))
5723 if (isa<PointerType>(CI->getOperand(0)->getType())) {
5724 FI.setOperand(0, CI->getOperand(0));
5725 return &FI;
5726 }
5727
Chris Lattner8ba9ec92004-10-18 02:59:09 +00005728 // free undef -> unreachable.
5729 if (isa<UndefValue>(Op)) {
5730 // Insert a new store to null because we cannot modify the CFG here.
5731 new StoreInst(ConstantBool::True,
5732 UndefValue::get(PointerType::get(Type::BoolTy)), &FI);
5733 return EraseInstFromFunction(FI);
5734 }
5735
Chris Lattnerf3a36602004-02-28 04:57:37 +00005736 // If we have 'free null' delete the instruction. This can happen in stl code
5737 // when lots of inlining happens.
Chris Lattner8ba9ec92004-10-18 02:59:09 +00005738 if (isa<ConstantPointerNull>(Op))
Chris Lattner51ea1272004-02-28 05:22:00 +00005739 return EraseInstFromFunction(FI);
Chris Lattnerf3a36602004-02-28 04:57:37 +00005740
Chris Lattner8427bff2003-12-07 01:24:23 +00005741 return 0;
5742}
5743
5744
Chris Lattner72684fe2005-01-31 05:51:45 +00005745/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Chris Lattner35e24772004-07-13 01:49:43 +00005746static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
5747 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00005748 Value *CastOp = CI->getOperand(0);
Chris Lattner35e24772004-07-13 01:49:43 +00005749
5750 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00005751 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattner35e24772004-07-13 01:49:43 +00005752 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00005753
5754 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
5755 // If the source is an array, the code below will not succeed. Check to
5756 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
5757 // constants.
5758 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
5759 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
5760 if (ASrcTy->getNumElements() != 0) {
5761 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
5762 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
5763 SrcTy = cast<PointerType>(CastOp->getType());
5764 SrcPTy = SrcTy->getElementType();
5765 }
5766
5767 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
Chris Lattnerecfa9b52005-03-29 06:37:47 +00005768 // Do not allow turning this into a load of an integer, which is then
5769 // casted to a pointer, this pessimizes pointer analysis a lot.
5770 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00005771 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00005772 IC.getTargetData().getTypeSize(DestPTy)) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00005773
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00005774 // Okay, we are casting from one integer or pointer type to another of
5775 // the same size. Instead of casting the pointer before the load, cast
5776 // the result of the loaded value.
5777 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
5778 CI->getName(),
5779 LI.isVolatile()),LI);
5780 // Now cast the result of the load.
5781 return new CastInst(NewLoad, LI.getType());
5782 }
Chris Lattner35e24772004-07-13 01:49:43 +00005783 }
5784 }
5785 return 0;
5786}
5787
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00005788/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattnere6f13092004-09-19 19:18:10 +00005789/// from this value cannot trap. If it is not obviously safe to load from the
5790/// specified pointer, we do a quick local scan of the basic block containing
5791/// ScanFrom, to determine if the address is already accessed.
5792static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
5793 // If it is an alloca or global variable, it is always safe to load from.
5794 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
5795
5796 // Otherwise, be a little bit agressive by scanning the local block where we
5797 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00005798 // from/to. If so, the previous load or store would have already trapped,
5799 // so there is no harm doing an extra load (also, CSE will later eliminate
5800 // the load entirely).
Chris Lattnere6f13092004-09-19 19:18:10 +00005801 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
5802
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00005803 while (BBI != E) {
Chris Lattnere6f13092004-09-19 19:18:10 +00005804 --BBI;
5805
5806 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
5807 if (LI->getOperand(0) == V) return true;
5808 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
5809 if (SI->getOperand(1) == V) return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00005810
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00005811 }
Chris Lattnere6f13092004-09-19 19:18:10 +00005812 return false;
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00005813}
5814
Chris Lattner0f1d8a32003-06-26 05:06:25 +00005815Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
5816 Value *Op = LI.getOperand(0);
Chris Lattner7e8af382004-01-12 04:13:56 +00005817
Chris Lattnera9d84e32005-05-01 04:24:53 +00005818 // load (cast X) --> cast (load X) iff safe
5819 if (CastInst *CI = dyn_cast<CastInst>(Op))
5820 if (Instruction *Res = InstCombineLoadCast(*this, LI))
5821 return Res;
5822
5823 // None of the following transforms are legal for volatile loads.
5824 if (LI.isVolatile()) return 0;
Chris Lattnerb990f7d2005-09-12 22:00:15 +00005825
Chris Lattnerb990f7d2005-09-12 22:00:15 +00005826 if (&LI.getParent()->front() != &LI) {
5827 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattnere0bfdf12005-09-12 22:21:03 +00005828 // If the instruction immediately before this is a store to the same
5829 // address, do a simple form of store->load forwarding.
Chris Lattnerb990f7d2005-09-12 22:00:15 +00005830 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
5831 if (SI->getOperand(1) == LI.getOperand(0))
5832 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattnere0bfdf12005-09-12 22:21:03 +00005833 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
5834 if (LIB->getOperand(0) == LI.getOperand(0))
5835 return ReplaceInstUsesWith(LI, LIB);
Chris Lattnerb990f7d2005-09-12 22:00:15 +00005836 }
Chris Lattnera9d84e32005-05-01 04:24:53 +00005837
5838 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
5839 if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
5840 isa<UndefValue>(GEPI->getOperand(0))) {
5841 // Insert a new store to null instruction before the load to indicate
5842 // that this code is not reachable. We do this instead of inserting
5843 // an unreachable instruction directly because we cannot modify the
5844 // CFG.
5845 new StoreInst(UndefValue::get(LI.getType()),
5846 Constant::getNullValue(Op->getType()), &LI);
5847 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
5848 }
5849
Chris Lattner81a7a232004-10-16 18:11:37 +00005850 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattnera9d84e32005-05-01 04:24:53 +00005851 // load null/undef -> undef
5852 if ((C->isNullValue() || isa<UndefValue>(C))) {
Chris Lattner8ba9ec92004-10-18 02:59:09 +00005853 // Insert a new store to null instruction before the load to indicate that
5854 // this code is not reachable. We do this instead of inserting an
5855 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattnera9d84e32005-05-01 04:24:53 +00005856 new StoreInst(UndefValue::get(LI.getType()),
5857 Constant::getNullValue(Op->getType()), &LI);
Chris Lattner81a7a232004-10-16 18:11:37 +00005858 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner8ba9ec92004-10-18 02:59:09 +00005859 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00005860
Chris Lattner81a7a232004-10-16 18:11:37 +00005861 // Instcombine load (constant global) into the value loaded.
5862 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
5863 if (GV->isConstant() && !GV->isExternal())
5864 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanb1c93172005-04-21 23:48:37 +00005865
Chris Lattner81a7a232004-10-16 18:11:37 +00005866 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
5867 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
5868 if (CE->getOpcode() == Instruction::GetElementPtr) {
5869 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
5870 if (GV->isConstant() && !GV->isExternal())
Chris Lattner0b011ec2005-09-26 05:28:06 +00005871 if (Constant *V =
5872 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattner81a7a232004-10-16 18:11:37 +00005873 return ReplaceInstUsesWith(LI, V);
Chris Lattnera9d84e32005-05-01 04:24:53 +00005874 if (CE->getOperand(0)->isNullValue()) {
5875 // Insert a new store to null instruction before the load to indicate
5876 // that this code is not reachable. We do this instead of inserting
5877 // an unreachable instruction directly because we cannot modify the
5878 // CFG.
5879 new StoreInst(UndefValue::get(LI.getType()),
5880 Constant::getNullValue(Op->getType()), &LI);
5881 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
5882 }
5883
Chris Lattner81a7a232004-10-16 18:11:37 +00005884 } else if (CE->getOpcode() == Instruction::Cast) {
5885 if (Instruction *Res = InstCombineLoadCast(*this, LI))
5886 return Res;
5887 }
5888 }
Chris Lattnere228ee52004-04-08 20:39:49 +00005889
Chris Lattnera9d84e32005-05-01 04:24:53 +00005890 if (Op->hasOneUse()) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00005891 // Change select and PHI nodes to select values instead of addresses: this
5892 // helps alias analysis out a lot, allows many others simplifications, and
5893 // exposes redundancy in the code.
5894 //
5895 // Note that we cannot do the transformation unless we know that the
5896 // introduced loads cannot trap! Something like this is valid as long as
5897 // the condition is always false: load (select bool %C, int* null, int* %G),
5898 // but it would not be valid if we transformed it to load from null
5899 // unconditionally.
5900 //
5901 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
5902 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattnere6f13092004-09-19 19:18:10 +00005903 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
5904 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00005905 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner42618552004-09-20 10:15:10 +00005906 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00005907 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner42618552004-09-20 10:15:10 +00005908 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00005909 return new SelectInst(SI->getCondition(), V1, V2);
5910 }
5911
Chris Lattnerbdcf41a2004-09-23 15:46:00 +00005912 // load (select (cond, null, P)) -> load P
5913 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
5914 if (C->isNullValue()) {
5915 LI.setOperand(0, SI->getOperand(2));
5916 return &LI;
5917 }
5918
5919 // load (select (cond, P, null)) -> load P
5920 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
5921 if (C->isNullValue()) {
5922 LI.setOperand(0, SI->getOperand(1));
5923 return &LI;
5924 }
5925
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00005926 } else if (PHINode *PN = dyn_cast<PHINode>(Op)) {
5927 // load (phi (&V1, &V2, &V3)) --> phi(load &V1, load &V2, load &V3)
Chris Lattner42618552004-09-20 10:15:10 +00005928 bool Safe = PN->getParent() == LI.getParent();
5929
5930 // Scan all of the instructions between the PHI and the load to make
5931 // sure there are no instructions that might possibly alter the value
5932 // loaded from the PHI.
5933 if (Safe) {
5934 BasicBlock::iterator I = &LI;
5935 for (--I; !isa<PHINode>(I); --I)
5936 if (isa<StoreInst>(I) || isa<CallInst>(I)) {
5937 Safe = false;
5938 break;
5939 }
5940 }
5941
5942 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e && Safe; ++i)
Chris Lattnere6f13092004-09-19 19:18:10 +00005943 if (!isSafeToLoadUnconditionally(PN->getIncomingValue(i),
Chris Lattner42618552004-09-20 10:15:10 +00005944 PN->getIncomingBlock(i)->getTerminator()))
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00005945 Safe = false;
Chris Lattner42618552004-09-20 10:15:10 +00005946
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00005947 if (Safe) {
5948 // Create the PHI.
5949 PHINode *NewPN = new PHINode(LI.getType(), PN->getName());
5950 InsertNewInstBefore(NewPN, *PN);
5951 std::map<BasicBlock*,Value*> LoadMap; // Don't insert duplicate loads
5952
5953 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
5954 BasicBlock *BB = PN->getIncomingBlock(i);
5955 Value *&TheLoad = LoadMap[BB];
5956 if (TheLoad == 0) {
5957 Value *InVal = PN->getIncomingValue(i);
5958 TheLoad = InsertNewInstBefore(new LoadInst(InVal,
5959 InVal->getName()+".val"),
5960 *BB->getTerminator());
5961 }
5962 NewPN->addIncoming(TheLoad, BB);
5963 }
5964 return ReplaceInstUsesWith(LI, NewPN);
5965 }
5966 }
5967 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00005968 return 0;
5969}
5970
Chris Lattner72684fe2005-01-31 05:51:45 +00005971/// InstCombineStoreToCast - Fold 'store V, (cast P)' -> store (cast V), P'
5972/// when possible.
5973static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
5974 User *CI = cast<User>(SI.getOperand(1));
5975 Value *CastOp = CI->getOperand(0);
5976
5977 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
5978 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
5979 const Type *SrcPTy = SrcTy->getElementType();
5980
5981 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
5982 // If the source is an array, the code below will not succeed. Check to
5983 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
5984 // constants.
5985 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
5986 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
5987 if (ASrcTy->getNumElements() != 0) {
5988 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
5989 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
5990 SrcTy = cast<PointerType>(CastOp->getType());
5991 SrcPTy = SrcTy->getElementType();
5992 }
5993
5994 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00005995 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattner72684fe2005-01-31 05:51:45 +00005996 IC.getTargetData().getTypeSize(DestPTy)) {
5997
5998 // Okay, we are casting from one integer or pointer type to another of
5999 // the same size. Instead of casting the pointer before the store, cast
6000 // the value to be stored.
6001 Value *NewCast;
6002 if (Constant *C = dyn_cast<Constant>(SI.getOperand(0)))
6003 NewCast = ConstantExpr::getCast(C, SrcPTy);
6004 else
6005 NewCast = IC.InsertNewInstBefore(new CastInst(SI.getOperand(0),
6006 SrcPTy,
6007 SI.getOperand(0)->getName()+".c"), SI);
6008
6009 return new StoreInst(NewCast, CastOp);
6010 }
6011 }
6012 }
6013 return 0;
6014}
6015
Chris Lattner31f486c2005-01-31 05:36:43 +00006016Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
6017 Value *Val = SI.getOperand(0);
6018 Value *Ptr = SI.getOperand(1);
6019
6020 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner5997cf92006-02-08 03:25:32 +00006021 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +00006022 ++NumCombined;
6023 return 0;
6024 }
6025
Chris Lattner5997cf92006-02-08 03:25:32 +00006026 // Do really simple DSE, to catch cases where there are several consequtive
6027 // stores to the same location, separated by a few arithmetic operations. This
6028 // situation often occurs with bitfield accesses.
6029 BasicBlock::iterator BBI = &SI;
6030 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
6031 --ScanInsts) {
6032 --BBI;
6033
6034 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
6035 // Prev store isn't volatile, and stores to the same location?
6036 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
6037 ++NumDeadStore;
6038 ++BBI;
6039 EraseInstFromFunction(*PrevSI);
6040 continue;
6041 }
6042 break;
6043 }
6044
6045 // Don't skip over loads or things that can modify memory.
6046 if (BBI->mayWriteToMemory() || isa<LoadInst>(BBI))
6047 break;
6048 }
6049
6050
6051 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner31f486c2005-01-31 05:36:43 +00006052
6053 // store X, null -> turns into 'unreachable' in SimplifyCFG
6054 if (isa<ConstantPointerNull>(Ptr)) {
6055 if (!isa<UndefValue>(Val)) {
6056 SI.setOperand(0, UndefValue::get(Val->getType()));
6057 if (Instruction *U = dyn_cast<Instruction>(Val))
6058 WorkList.push_back(U); // Dropped a use.
6059 ++NumCombined;
6060 }
6061 return 0; // Do not modify these!
6062 }
6063
6064 // store undef, Ptr -> noop
6065 if (isa<UndefValue>(Val)) {
Chris Lattner5997cf92006-02-08 03:25:32 +00006066 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +00006067 ++NumCombined;
6068 return 0;
6069 }
6070
Chris Lattner72684fe2005-01-31 05:51:45 +00006071 // If the pointer destination is a cast, see if we can fold the cast into the
6072 // source instead.
6073 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
6074 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
6075 return Res;
6076 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
6077 if (CE->getOpcode() == Instruction::Cast)
6078 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
6079 return Res;
6080
Chris Lattner219175c2005-09-12 23:23:25 +00006081
6082 // If this store is the last instruction in the basic block, and if the block
6083 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner5997cf92006-02-08 03:25:32 +00006084 BBI = &SI; ++BBI;
Chris Lattner219175c2005-09-12 23:23:25 +00006085 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
6086 if (BI->isUnconditional()) {
6087 // Check to see if the successor block has exactly two incoming edges. If
6088 // so, see if the other predecessor contains a store to the same location.
6089 // if so, insert a PHI node (if needed) and move the stores down.
6090 BasicBlock *Dest = BI->getSuccessor(0);
6091
6092 pred_iterator PI = pred_begin(Dest);
6093 BasicBlock *Other = 0;
6094 if (*PI != BI->getParent())
6095 Other = *PI;
6096 ++PI;
6097 if (PI != pred_end(Dest)) {
6098 if (*PI != BI->getParent())
6099 if (Other)
6100 Other = 0;
6101 else
6102 Other = *PI;
6103 if (++PI != pred_end(Dest))
6104 Other = 0;
6105 }
6106 if (Other) { // If only one other pred...
6107 BBI = Other->getTerminator();
6108 // Make sure this other block ends in an unconditional branch and that
6109 // there is an instruction before the branch.
6110 if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
6111 BBI != Other->begin()) {
6112 --BBI;
6113 StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
6114
6115 // If this instruction is a store to the same location.
6116 if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
6117 // Okay, we know we can perform this transformation. Insert a PHI
6118 // node now if we need it.
6119 Value *MergedVal = OtherStore->getOperand(0);
6120 if (MergedVal != SI.getOperand(0)) {
6121 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
6122 PN->reserveOperandSpace(2);
6123 PN->addIncoming(SI.getOperand(0), SI.getParent());
6124 PN->addIncoming(OtherStore->getOperand(0), Other);
6125 MergedVal = InsertNewInstBefore(PN, Dest->front());
6126 }
6127
6128 // Advance to a place where it is safe to insert the new store and
6129 // insert it.
6130 BBI = Dest->begin();
6131 while (isa<PHINode>(BBI)) ++BBI;
6132 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
6133 OtherStore->isVolatile()), *BBI);
6134
6135 // Nuke the old stores.
Chris Lattner5997cf92006-02-08 03:25:32 +00006136 EraseInstFromFunction(SI);
6137 EraseInstFromFunction(*OtherStore);
Chris Lattner219175c2005-09-12 23:23:25 +00006138 ++NumCombined;
6139 return 0;
6140 }
6141 }
6142 }
6143 }
6144
Chris Lattner31f486c2005-01-31 05:36:43 +00006145 return 0;
6146}
6147
6148
Chris Lattner9eef8a72003-06-04 04:46:00 +00006149Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
6150 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4fdd96c2005-06-18 17:37:34 +00006151 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00006152 BasicBlock *TrueDest;
6153 BasicBlock *FalseDest;
6154 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
6155 !isa<Constant>(X)) {
6156 // Swap Destinations and condition...
6157 BI.setCondition(X);
6158 BI.setSuccessor(0, FalseDest);
6159 BI.setSuccessor(1, TrueDest);
6160 return &BI;
6161 }
6162
6163 // Cannonicalize setne -> seteq
6164 Instruction::BinaryOps Op; Value *Y;
6165 if (match(&BI, m_Br(m_SetCond(Op, m_Value(X), m_Value(Y)),
6166 TrueDest, FalseDest)))
6167 if ((Op == Instruction::SetNE || Op == Instruction::SetLE ||
6168 Op == Instruction::SetGE) && BI.getCondition()->hasOneUse()) {
6169 SetCondInst *I = cast<SetCondInst>(BI.getCondition());
6170 std::string Name = I->getName(); I->setName("");
6171 Instruction::BinaryOps NewOpcode = SetCondInst::getInverseCondition(Op);
6172 Value *NewSCC = BinaryOperator::create(NewOpcode, X, Y, Name, I);
Chris Lattnere967b342003-06-04 05:10:11 +00006173 // Swap Destinations and condition...
Chris Lattnerd4252a72004-07-30 07:50:03 +00006174 BI.setCondition(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +00006175 BI.setSuccessor(0, FalseDest);
6176 BI.setSuccessor(1, TrueDest);
Chris Lattnerd4252a72004-07-30 07:50:03 +00006177 removeFromWorkList(I);
6178 I->getParent()->getInstList().erase(I);
6179 WorkList.push_back(cast<Instruction>(NewSCC));
Chris Lattnere967b342003-06-04 05:10:11 +00006180 return &BI;
6181 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006182
Chris Lattner9eef8a72003-06-04 04:46:00 +00006183 return 0;
6184}
Chris Lattner1085bdf2002-11-04 16:18:53 +00006185
Chris Lattner4c9c20a2004-07-03 00:26:11 +00006186Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
6187 Value *Cond = SI.getCondition();
6188 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
6189 if (I->getOpcode() == Instruction::Add)
6190 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
6191 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
6192 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattner81a7a232004-10-16 18:11:37 +00006193 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner4c9c20a2004-07-03 00:26:11 +00006194 AddRHS));
6195 SI.setOperand(0, I->getOperand(0));
6196 WorkList.push_back(I);
6197 return &SI;
6198 }
6199 }
6200 return 0;
6201}
6202
Robert Bocchinoa8352962006-01-13 22:48:06 +00006203Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
6204 if (ConstantAggregateZero *C =
6205 dyn_cast<ConstantAggregateZero>(EI.getOperand(0))) {
6206 // If packed val is constant 0, replace extract with scalar 0
6207 const Type *Ty = cast<PackedType>(C->getType())->getElementType();
6208 EI.replaceAllUsesWith(Constant::getNullValue(Ty));
6209 return ReplaceInstUsesWith(EI, Constant::getNullValue(Ty));
6210 }
6211 if (ConstantPacked *C = dyn_cast<ConstantPacked>(EI.getOperand(0))) {
6212 // If packed val is constant with uniform operands, replace EI
6213 // with that operand
6214 Constant *op0 = cast<Constant>(C->getOperand(0));
6215 for (unsigned i = 1; i < C->getNumOperands(); ++i)
6216 if (C->getOperand(i) != op0) return 0;
6217 return ReplaceInstUsesWith(EI, op0);
6218 }
6219 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0)))
6220 if (I->hasOneUse()) {
6221 // Push extractelement into predecessor operation if legal and
6222 // profitable to do so
6223 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
6224 if (!isa<Constant>(BO->getOperand(0)) &&
6225 !isa<Constant>(BO->getOperand(1)))
6226 return 0;
6227 ExtractElementInst *newEI0 =
6228 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
6229 EI.getName());
6230 ExtractElementInst *newEI1 =
6231 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
6232 EI.getName());
6233 InsertNewInstBefore(newEI0, EI);
6234 InsertNewInstBefore(newEI1, EI);
6235 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
6236 }
6237 switch(I->getOpcode()) {
6238 case Instruction::Load: {
6239 Value *Ptr = InsertCastBefore(I->getOperand(0),
6240 PointerType::get(EI.getType()), EI);
6241 GetElementPtrInst *GEP =
6242 new GetElementPtrInst(Ptr, EI.getOperand(1),
6243 I->getName() + ".gep");
6244 InsertNewInstBefore(GEP, EI);
6245 return new LoadInst(GEP);
6246 }
6247 default:
6248 return 0;
6249 }
6250 }
6251 return 0;
6252}
6253
6254
Chris Lattner99f48c62002-09-02 04:59:56 +00006255void InstCombiner::removeFromWorkList(Instruction *I) {
6256 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
6257 WorkList.end());
6258}
6259
Chris Lattner39c98bb2004-12-08 23:43:58 +00006260
6261/// TryToSinkInstruction - Try to move the specified instruction from its
6262/// current block into the beginning of DestBlock, which can only happen if it's
6263/// safe to move the instruction past all of the instructions between it and the
6264/// end of its block.
6265static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
6266 assert(I->hasOneUse() && "Invariants didn't hold!");
6267
Chris Lattnerc4f67e62005-10-27 17:13:11 +00006268 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
6269 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +00006270
Chris Lattner39c98bb2004-12-08 23:43:58 +00006271 // Do not sink alloca instructions out of the entry block.
6272 if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
6273 return false;
6274
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00006275 // We can only sink load instructions if there is nothing between the load and
6276 // the end of block that could change the value.
6277 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00006278 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
6279 Scan != E; ++Scan)
6280 if (Scan->mayWriteToMemory())
6281 return false;
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00006282 }
Chris Lattner39c98bb2004-12-08 23:43:58 +00006283
6284 BasicBlock::iterator InsertPos = DestBlock->begin();
6285 while (isa<PHINode>(InsertPos)) ++InsertPos;
6286
Chris Lattner9f269e42005-08-08 19:11:57 +00006287 I->moveBefore(InsertPos);
Chris Lattner39c98bb2004-12-08 23:43:58 +00006288 ++NumSunkInst;
6289 return true;
6290}
6291
Chris Lattner113f4f42002-06-25 16:13:24 +00006292bool InstCombiner::runOnFunction(Function &F) {
Chris Lattner260ab202002-04-18 17:39:14 +00006293 bool Changed = false;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00006294 TD = &getAnalysis<TargetData>();
Chris Lattnerca081252001-12-14 16:52:21 +00006295
Chris Lattner4ed40f72005-07-07 20:40:38 +00006296 {
6297 // Populate the worklist with the reachable instructions.
6298 std::set<BasicBlock*> Visited;
6299 for (df_ext_iterator<BasicBlock*> BB = df_ext_begin(&F.front(), Visited),
6300 E = df_ext_end(&F.front(), Visited); BB != E; ++BB)
6301 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
6302 WorkList.push_back(I);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00006303
Chris Lattner4ed40f72005-07-07 20:40:38 +00006304 // Do a quick scan over the function. If we find any blocks that are
6305 // unreachable, remove any instructions inside of them. This prevents
6306 // the instcombine code from having to deal with some bad special cases.
6307 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
6308 if (!Visited.count(BB)) {
6309 Instruction *Term = BB->getTerminator();
6310 while (Term != BB->begin()) { // Remove instrs bottom-up
6311 BasicBlock::iterator I = Term; --I;
Chris Lattner2d3a7a62004-04-27 15:13:33 +00006312
Chris Lattner4ed40f72005-07-07 20:40:38 +00006313 DEBUG(std::cerr << "IC: DCE: " << *I);
6314 ++NumDeadInst;
6315
6316 if (!I->use_empty())
6317 I->replaceAllUsesWith(UndefValue::get(I->getType()));
6318 I->eraseFromParent();
6319 }
6320 }
6321 }
Chris Lattnerca081252001-12-14 16:52:21 +00006322
6323 while (!WorkList.empty()) {
6324 Instruction *I = WorkList.back(); // Get an instruction from the worklist
6325 WorkList.pop_back();
6326
Misha Brukman632df282002-10-29 23:06:16 +00006327 // Check to see if we can DCE or ConstantPropagate the instruction...
Chris Lattner99f48c62002-09-02 04:59:56 +00006328 // Check to see if we can DIE the instruction...
6329 if (isInstructionTriviallyDead(I)) {
6330 // Add operands to the worklist...
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00006331 if (I->getNumOperands() < 4)
Chris Lattner51ea1272004-02-28 05:22:00 +00006332 AddUsesToWorkList(*I);
Chris Lattner99f48c62002-09-02 04:59:56 +00006333 ++NumDeadInst;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00006334
Chris Lattnercd517ff2005-01-28 19:32:01 +00006335 DEBUG(std::cerr << "IC: DCE: " << *I);
6336
6337 I->eraseFromParent();
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00006338 removeFromWorkList(I);
6339 continue;
6340 }
Chris Lattner99f48c62002-09-02 04:59:56 +00006341
Misha Brukman632df282002-10-29 23:06:16 +00006342 // Instruction isn't dead, see if we can constant propagate it...
Chris Lattner99f48c62002-09-02 04:59:56 +00006343 if (Constant *C = ConstantFoldInstruction(I)) {
Alkis Evlogimenosa1291a02004-12-08 23:10:30 +00006344 Value* Ptr = I->getOperand(0);
Chris Lattner6580e092004-10-16 19:44:59 +00006345 if (isa<GetElementPtrInst>(I) &&
Alkis Evlogimenosa1291a02004-12-08 23:10:30 +00006346 cast<Constant>(Ptr)->isNullValue() &&
6347 !isa<ConstantPointerNull>(C) &&
6348 cast<PointerType>(Ptr->getType())->getElementType()->isSized()) {
Chris Lattner6580e092004-10-16 19:44:59 +00006349 // If this is a constant expr gep that is effectively computing an
6350 // "offsetof", fold it into 'cast int X to T*' instead of 'gep 0, 0, 12'
6351 bool isFoldableGEP = true;
6352 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i)
6353 if (!isa<ConstantInt>(I->getOperand(i)))
6354 isFoldableGEP = false;
6355 if (isFoldableGEP) {
Alkis Evlogimenosa1291a02004-12-08 23:10:30 +00006356 uint64_t Offset = TD->getIndexedOffset(Ptr->getType(),
Chris Lattner6580e092004-10-16 19:44:59 +00006357 std::vector<Value*>(I->op_begin()+1, I->op_end()));
6358 C = ConstantUInt::get(Type::ULongTy, Offset);
Chris Lattner684c5c62004-10-16 19:46:33 +00006359 C = ConstantExpr::getCast(C, TD->getIntPtrType());
Chris Lattner6580e092004-10-16 19:44:59 +00006360 C = ConstantExpr::getCast(C, I->getType());
6361 }
6362 }
6363
Chris Lattnercd517ff2005-01-28 19:32:01 +00006364 DEBUG(std::cerr << "IC: ConstFold to: " << *C << " from: " << *I);
6365
Chris Lattner99f48c62002-09-02 04:59:56 +00006366 // Add operands to the worklist...
Chris Lattner51ea1272004-02-28 05:22:00 +00006367 AddUsesToWorkList(*I);
Chris Lattnerc6509f42002-12-05 22:41:53 +00006368 ReplaceInstUsesWith(*I, C);
6369
Chris Lattner99f48c62002-09-02 04:59:56 +00006370 ++NumConstProp;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00006371 I->getParent()->getInstList().erase(I);
Chris Lattner800aaaf2003-10-07 15:17:02 +00006372 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00006373 continue;
Chris Lattner99f48c62002-09-02 04:59:56 +00006374 }
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00006375
Chris Lattner39c98bb2004-12-08 23:43:58 +00006376 // See if we can trivially sink this instruction to a successor basic block.
6377 if (I->hasOneUse()) {
6378 BasicBlock *BB = I->getParent();
6379 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
6380 if (UserParent != BB) {
6381 bool UserIsSuccessor = false;
6382 // See if the user is one of our successors.
6383 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
6384 if (*SI == UserParent) {
6385 UserIsSuccessor = true;
6386 break;
6387 }
6388
6389 // If the user is one of our immediate successors, and if that successor
6390 // only has us as a predecessors (we'd have to split the critical edge
6391 // otherwise), we can keep going.
6392 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
6393 next(pred_begin(UserParent)) == pred_end(UserParent))
6394 // Okay, the CFG is simple enough, try to sink this instruction.
6395 Changed |= TryToSinkInstruction(I, UserParent);
6396 }
6397 }
6398
Chris Lattnerca081252001-12-14 16:52:21 +00006399 // Now that we have an instruction, try combining it to simplify it...
Chris Lattnerae7a0d32002-08-02 19:29:35 +00006400 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +00006401 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +00006402 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +00006403 if (Result != I) {
Chris Lattner7d2a5392004-03-13 23:54:27 +00006404 DEBUG(std::cerr << "IC: Old = " << *I
6405 << " New = " << *Result);
6406
Chris Lattner396dbfe2004-06-09 05:08:07 +00006407 // Everything uses the new instruction now.
6408 I->replaceAllUsesWith(Result);
6409
6410 // Push the new instruction and any users onto the worklist.
6411 WorkList.push_back(Result);
6412 AddUsersToWorkList(*Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00006413
6414 // Move the name to the new instruction first...
6415 std::string OldName = I->getName(); I->setName("");
Chris Lattner950fc782003-10-07 22:58:41 +00006416 Result->setName(OldName);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00006417
6418 // Insert the new instruction into the basic block...
6419 BasicBlock *InstParent = I->getParent();
Chris Lattner7515cab2004-11-14 19:13:23 +00006420 BasicBlock::iterator InsertPos = I;
6421
6422 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
6423 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
6424 ++InsertPos;
6425
6426 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00006427
Chris Lattner63d75af2004-05-01 23:27:23 +00006428 // Make sure that we reprocess all operands now that we reduced their
6429 // use counts.
Chris Lattnerb643a9e2004-05-01 23:19:52 +00006430 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
6431 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
6432 WorkList.push_back(OpI);
6433
Chris Lattner396dbfe2004-06-09 05:08:07 +00006434 // Instructions can end up on the worklist more than once. Make sure
6435 // we do not process an instruction that has been deleted.
6436 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00006437
6438 // Erase the old instruction.
6439 InstParent->getInstList().erase(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00006440 } else {
Chris Lattner7d2a5392004-03-13 23:54:27 +00006441 DEBUG(std::cerr << "IC: MOD = " << *I);
6442
Chris Lattnerae7a0d32002-08-02 19:29:35 +00006443 // If the instruction was modified, it's possible that it is now dead.
6444 // if so, remove it.
Chris Lattner63d75af2004-05-01 23:27:23 +00006445 if (isInstructionTriviallyDead(I)) {
6446 // Make sure we process all operands now that we are reducing their
6447 // use counts.
6448 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
6449 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
6450 WorkList.push_back(OpI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00006451
Chris Lattner63d75af2004-05-01 23:27:23 +00006452 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchinoa8352962006-01-13 22:48:06 +00006453 // occurrences of this instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00006454 removeFromWorkList(I);
Chris Lattner31f486c2005-01-31 05:36:43 +00006455 I->eraseFromParent();
Chris Lattner396dbfe2004-06-09 05:08:07 +00006456 } else {
6457 WorkList.push_back(Result);
6458 AddUsersToWorkList(*Result);
Chris Lattnerae7a0d32002-08-02 19:29:35 +00006459 }
Chris Lattner053c0932002-05-14 15:24:07 +00006460 }
Chris Lattner260ab202002-04-18 17:39:14 +00006461 Changed = true;
Chris Lattnerca081252001-12-14 16:52:21 +00006462 }
6463 }
6464
Chris Lattner260ab202002-04-18 17:39:14 +00006465 return Changed;
Chris Lattner04805fa2002-02-26 21:46:54 +00006466}
6467
Brian Gaeke38b79e82004-07-27 17:43:21 +00006468FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +00006469 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +00006470}
Brian Gaeke960707c2003-11-11 22:41:34 +00006471