blob: 1d44f6b9840a4a4c73cac024cad5894cb652f5fa [file] [log] [blame]
Chris Lattner233f7dc2002-08-12 21:17:25 +00001//===- InstructionCombining.cpp - Combine multiple instructions -----------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner8a2a3112001-12-14 16:52:21 +00009//
10// InstructionCombining - Combine instructions to form fewer, simple
Chris Lattner62b14df2002-09-02 04:59:56 +000011// instructions. This pass does not modify the CFG This pass is where algebraic
12// simplification happens.
Chris Lattner8a2a3112001-12-14 16:52:21 +000013//
14// This pass combines things like:
Chris Lattner318bf792007-03-18 22:51:34 +000015// %Y = add i32 %X, 1
16// %Z = add i32 %Y, 1
Chris Lattner8a2a3112001-12-14 16:52:21 +000017// into:
Chris Lattner318bf792007-03-18 22:51:34 +000018// %Z = add i32 %X, 2
Chris Lattner8a2a3112001-12-14 16:52:21 +000019//
20// This is a simple worklist driven algorithm.
21//
Chris Lattner065a6162003-09-10 05:29:43 +000022// This pass guarantees that the following canonicalizations are performed on
Chris Lattner2cd91962003-07-23 21:41:57 +000023// the program:
24// 1. If a binary operator has a constant operand, it is moved to the RHS
Chris Lattnerdf17af12003-08-12 21:53:41 +000025// 2. Bitwise operators with constant operands are always grouped so that
26// shifts are performed first, then or's, then and's, then xor's.
Reid Spencere4d87aa2006-12-23 06:05:41 +000027// 3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
28// 4. All cmp instructions on boolean values are replaced with logical ops
Chris Lattnere92d2f42003-08-13 04:18:28 +000029// 5. add X, X is represented as (X*2) => (X << 1)
30// 6. Multiplies with a power-of-two constant argument are transformed into
31// shifts.
Chris Lattnerbac32862004-11-14 19:13:23 +000032// ... etc.
Chris Lattner2cd91962003-07-23 21:41:57 +000033//
Chris Lattner8a2a3112001-12-14 16:52:21 +000034//===----------------------------------------------------------------------===//
35
Chris Lattner0cea42a2004-03-13 23:54:27 +000036#define DEBUG_TYPE "instcombine"
Chris Lattner022103b2002-05-07 20:03:00 +000037#include "llvm/Transforms/Scalar.h"
Chris Lattner35b9e482004-10-12 04:52:52 +000038#include "llvm/IntrinsicInst.h"
Chris Lattnerbd0ef772002-02-26 21:46:54 +000039#include "llvm/Pass.h"
Chris Lattner0864acf2002-11-04 16:18:53 +000040#include "llvm/DerivedTypes.h"
Chris Lattner833b8a42003-06-26 05:06:25 +000041#include "llvm/GlobalVariable.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000042#include "llvm/Analysis/ConstantFolding.h"
Chris Lattnerbc61e662003-11-02 05:57:39 +000043#include "llvm/Target/TargetData.h"
44#include "llvm/Transforms/Utils/BasicBlockUtils.h"
45#include "llvm/Transforms/Utils/Local.h"
Chris Lattner28977af2004-04-05 01:30:19 +000046#include "llvm/Support/CallSite.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000047#include "llvm/Support/Debug.h"
Chris Lattner28977af2004-04-05 01:30:19 +000048#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattnerdd841ae2002-04-18 17:39:14 +000049#include "llvm/Support/InstVisitor.h"
Chris Lattnerbcd7db52005-08-02 19:16:58 +000050#include "llvm/Support/MathExtras.h"
Chris Lattneracd1f0f2004-07-30 07:50:03 +000051#include "llvm/Support/PatternMatch.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000052#include "llvm/Support/Compiler.h"
Chris Lattnerdbab3862007-03-02 21:28:56 +000053#include "llvm/ADT/DenseMap.h"
Chris Lattner55eb1c42007-01-31 04:40:53 +000054#include "llvm/ADT/SmallVector.h"
Chris Lattner1f87a582007-02-15 19:41:52 +000055#include "llvm/ADT/SmallPtrSet.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000056#include "llvm/ADT/Statistic.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000057#include "llvm/ADT/STLExtras.h"
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000058#include <algorithm>
Reid Spencer6734b572007-02-04 00:40:42 +000059#include <set>
Chris Lattner67b1e1b2003-12-07 01:24:23 +000060using namespace llvm;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000061using namespace llvm::PatternMatch;
Brian Gaeked0fde302003-11-11 22:41:34 +000062
Chris Lattner0e5f4992006-12-19 21:40:18 +000063STATISTIC(NumCombined , "Number of insts combined");
64STATISTIC(NumConstProp, "Number of constant folds");
65STATISTIC(NumDeadInst , "Number of dead inst eliminated");
66STATISTIC(NumDeadStore, "Number of dead stores eliminated");
67STATISTIC(NumSunkInst , "Number of instructions sunk");
Chris Lattnera92f6962002-10-01 22:38:41 +000068
Chris Lattner0e5f4992006-12-19 21:40:18 +000069namespace {
Chris Lattnerf4b54612006-06-28 22:08:15 +000070 class VISIBILITY_HIDDEN InstCombiner
71 : public FunctionPass,
72 public InstVisitor<InstCombiner, Instruction*> {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000073 // Worklist of all of the instructions that need to be simplified.
Chris Lattnerdbab3862007-03-02 21:28:56 +000074 std::vector<Instruction*> Worklist;
75 DenseMap<Instruction*, unsigned> WorklistMap;
Chris Lattnerbc61e662003-11-02 05:57:39 +000076 TargetData *TD;
Chris Lattnerf964f322007-03-04 04:27:24 +000077 bool MustPreserveLCSSA;
Chris Lattnerdbab3862007-03-02 21:28:56 +000078 public:
79 /// AddToWorkList - Add the specified instruction to the worklist if it
80 /// isn't already in it.
81 void AddToWorkList(Instruction *I) {
82 if (WorklistMap.insert(std::make_pair(I, Worklist.size())))
83 Worklist.push_back(I);
84 }
85
86 // RemoveFromWorkList - remove I from the worklist if it exists.
87 void RemoveFromWorkList(Instruction *I) {
88 DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
89 if (It == WorklistMap.end()) return; // Not in worklist.
90
91 // Don't bother moving everything down, just null out the slot.
92 Worklist[It->second] = 0;
93
94 WorklistMap.erase(It);
95 }
96
97 Instruction *RemoveOneFromWorkList() {
98 Instruction *I = Worklist.back();
99 Worklist.pop_back();
100 WorklistMap.erase(I);
101 return I;
102 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000103
Chris Lattnerdbab3862007-03-02 21:28:56 +0000104
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000105 /// AddUsersToWorkList - When an instruction is simplified, add all users of
106 /// the instruction to the work lists because they might get more simplified
107 /// now.
108 ///
Chris Lattner6dce1a72006-02-07 06:56:34 +0000109 void AddUsersToWorkList(Value &I) {
Chris Lattner7e708292002-06-25 16:13:24 +0000110 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000111 UI != UE; ++UI)
Chris Lattnerdbab3862007-03-02 21:28:56 +0000112 AddToWorkList(cast<Instruction>(*UI));
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000113 }
114
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000115 /// AddUsesToWorkList - When an instruction is simplified, add operands to
116 /// the work lists because they might get more simplified now.
117 ///
118 void AddUsesToWorkList(Instruction &I) {
119 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
120 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
Chris Lattnerdbab3862007-03-02 21:28:56 +0000121 AddToWorkList(Op);
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000122 }
Chris Lattner867b99f2006-10-05 06:55:50 +0000123
124 /// AddSoonDeadInstToWorklist - The specified instruction is about to become
125 /// dead. Add all of its operands to the worklist, turning them into
126 /// undef's to reduce the number of uses of those instructions.
127 ///
128 /// Return the specified operand before it is turned into an undef.
129 ///
130 Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
131 Value *R = I.getOperand(op);
132
133 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
134 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i))) {
Chris Lattnerdbab3862007-03-02 21:28:56 +0000135 AddToWorkList(Op);
Chris Lattner867b99f2006-10-05 06:55:50 +0000136 // Set the operand to undef to drop the use.
137 I.setOperand(i, UndefValue::get(Op->getType()));
138 }
139
140 return R;
141 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000142
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000143 public:
Chris Lattner7e708292002-06-25 16:13:24 +0000144 virtual bool runOnFunction(Function &F);
Chris Lattnerec9c3582007-03-03 02:04:50 +0000145
146 bool DoOneIteration(Function &F, unsigned ItNum);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000147
Chris Lattner97e52e42002-04-28 21:27:06 +0000148 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerbc61e662003-11-02 05:57:39 +0000149 AU.addRequired<TargetData>();
Owen Andersond1b78a12006-07-10 19:03:49 +0000150 AU.addPreservedID(LCSSAID);
Chris Lattnercb2610e2002-10-21 20:00:28 +0000151 AU.setPreservesCFG();
Chris Lattner97e52e42002-04-28 21:27:06 +0000152 }
153
Chris Lattner28977af2004-04-05 01:30:19 +0000154 TargetData &getTargetData() const { return *TD; }
155
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000156 // Visitation implementation - Implement instruction combining for different
157 // instruction types. The semantics are as follows:
158 // Return Value:
159 // null - No change was made
Chris Lattner233f7dc2002-08-12 21:17:25 +0000160 // I - Change was made, I is still valid, I may be dead though
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000161 // otherwise - Change was made, replace I with returned instruction
Misha Brukmanfd939082005-04-21 23:48:37 +0000162 //
Chris Lattner7e708292002-06-25 16:13:24 +0000163 Instruction *visitAdd(BinaryOperator &I);
164 Instruction *visitSub(BinaryOperator &I);
165 Instruction *visitMul(BinaryOperator &I);
Reid Spencer0a783f72006-11-02 01:53:59 +0000166 Instruction *visitURem(BinaryOperator &I);
167 Instruction *visitSRem(BinaryOperator &I);
168 Instruction *visitFRem(BinaryOperator &I);
169 Instruction *commonRemTransforms(BinaryOperator &I);
170 Instruction *commonIRemTransforms(BinaryOperator &I);
Reid Spencer1628cec2006-10-26 06:15:43 +0000171 Instruction *commonDivTransforms(BinaryOperator &I);
172 Instruction *commonIDivTransforms(BinaryOperator &I);
173 Instruction *visitUDiv(BinaryOperator &I);
174 Instruction *visitSDiv(BinaryOperator &I);
175 Instruction *visitFDiv(BinaryOperator &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000176 Instruction *visitAnd(BinaryOperator &I);
177 Instruction *visitOr (BinaryOperator &I);
178 Instruction *visitXor(BinaryOperator &I);
Reid Spencer832254e2007-02-02 02:16:23 +0000179 Instruction *visitShl(BinaryOperator &I);
180 Instruction *visitAShr(BinaryOperator &I);
181 Instruction *visitLShr(BinaryOperator &I);
182 Instruction *commonShiftTransforms(BinaryOperator &I);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000183 Instruction *visitFCmpInst(FCmpInst &I);
184 Instruction *visitICmpInst(ICmpInst &I);
185 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
Chris Lattner484d3cf2005-04-24 06:59:08 +0000186
Reid Spencere4d87aa2006-12-23 06:05:41 +0000187 Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
188 ICmpInst::Predicate Cond, Instruction &I);
Reid Spencerb83eb642006-10-20 07:07:24 +0000189 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +0000190 BinaryOperator &I);
Reid Spencer3da59db2006-11-27 01:05:10 +0000191 Instruction *commonCastTransforms(CastInst &CI);
192 Instruction *commonIntCastTransforms(CastInst &CI);
193 Instruction *visitTrunc(CastInst &CI);
194 Instruction *visitZExt(CastInst &CI);
195 Instruction *visitSExt(CastInst &CI);
196 Instruction *visitFPTrunc(CastInst &CI);
197 Instruction *visitFPExt(CastInst &CI);
198 Instruction *visitFPToUI(CastInst &CI);
199 Instruction *visitFPToSI(CastInst &CI);
200 Instruction *visitUIToFP(CastInst &CI);
201 Instruction *visitSIToFP(CastInst &CI);
202 Instruction *visitPtrToInt(CastInst &CI);
203 Instruction *visitIntToPtr(CastInst &CI);
204 Instruction *visitBitCast(CastInst &CI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +0000205 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
206 Instruction *FI);
Chris Lattner3d69f462004-03-12 05:52:32 +0000207 Instruction *visitSelectInst(SelectInst &CI);
Chris Lattner9fe38862003-06-19 17:00:31 +0000208 Instruction *visitCallInst(CallInst &CI);
209 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner7e708292002-06-25 16:13:24 +0000210 Instruction *visitPHINode(PHINode &PN);
211 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner0864acf2002-11-04 16:18:53 +0000212 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner67b1e1b2003-12-07 01:24:23 +0000213 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner833b8a42003-06-26 05:06:25 +0000214 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner2f503e62005-01-31 05:36:43 +0000215 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattnerc4d10eb2003-06-04 04:46:00 +0000216 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner46238a62004-07-03 00:26:11 +0000217 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattnerefb47352006-04-15 01:39:45 +0000218 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchino1d7456d2006-01-13 22:48:06 +0000219 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +0000220 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000221
222 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner7e708292002-06-25 16:13:24 +0000223 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner8b170942002-08-09 23:47:40 +0000224
Chris Lattner9fe38862003-06-19 17:00:31 +0000225 private:
Chris Lattnera44d8a22003-10-07 22:32:43 +0000226 Instruction *visitCallSite(CallSite CS);
Chris Lattner9fe38862003-06-19 17:00:31 +0000227 bool transformConstExprCastCall(CallSite CS);
228
Chris Lattner28977af2004-04-05 01:30:19 +0000229 public:
Chris Lattner8b170942002-08-09 23:47:40 +0000230 // InsertNewInstBefore - insert an instruction New before instruction Old
231 // in the program. Add the new instruction to the worklist.
232 //
Chris Lattner955f3312004-09-28 21:48:02 +0000233 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattnere6f9a912002-08-23 18:32:43 +0000234 assert(New && New->getParent() == 0 &&
235 "New instruction already inserted into a basic block!");
Chris Lattner8b170942002-08-09 23:47:40 +0000236 BasicBlock *BB = Old.getParent();
237 BB->getInstList().insert(&Old, New); // Insert inst
Chris Lattnerdbab3862007-03-02 21:28:56 +0000238 AddToWorkList(New);
Chris Lattner4cb170c2004-02-23 06:38:22 +0000239 return New;
Chris Lattner8b170942002-08-09 23:47:40 +0000240 }
241
Chris Lattner0c967662004-09-24 15:21:34 +0000242 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
243 /// This also adds the cast to the worklist. Finally, this returns the
244 /// cast.
Reid Spencer17212df2006-12-12 09:18:51 +0000245 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
246 Instruction &Pos) {
Chris Lattner0c967662004-09-24 15:21:34 +0000247 if (V->getType() == Ty) return V;
Misha Brukmanfd939082005-04-21 23:48:37 +0000248
Chris Lattnere2ed0572006-04-06 19:19:17 +0000249 if (Constant *CV = dyn_cast<Constant>(V))
Reid Spencer17212df2006-12-12 09:18:51 +0000250 return ConstantExpr::getCast(opc, CV, Ty);
Chris Lattnere2ed0572006-04-06 19:19:17 +0000251
Reid Spencer17212df2006-12-12 09:18:51 +0000252 Instruction *C = CastInst::create(opc, V, Ty, V->getName(), &Pos);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000253 AddToWorkList(C);
Chris Lattner0c967662004-09-24 15:21:34 +0000254 return C;
255 }
256
Chris Lattner8b170942002-08-09 23:47:40 +0000257 // ReplaceInstUsesWith - This method is to be used when an instruction is
258 // found to be dead, replacable with another preexisting expression. Here
259 // we add all uses of I to the worklist, replace all uses of I with the new
260 // value, then return I, so that the inst combiner will know that I was
261 // modified.
262 //
263 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000264 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner15a76c02004-04-05 02:10:19 +0000265 if (&I != V) {
266 I.replaceAllUsesWith(V);
267 return &I;
268 } else {
269 // If we are replacing the instruction with itself, this must be in a
270 // segment of unreachable code, so just clobber the instruction.
Chris Lattner17be6352004-10-18 02:59:09 +0000271 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +0000272 return &I;
273 }
Chris Lattner8b170942002-08-09 23:47:40 +0000274 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000275
Chris Lattner6dce1a72006-02-07 06:56:34 +0000276 // UpdateValueUsesWith - This method is to be used when an value is
277 // found to be replacable with another preexisting expression or was
278 // updated. Here we add all uses of I to the worklist, replace all uses of
279 // I with the new value (unless the instruction was just updated), then
280 // return true, so that the inst combiner will know that I was modified.
281 //
282 bool UpdateValueUsesWith(Value *Old, Value *New) {
283 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
284 if (Old != New)
285 Old->replaceAllUsesWith(New);
286 if (Instruction *I = dyn_cast<Instruction>(Old))
Chris Lattnerdbab3862007-03-02 21:28:56 +0000287 AddToWorkList(I);
Chris Lattnerf8c36f52006-02-12 08:02:11 +0000288 if (Instruction *I = dyn_cast<Instruction>(New))
Chris Lattnerdbab3862007-03-02 21:28:56 +0000289 AddToWorkList(I);
Chris Lattner6dce1a72006-02-07 06:56:34 +0000290 return true;
291 }
292
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000293 // EraseInstFromFunction - When dealing with an instruction that has side
294 // effects or produces a void value, we can't rely on DCE to delete the
295 // instruction. Instead, visit methods should return the value returned by
296 // this function.
297 Instruction *EraseInstFromFunction(Instruction &I) {
298 assert(I.use_empty() && "Cannot erase instruction that is used!");
299 AddUsesToWorkList(I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000300 RemoveFromWorkList(&I);
Chris Lattner954f66a2004-11-18 21:41:39 +0000301 I.eraseFromParent();
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000302 return 0; // Don't do anything with FI
303 }
304
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000305 private:
Chris Lattner24c8e382003-07-24 17:35:25 +0000306 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
307 /// InsertBefore instruction. This is specialized a bit to avoid inserting
308 /// casts that are known to not do anything...
309 ///
Reid Spencer17212df2006-12-12 09:18:51 +0000310 Value *InsertOperandCastBefore(Instruction::CastOps opcode,
311 Value *V, const Type *DestTy,
Chris Lattner24c8e382003-07-24 17:35:25 +0000312 Instruction *InsertBefore);
313
Reid Spencere4d87aa2006-12-23 06:05:41 +0000314 /// SimplifyCommutative - This performs a few simplifications for
315 /// commutative operators.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000316 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000317
Reid Spencere4d87aa2006-12-23 06:05:41 +0000318 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
319 /// most-complex to least-complex order.
320 bool SimplifyCompare(CmpInst &I);
321
Reid Spencer8cb68342007-03-12 17:25:59 +0000322 bool SimplifyDemandedBits(Value *V, uint64_t DemandedMask,
Chris Lattner255d8912006-02-11 09:31:47 +0000323 uint64_t &KnownZero, uint64_t &KnownOne,
324 unsigned Depth = 0);
Chris Lattner4e998b22004-09-29 05:07:12 +0000325
Reid Spencer8cb68342007-03-12 17:25:59 +0000326 bool SimplifyDemandedBits(Value *V, APInt DemandedMask,
327 APInt& KnownZero, APInt& KnownOne,
328 unsigned Depth = 0);
329
Chris Lattner867b99f2006-10-05 06:55:50 +0000330 Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
331 uint64_t &UndefElts, unsigned Depth = 0);
332
Chris Lattner4e998b22004-09-29 05:07:12 +0000333 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
334 // PHI node as operand #0, see if we can fold the instruction into the PHI
335 // (which is only possible if all operands to the PHI are constants).
336 Instruction *FoldOpIntoPhi(Instruction &I);
337
Chris Lattnerbac32862004-11-14 19:13:23 +0000338 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
339 // operator and they all are only used by the PHI, PHI together their
340 // inputs, and do the operation once, to the result of the PHI.
341 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
Chris Lattner7da52b22006-11-01 04:51:18 +0000342 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
343
344
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000345 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
346 ConstantInt *AndRHS, BinaryOperator &TheAnd);
Chris Lattnerc8e77562005-09-18 04:24:45 +0000347
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000348 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
Chris Lattnerc8e77562005-09-18 04:24:45 +0000349 bool isSub, Instruction &I);
Chris Lattnera96879a2004-09-29 17:40:11 +0000350 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000351 bool isSigned, bool Inside, Instruction &IB);
Chris Lattnerb3f83972005-10-24 06:03:58 +0000352 Instruction *PromoteCastOfAllocation(CastInst &CI, AllocationInst &AI);
Chris Lattnerafe91a52006-06-15 19:07:26 +0000353 Instruction *MatchBSwap(BinaryOperator &I);
354
Reid Spencerc55b2432006-12-13 18:21:21 +0000355 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000356 };
Chris Lattnerf6293092002-07-23 18:06:35 +0000357
Chris Lattner7f8897f2006-08-27 22:42:52 +0000358 RegisterPass<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000359}
360
Chris Lattner4f98c562003-03-10 21:43:22 +0000361// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattnere87597f2004-10-16 18:11:37 +0000362// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattner4f98c562003-03-10 21:43:22 +0000363static unsigned getComplexity(Value *V) {
364 if (isa<Instruction>(V)) {
365 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattnere87597f2004-10-16 18:11:37 +0000366 return 3;
367 return 4;
Chris Lattner4f98c562003-03-10 21:43:22 +0000368 }
Chris Lattnere87597f2004-10-16 18:11:37 +0000369 if (isa<Argument>(V)) return 3;
370 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattner4f98c562003-03-10 21:43:22 +0000371}
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000372
Chris Lattnerc8802d22003-03-11 00:12:48 +0000373// isOnlyUse - Return true if this instruction will be deleted if we stop using
374// it.
375static bool isOnlyUse(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000376 return V->hasOneUse() || isa<Constant>(V);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000377}
378
Chris Lattner4cb170c2004-02-23 06:38:22 +0000379// getPromotedType - Return the specified type promoted as it would be to pass
380// though a va_arg area...
381static const Type *getPromotedType(const Type *Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000382 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
383 if (ITy->getBitWidth() < 32)
384 return Type::Int32Ty;
385 } else if (Ty == Type::FloatTy)
386 return Type::DoubleTy;
387 return Ty;
Chris Lattner4cb170c2004-02-23 06:38:22 +0000388}
389
Reid Spencer3da59db2006-11-27 01:05:10 +0000390/// getBitCastOperand - If the specified operand is a CastInst or a constant
391/// expression bitcast, return the operand value, otherwise return null.
392static Value *getBitCastOperand(Value *V) {
393 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
Chris Lattnereed48272005-09-13 00:40:14 +0000394 return I->getOperand(0);
395 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Reid Spencer3da59db2006-11-27 01:05:10 +0000396 if (CE->getOpcode() == Instruction::BitCast)
Chris Lattnereed48272005-09-13 00:40:14 +0000397 return CE->getOperand(0);
398 return 0;
399}
400
Reid Spencer3da59db2006-11-27 01:05:10 +0000401/// This function is a wrapper around CastInst::isEliminableCastPair. It
402/// simply extracts arguments and returns what that function returns.
Reid Spencer3da59db2006-11-27 01:05:10 +0000403static Instruction::CastOps
404isEliminableCastPair(
405 const CastInst *CI, ///< The first cast instruction
406 unsigned opcode, ///< The opcode of the second cast instruction
407 const Type *DstTy, ///< The target type for the second cast instruction
408 TargetData *TD ///< The target data for pointer size
409) {
410
411 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
412 const Type *MidTy = CI->getType(); // B from above
Chris Lattner33a61132006-05-06 09:00:16 +0000413
Reid Spencer3da59db2006-11-27 01:05:10 +0000414 // Get the opcodes of the two Cast instructions
415 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
416 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner33a61132006-05-06 09:00:16 +0000417
Reid Spencer3da59db2006-11-27 01:05:10 +0000418 return Instruction::CastOps(
419 CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
420 DstTy, TD->getIntPtrType()));
Chris Lattner33a61132006-05-06 09:00:16 +0000421}
422
423/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
424/// in any code being generated. It does not require codegen if V is simple
425/// enough or if the cast can be folded into other casts.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000426static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
427 const Type *Ty, TargetData *TD) {
Chris Lattner33a61132006-05-06 09:00:16 +0000428 if (V->getType() == Ty || isa<Constant>(V)) return false;
429
Chris Lattner01575b72006-05-25 23:24:33 +0000430 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner33a61132006-05-06 09:00:16 +0000431 if (const CastInst *CI = dyn_cast<CastInst>(V))
Reid Spencere4d87aa2006-12-23 06:05:41 +0000432 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner33a61132006-05-06 09:00:16 +0000433 return false;
434 return true;
435}
436
437/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
438/// InsertBefore instruction. This is specialized a bit to avoid inserting
439/// casts that are known to not do anything...
440///
Reid Spencer17212df2006-12-12 09:18:51 +0000441Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
442 Value *V, const Type *DestTy,
Chris Lattner33a61132006-05-06 09:00:16 +0000443 Instruction *InsertBefore) {
444 if (V->getType() == DestTy) return V;
445 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencer17212df2006-12-12 09:18:51 +0000446 return ConstantExpr::getCast(opcode, C, DestTy);
Chris Lattner33a61132006-05-06 09:00:16 +0000447
Reid Spencer17212df2006-12-12 09:18:51 +0000448 return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
Chris Lattner33a61132006-05-06 09:00:16 +0000449}
450
Chris Lattner4f98c562003-03-10 21:43:22 +0000451// SimplifyCommutative - This performs a few simplifications for commutative
452// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000453//
Chris Lattner4f98c562003-03-10 21:43:22 +0000454// 1. Order operands such that they are listed from right (least complex) to
455// left (most complex). This puts constants before unary operators before
456// binary operators.
457//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000458// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
459// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000460//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000461bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000462 bool Changed = false;
463 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
464 Changed = !I.swapOperands();
Misha Brukmanfd939082005-04-21 23:48:37 +0000465
Chris Lattner4f98c562003-03-10 21:43:22 +0000466 if (!I.isAssociative()) return Changed;
467 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000468 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
469 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
470 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner2a9c8472003-05-27 16:40:51 +0000471 Constant *Folded = ConstantExpr::get(I.getOpcode(),
472 cast<Constant>(I.getOperand(1)),
473 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000474 I.setOperand(0, Op->getOperand(0));
475 I.setOperand(1, Folded);
476 return true;
477 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
478 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
479 isOnlyUse(Op) && isOnlyUse(Op1)) {
480 Constant *C1 = cast<Constant>(Op->getOperand(1));
481 Constant *C2 = cast<Constant>(Op1->getOperand(1));
482
483 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner2a9c8472003-05-27 16:40:51 +0000484 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000485 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
486 Op1->getOperand(0),
487 Op1->getName(), &I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000488 AddToWorkList(New);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000489 I.setOperand(0, New);
490 I.setOperand(1, Folded);
491 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000492 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000493 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000494 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000495}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000496
Reid Spencere4d87aa2006-12-23 06:05:41 +0000497/// SimplifyCompare - For a CmpInst this function just orders the operands
498/// so that theyare listed from right (least complex) to left (most complex).
499/// This puts constants before unary operators before binary operators.
500bool InstCombiner::SimplifyCompare(CmpInst &I) {
501 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
502 return false;
503 I.swapOperands();
504 // Compare instructions are not associative so there's nothing else we can do.
505 return true;
506}
507
Chris Lattner8d969642003-03-10 23:06:50 +0000508// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
509// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000510//
Chris Lattner8d969642003-03-10 23:06:50 +0000511static inline Value *dyn_castNegVal(Value *V) {
512 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000513 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000514
Chris Lattner0ce85802004-12-14 20:08:06 +0000515 // Constants can be considered to be negated values if they can be folded.
516 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
517 return ConstantExpr::getNeg(C);
Chris Lattner8d969642003-03-10 23:06:50 +0000518 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000519}
520
Chris Lattner8d969642003-03-10 23:06:50 +0000521static inline Value *dyn_castNotVal(Value *V) {
522 if (BinaryOperator::isNot(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000523 return BinaryOperator::getNotArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000524
525 // Constants can be considered to be not'ed values...
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000526 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Chris Lattner448c3232004-06-10 02:12:35 +0000527 return ConstantExpr::getNot(C);
Chris Lattner8d969642003-03-10 23:06:50 +0000528 return 0;
529}
530
Chris Lattnerc8802d22003-03-11 00:12:48 +0000531// dyn_castFoldableMul - If this value is a multiply that can be folded into
532// other computations (because it has a constant operand), return the
Chris Lattner50af16a2004-11-13 19:50:12 +0000533// non-constant operand of the multiply, and set CST to point to the multiplier.
534// Otherwise, return null.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000535//
Chris Lattner50af16a2004-11-13 19:50:12 +0000536static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattner42a75512007-01-15 02:27:26 +0000537 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner50af16a2004-11-13 19:50:12 +0000538 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000539 if (I->getOpcode() == Instruction::Mul)
Chris Lattner50e60c72004-11-15 05:54:07 +0000540 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000541 return I->getOperand(0);
Chris Lattner50af16a2004-11-13 19:50:12 +0000542 if (I->getOpcode() == Instruction::Shl)
Chris Lattner50e60c72004-11-15 05:54:07 +0000543 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000544 // The multiplier is really 1 << CST.
545 Constant *One = ConstantInt::get(V->getType(), 1);
546 CST = cast<ConstantInt>(ConstantExpr::getShl(One, CST));
547 return I->getOperand(0);
548 }
549 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000550 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000551}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000552
Chris Lattner574da9b2005-01-13 20:14:25 +0000553/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
554/// expression, return it.
555static User *dyn_castGetElementPtr(Value *V) {
556 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
557 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
558 if (CE->getOpcode() == Instruction::GetElementPtr)
559 return cast<User>(V);
560 return false;
561}
562
Chris Lattner955f3312004-09-28 21:48:02 +0000563// AddOne, SubOne - Add or subtract a constant one from an integer constant...
Chris Lattnera96879a2004-09-29 17:40:11 +0000564static ConstantInt *AddOne(ConstantInt *C) {
565 return cast<ConstantInt>(ConstantExpr::getAdd(C,
566 ConstantInt::get(C->getType(), 1)));
Chris Lattner955f3312004-09-28 21:48:02 +0000567}
Chris Lattnera96879a2004-09-29 17:40:11 +0000568static ConstantInt *SubOne(ConstantInt *C) {
569 return cast<ConstantInt>(ConstantExpr::getSub(C,
570 ConstantInt::get(C->getType(), 1)));
Chris Lattner955f3312004-09-28 21:48:02 +0000571}
572
Chris Lattner68d5ff22006-02-09 07:38:58 +0000573/// ComputeMaskedBits - Determine which of the bits specified in Mask are
574/// known to be either zero or one and return them in the KnownZero/KnownOne
Reid Spencer3e7594f2007-03-08 01:46:38 +0000575/// bit sets. This code only analyzes bits in Mask, in order to short-circuit
576/// processing.
577/// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
578/// we cannot optimize based on the assumption that it is zero without changing
579/// it to be an explicit zero. If we don't change it to zero, other code could
580/// optimized based on the contradictory assumption that it is non-zero.
581/// Because instcombine aggressively folds operations with undef args anyway,
582/// this won't lose us code quality.
583static void ComputeMaskedBits(Value *V, APInt Mask, APInt& KnownZero,
584 APInt& KnownOne, unsigned Depth = 0) {
Zhou Sheng771dbf72007-03-13 02:23:10 +0000585 assert(V && "No Value?");
586 assert(Depth <= 6 && "Limit Search Depth");
Reid Spencer3e7594f2007-03-08 01:46:38 +0000587 uint32_t BitWidth = Mask.getBitWidth();
Zhou Sheng771dbf72007-03-13 02:23:10 +0000588 const IntegerType *VTy = cast<IntegerType>(V->getType());
589 assert(VTy->getBitWidth() == BitWidth &&
590 KnownZero.getBitWidth() == BitWidth &&
Reid Spencer3e7594f2007-03-08 01:46:38 +0000591 KnownOne.getBitWidth() == BitWidth &&
Zhou Sheng771dbf72007-03-13 02:23:10 +0000592 "VTy, Mask, KnownOne and KnownZero should have same BitWidth");
Reid Spencer3e7594f2007-03-08 01:46:38 +0000593 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
594 // We know all of the bits for a constant!
Zhou Sheng771dbf72007-03-13 02:23:10 +0000595 KnownOne = CI->getValue() & Mask;
Reid Spencer3e7594f2007-03-08 01:46:38 +0000596 KnownZero = ~KnownOne & Mask;
597 return;
598 }
599
Reid Spencer3e7594f2007-03-08 01:46:38 +0000600 if (Depth == 6 || Mask == 0)
601 return; // Limit search depth.
602
603 Instruction *I = dyn_cast<Instruction>(V);
604 if (!I) return;
605
Zhou Sheng771dbf72007-03-13 02:23:10 +0000606 KnownZero.clear(); KnownOne.clear(); // Don't know anything.
Reid Spencer3e7594f2007-03-08 01:46:38 +0000607 APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
Zhou Sheng771dbf72007-03-13 02:23:10 +0000608 Mask &= APInt::getAllOnesValue(BitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000609
610 switch (I->getOpcode()) {
611 case Instruction::And:
612 // If either the LHS or the RHS are Zero, the result is zero.
613 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
614 Mask &= ~KnownZero;
615 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
616 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
617 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
618
619 // Output known-1 bits are only known if set in both the LHS & RHS.
620 KnownOne &= KnownOne2;
621 // Output known-0 are known to be clear if zero in either the LHS | RHS.
622 KnownZero |= KnownZero2;
623 return;
624 case Instruction::Or:
625 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
626 Mask &= ~KnownOne;
627 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
628 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
629 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
630
631 // Output known-0 bits are only known if clear in both the LHS & RHS.
632 KnownZero &= KnownZero2;
633 // Output known-1 are known to be set if set in either the LHS | RHS.
634 KnownOne |= KnownOne2;
635 return;
636 case Instruction::Xor: {
637 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
638 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
639 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
640 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
641
642 // Output known-0 bits are known if clear or set in both the LHS & RHS.
643 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
644 // Output known-1 are known to be set if set in only one of the LHS, RHS.
645 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
646 KnownZero = KnownZeroOut;
647 return;
648 }
649 case Instruction::Select:
650 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
651 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
652 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
653 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
654
655 // Only known if known in both the LHS and RHS.
656 KnownOne &= KnownOne2;
657 KnownZero &= KnownZero2;
658 return;
659 case Instruction::FPTrunc:
660 case Instruction::FPExt:
661 case Instruction::FPToUI:
662 case Instruction::FPToSI:
663 case Instruction::SIToFP:
664 case Instruction::PtrToInt:
665 case Instruction::UIToFP:
666 case Instruction::IntToPtr:
667 return; // Can't work with floating point or pointers
Zhou Sheng771dbf72007-03-13 02:23:10 +0000668 case Instruction::Trunc: {
Reid Spencer3e7594f2007-03-08 01:46:38 +0000669 // All these have integer operands
Zhou Sheng771dbf72007-03-13 02:23:10 +0000670 uint32_t SrcBitWidth =
671 cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
672 ComputeMaskedBits(I->getOperand(0), Mask.zext(SrcBitWidth),
673 KnownZero.zext(SrcBitWidth), KnownOne.zext(SrcBitWidth), Depth+1);
674 KnownZero.trunc(BitWidth);
675 KnownOne.trunc(BitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000676 return;
Zhou Sheng771dbf72007-03-13 02:23:10 +0000677 }
Reid Spencer3e7594f2007-03-08 01:46:38 +0000678 case Instruction::BitCast: {
679 const Type *SrcTy = I->getOperand(0)->getType();
680 if (SrcTy->isInteger()) {
681 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
682 return;
683 }
684 break;
685 }
686 case Instruction::ZExt: {
687 // Compute the bits in the result that are not present in the input.
688 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Zhou Sheng9a28daa2007-03-08 05:42:00 +0000689 APInt NewBits(APInt::getAllOnesValue(BitWidth).shl(SrcTy->getBitWidth()));
Reid Spencer3e7594f2007-03-08 01:46:38 +0000690
Zhou Sheng771dbf72007-03-13 02:23:10 +0000691 uint32_t SrcBitWidth = SrcTy->getBitWidth();
692 ComputeMaskedBits(I->getOperand(0), Mask.trunc(SrcBitWidth),
693 KnownZero.trunc(SrcBitWidth), KnownOne.trunc(SrcBitWidth), Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000694 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
695 // The top bits are known to be zero.
Zhou Sheng771dbf72007-03-13 02:23:10 +0000696 KnownZero.zext(BitWidth);
697 KnownOne.zext(BitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000698 KnownZero |= NewBits;
699 return;
700 }
701 case Instruction::SExt: {
702 // Compute the bits in the result that are not present in the input.
703 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Zhou Sheng9a28daa2007-03-08 05:42:00 +0000704 APInt NewBits(APInt::getAllOnesValue(BitWidth).shl(SrcTy->getBitWidth()));
Reid Spencer3e7594f2007-03-08 01:46:38 +0000705
Zhou Sheng771dbf72007-03-13 02:23:10 +0000706 uint32_t SrcBitWidth = SrcTy->getBitWidth();
707 ComputeMaskedBits(I->getOperand(0), Mask.trunc(SrcBitWidth),
708 KnownZero.trunc(SrcBitWidth), KnownOne.trunc(SrcBitWidth), Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000709 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Zhou Sheng771dbf72007-03-13 02:23:10 +0000710 KnownZero.zext(BitWidth);
711 KnownOne.zext(BitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000712
713 // If the sign bit of the input is known set or clear, then we know the
714 // top bits of the result.
Zhou Sheng430f6262007-03-12 05:44:52 +0000715 APInt InSignBit(APInt::getSignBit(SrcTy->getBitWidth()));
Zhou Sheng771dbf72007-03-13 02:23:10 +0000716 InSignBit.zext(BitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000717 if ((KnownZero & InSignBit) != 0) { // Input sign bit known zero
718 KnownZero |= NewBits;
719 KnownOne &= ~NewBits;
720 } else if ((KnownOne & InSignBit) != 0) { // Input sign bit known set
721 KnownOne |= NewBits;
722 KnownZero &= ~NewBits;
723 } else { // Input sign bit unknown
724 KnownZero &= ~NewBits;
725 KnownOne &= ~NewBits;
726 }
727 return;
728 }
729 case Instruction::Shl:
730 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
731 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
732 uint64_t ShiftAmt = SA->getZExtValue();
733 Mask = APIntOps::lshr(Mask, ShiftAmt);
734 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
735 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Zhou Sheng430f6262007-03-12 05:44:52 +0000736 KnownZero <<= ShiftAmt;
737 KnownOne <<= ShiftAmt;
Reid Spencer3e7594f2007-03-08 01:46:38 +0000738 KnownZero |= APInt(BitWidth, 1ULL).shl(ShiftAmt)-1; // low bits known zero.
739 return;
740 }
741 break;
742 case Instruction::LShr:
743 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
744 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
745 // Compute the new bits that are at the top now.
746 uint64_t ShiftAmt = SA->getZExtValue();
747 APInt HighBits(APInt::getAllOnesValue(BitWidth).shl(BitWidth-ShiftAmt));
748
749 // Unsigned shift right.
Zhou Sheng430f6262007-03-12 05:44:52 +0000750 Mask <<= ShiftAmt;
Reid Spencer3e7594f2007-03-08 01:46:38 +0000751 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
752 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
753 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
754 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
755 KnownZero |= HighBits; // high bits known zero.
756 return;
757 }
758 break;
759 case Instruction::AShr:
760 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
761 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
762 // Compute the new bits that are at the top now.
763 uint64_t ShiftAmt = SA->getZExtValue();
764 APInt HighBits(APInt::getAllOnesValue(BitWidth).shl(BitWidth-ShiftAmt));
765
766 // Signed shift right.
Zhou Sheng430f6262007-03-12 05:44:52 +0000767 Mask <<= ShiftAmt;
Reid Spencer3e7594f2007-03-08 01:46:38 +0000768 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
769 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
770 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
771 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
772
773 // Handle the sign bits and adjust to where it is now in the mask.
Zhou Sheng430f6262007-03-12 05:44:52 +0000774 APInt SignBit(APInt::getSignBit(BitWidth).lshr(ShiftAmt));
Reid Spencer3e7594f2007-03-08 01:46:38 +0000775
776 if ((KnownZero & SignBit) != 0) { // New bits are known zero.
777 KnownZero |= HighBits;
778 } else if ((KnownOne & SignBit) != 0) { // New bits are known one.
779 KnownOne |= HighBits;
780 }
781 return;
782 }
783 break;
784 }
785}
786
787/// ComputeMaskedBits - Determine which of the bits specified in Mask are
788/// known to be either zero or one and return them in the KnownZero/KnownOne
Chris Lattner68d5ff22006-02-09 07:38:58 +0000789/// bitsets. This code only analyzes bits in Mask, in order to short-circuit
790/// processing.
Reid Spencer3e7594f2007-03-08 01:46:38 +0000791static void ComputeMaskedBits(Value *V, uint64_t Mask, uint64_t &KnownZero,
Chris Lattner68d5ff22006-02-09 07:38:58 +0000792 uint64_t &KnownOne, unsigned Depth = 0) {
Chris Lattner5931c542005-09-24 23:43:33 +0000793 // Note, we cannot consider 'undef' to be "IsZero" here. The problem is that
794 // we cannot optimize based on the assumption that it is zero without changing
Chris Lattner3bedbd92006-02-07 07:27:52 +0000795 // it to be an explicit zero. If we don't change it to zero, other code could
Chris Lattner5931c542005-09-24 23:43:33 +0000796 // optimized based on the contradictory assumption that it is non-zero.
797 // Because instcombine aggressively folds operations with undef args anyway,
798 // this won't lose us code quality.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000799 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
Chris Lattner68d5ff22006-02-09 07:38:58 +0000800 // We know all of the bits for a constant!
Chris Lattner255d8912006-02-11 09:31:47 +0000801 KnownOne = CI->getZExtValue() & Mask;
Chris Lattner68d5ff22006-02-09 07:38:58 +0000802 KnownZero = ~KnownOne & Mask;
803 return;
804 }
805
806 KnownZero = KnownOne = 0; // Don't know anything.
Chris Lattner74c51a02006-02-07 08:05:22 +0000807 if (Depth == 6 || Mask == 0)
Chris Lattner68d5ff22006-02-09 07:38:58 +0000808 return; // Limit search depth.
809
810 uint64_t KnownZero2, KnownOne2;
Chris Lattner255d8912006-02-11 09:31:47 +0000811 Instruction *I = dyn_cast<Instruction>(V);
812 if (!I) return;
813
Reid Spencerc1030572007-01-19 21:13:56 +0000814 Mask &= cast<IntegerType>(V->getType())->getBitMask();
Chris Lattnere3158302006-05-04 17:33:35 +0000815
Chris Lattner255d8912006-02-11 09:31:47 +0000816 switch (I->getOpcode()) {
817 case Instruction::And:
818 // If either the LHS or the RHS are Zero, the result is zero.
819 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
820 Mask &= ~KnownZero;
821 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
822 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
823 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
824
825 // Output known-1 bits are only known if set in both the LHS & RHS.
826 KnownOne &= KnownOne2;
827 // Output known-0 are known to be clear if zero in either the LHS | RHS.
828 KnownZero |= KnownZero2;
829 return;
830 case Instruction::Or:
831 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
832 Mask &= ~KnownOne;
833 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
834 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
835 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
836
837 // Output known-0 bits are only known if clear in both the LHS & RHS.
838 KnownZero &= KnownZero2;
839 // Output known-1 are known to be set if set in either the LHS | RHS.
840 KnownOne |= KnownOne2;
841 return;
842 case Instruction::Xor: {
843 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
844 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
845 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
846 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
847
848 // Output known-0 bits are known if clear or set in both the LHS & RHS.
849 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
850 // Output known-1 are known to be set if set in only one of the LHS, RHS.
851 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
852 KnownZero = KnownZeroOut;
853 return;
854 }
855 case Instruction::Select:
856 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
857 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
858 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
859 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
860
861 // Only known if known in both the LHS and RHS.
862 KnownOne &= KnownOne2;
863 KnownZero &= KnownZero2;
864 return;
Reid Spencer3da59db2006-11-27 01:05:10 +0000865 case Instruction::FPTrunc:
866 case Instruction::FPExt:
867 case Instruction::FPToUI:
868 case Instruction::FPToSI:
869 case Instruction::SIToFP:
870 case Instruction::PtrToInt:
871 case Instruction::UIToFP:
872 case Instruction::IntToPtr:
873 return; // Can't work with floating point or pointers
874 case Instruction::Trunc:
875 // All these have integer operands
876 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
877 return;
878 case Instruction::BitCast: {
Chris Lattner255d8912006-02-11 09:31:47 +0000879 const Type *SrcTy = I->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +0000880 if (SrcTy->isInteger()) {
Chris Lattner255d8912006-02-11 09:31:47 +0000881 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
Chris Lattner68d5ff22006-02-09 07:38:58 +0000882 return;
883 }
Reid Spencer3da59db2006-11-27 01:05:10 +0000884 break;
885 }
886 case Instruction::ZExt: {
887 // Compute the bits in the result that are not present in the input.
Reid Spencerc1030572007-01-19 21:13:56 +0000888 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
889 uint64_t NotIn = ~SrcTy->getBitMask();
890 uint64_t NewBits = cast<IntegerType>(I->getType())->getBitMask() & NotIn;
Chris Lattner60de63d2005-10-09 06:36:35 +0000891
Reid Spencerc1030572007-01-19 21:13:56 +0000892 Mask &= SrcTy->getBitMask();
Reid Spencer3da59db2006-11-27 01:05:10 +0000893 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
894 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
895 // The top bits are known to be zero.
896 KnownZero |= NewBits;
897 return;
898 }
899 case Instruction::SExt: {
900 // Compute the bits in the result that are not present in the input.
Reid Spencerc1030572007-01-19 21:13:56 +0000901 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
902 uint64_t NotIn = ~SrcTy->getBitMask();
903 uint64_t NewBits = cast<IntegerType>(I->getType())->getBitMask() & NotIn;
Reid Spencer3da59db2006-11-27 01:05:10 +0000904
Reid Spencerc1030572007-01-19 21:13:56 +0000905 Mask &= SrcTy->getBitMask();
Reid Spencer3da59db2006-11-27 01:05:10 +0000906 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
907 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner74c51a02006-02-07 08:05:22 +0000908
Reid Spencer3da59db2006-11-27 01:05:10 +0000909 // If the sign bit of the input is known set or clear, then we know the
910 // top bits of the result.
911 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
912 if (KnownZero & InSignBit) { // Input sign bit known zero
913 KnownZero |= NewBits;
914 KnownOne &= ~NewBits;
915 } else if (KnownOne & InSignBit) { // Input sign bit known set
916 KnownOne |= NewBits;
917 KnownZero &= ~NewBits;
918 } else { // Input sign bit unknown
919 KnownZero &= ~NewBits;
920 KnownOne &= ~NewBits;
Chris Lattner255d8912006-02-11 09:31:47 +0000921 }
922 return;
923 }
924 case Instruction::Shl:
925 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
Reid Spencerb83eb642006-10-20 07:07:24 +0000926 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
927 uint64_t ShiftAmt = SA->getZExtValue();
928 Mask >>= ShiftAmt;
Chris Lattner255d8912006-02-11 09:31:47 +0000929 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
930 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Reid Spencerb83eb642006-10-20 07:07:24 +0000931 KnownZero <<= ShiftAmt;
932 KnownOne <<= ShiftAmt;
933 KnownZero |= (1ULL << ShiftAmt)-1; // low bits known zero.
Chris Lattner255d8912006-02-11 09:31:47 +0000934 return;
935 }
936 break;
Reid Spencer3822ff52006-11-08 06:47:33 +0000937 case Instruction::LShr:
Chris Lattner255d8912006-02-11 09:31:47 +0000938 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
Reid Spencerb83eb642006-10-20 07:07:24 +0000939 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Chris Lattner255d8912006-02-11 09:31:47 +0000940 // Compute the new bits that are at the top now.
Reid Spencerb83eb642006-10-20 07:07:24 +0000941 uint64_t ShiftAmt = SA->getZExtValue();
942 uint64_t HighBits = (1ULL << ShiftAmt)-1;
943 HighBits <<= I->getType()->getPrimitiveSizeInBits()-ShiftAmt;
Chris Lattner255d8912006-02-11 09:31:47 +0000944
Reid Spencer3822ff52006-11-08 06:47:33 +0000945 // Unsigned shift right.
946 Mask <<= ShiftAmt;
947 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
948 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
949 KnownZero >>= ShiftAmt;
950 KnownOne >>= ShiftAmt;
951 KnownZero |= HighBits; // high bits known zero.
952 return;
953 }
954 break;
955 case Instruction::AShr:
956 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
957 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
958 // Compute the new bits that are at the top now.
959 uint64_t ShiftAmt = SA->getZExtValue();
960 uint64_t HighBits = (1ULL << ShiftAmt)-1;
961 HighBits <<= I->getType()->getPrimitiveSizeInBits()-ShiftAmt;
962
963 // Signed shift right.
964 Mask <<= ShiftAmt;
965 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
966 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
967 KnownZero >>= ShiftAmt;
968 KnownOne >>= ShiftAmt;
Chris Lattner255d8912006-02-11 09:31:47 +0000969
Reid Spencer3822ff52006-11-08 06:47:33 +0000970 // Handle the sign bits.
971 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
972 SignBit >>= ShiftAmt; // Adjust to where it is now in the mask.
Chris Lattner255d8912006-02-11 09:31:47 +0000973
Reid Spencer3822ff52006-11-08 06:47:33 +0000974 if (KnownZero & SignBit) { // New bits are known zero.
975 KnownZero |= HighBits;
976 } else if (KnownOne & SignBit) { // New bits are known one.
977 KnownOne |= HighBits;
Chris Lattner68d5ff22006-02-09 07:38:58 +0000978 }
979 return;
Chris Lattner60de63d2005-10-09 06:36:35 +0000980 }
Chris Lattner255d8912006-02-11 09:31:47 +0000981 break;
Chris Lattner5931c542005-09-24 23:43:33 +0000982 }
Chris Lattner74c51a02006-02-07 08:05:22 +0000983}
984
985/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
986/// this predicate to simplify operations downstream. Mask is known to be zero
987/// for bits that V cannot have.
988static bool MaskedValueIsZero(Value *V, uint64_t Mask, unsigned Depth = 0) {
Chris Lattner68d5ff22006-02-09 07:38:58 +0000989 uint64_t KnownZero, KnownOne;
990 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
991 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
992 return (KnownZero & Mask) == Mask;
Chris Lattner5931c542005-09-24 23:43:33 +0000993}
994
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +0000995#if 0
Reid Spencere7816b52007-03-08 01:52:58 +0000996/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
997/// this predicate to simplify operations downstream. Mask is known to be zero
998/// for bits that V cannot have.
999static bool MaskedValueIsZero(Value *V, const APInt& Mask, unsigned Depth = 0) {
Zhou Shengedd089c2007-03-12 16:54:56 +00001000 APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
Reid Spencere7816b52007-03-08 01:52:58 +00001001 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
1002 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1003 return (KnownZero & Mask) == Mask;
1004}
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00001005#endif
Reid Spencere7816b52007-03-08 01:52:58 +00001006
Chris Lattner255d8912006-02-11 09:31:47 +00001007/// ShrinkDemandedConstant - Check to see if the specified operand of the
1008/// specified instruction is a constant integer. If so, check to see if there
1009/// are any bits set in the constant that are not demanded. If so, shrink the
1010/// constant and return true.
1011static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
1012 uint64_t Demanded) {
1013 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
1014 if (!OpC) return false;
1015
1016 // If there are no bits set that aren't demanded, nothing to do.
1017 if ((~Demanded & OpC->getZExtValue()) == 0)
1018 return false;
1019
1020 // This is producing any bits that are not needed, shrink the RHS.
1021 uint64_t Val = Demanded & OpC->getZExtValue();
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001022 I->setOperand(OpNo, ConstantInt::get(OpC->getType(), Val));
Chris Lattner255d8912006-02-11 09:31:47 +00001023 return true;
1024}
1025
Reid Spencer6b79e2d2007-03-12 17:15:10 +00001026/// ShrinkDemandedConstant - Check to see if the specified operand of the
1027/// specified instruction is a constant integer. If so, check to see if there
1028/// are any bits set in the constant that are not demanded. If so, shrink the
1029/// constant and return true.
1030static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
1031 APInt Demanded) {
1032 assert(I && "No instruction?");
1033 assert(OpNo < I->getNumOperands() && "Operand index too large");
1034
1035 // If the operand is not a constant integer, nothing to do.
1036 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
1037 if (!OpC) return false;
1038
1039 // If there are no bits set that aren't demanded, nothing to do.
1040 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
1041 if ((~Demanded & OpC->getValue()) == 0)
1042 return false;
1043
1044 // This instruction is producing bits that are not demanded. Shrink the RHS.
1045 Demanded &= OpC->getValue();
1046 I->setOperand(OpNo, ConstantInt::get(Demanded));
1047 return true;
1048}
1049
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00001050// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
1051// set of known zero and one bits, compute the maximum and minimum values that
1052// could have the specified known zero and known one bits, returning them in
1053// min/max.
1054static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
1055 uint64_t KnownZero,
1056 uint64_t KnownOne,
1057 int64_t &Min, int64_t &Max) {
Reid Spencerc1030572007-01-19 21:13:56 +00001058 uint64_t TypeBits = cast<IntegerType>(Ty)->getBitMask();
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00001059 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
1060
1061 uint64_t SignBit = 1ULL << (Ty->getPrimitiveSizeInBits()-1);
1062
1063 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
1064 // bit if it is unknown.
1065 Min = KnownOne;
1066 Max = KnownOne|UnknownBits;
1067
1068 if (SignBit & UnknownBits) { // Sign bit is unknown
1069 Min |= SignBit;
1070 Max &= ~SignBit;
1071 }
1072
1073 // Sign extend the min/max values.
1074 int ShAmt = 64-Ty->getPrimitiveSizeInBits();
1075 Min = (Min << ShAmt) >> ShAmt;
1076 Max = (Max << ShAmt) >> ShAmt;
1077}
1078
1079// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
1080// a set of known zero and one bits, compute the maximum and minimum values that
1081// could have the specified known zero and known one bits, returning them in
1082// min/max.
1083static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
1084 uint64_t KnownZero,
1085 uint64_t KnownOne,
1086 uint64_t &Min,
1087 uint64_t &Max) {
Reid Spencerc1030572007-01-19 21:13:56 +00001088 uint64_t TypeBits = cast<IntegerType>(Ty)->getBitMask();
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00001089 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
1090
1091 // The minimum value is when the unknown bits are all zeros.
1092 Min = KnownOne;
1093 // The maximum value is when the unknown bits are all ones.
1094 Max = KnownOne|UnknownBits;
1095}
Chris Lattner255d8912006-02-11 09:31:47 +00001096
1097
1098/// SimplifyDemandedBits - Look at V. At this point, we know that only the
1099/// DemandedMask bits of the result of V are ever used downstream. If we can
1100/// use this information to simplify V, do so and return true. Otherwise,
1101/// analyze the expression and return a mask of KnownOne and KnownZero bits for
1102/// the expression (used to simplify the caller). The KnownZero/One bits may
1103/// only be accurate for those bits in the DemandedMask.
1104bool InstCombiner::SimplifyDemandedBits(Value *V, uint64_t DemandedMask,
1105 uint64_t &KnownZero, uint64_t &KnownOne,
Chris Lattner6dce1a72006-02-07 06:56:34 +00001106 unsigned Depth) {
Chris Lattnerd5fa2142007-03-04 23:16:36 +00001107 const IntegerType *VTy = cast<IntegerType>(V->getType());
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001108 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
Chris Lattner255d8912006-02-11 09:31:47 +00001109 // We know all of the bits for a constant!
1110 KnownOne = CI->getZExtValue() & DemandedMask;
1111 KnownZero = ~KnownOne & DemandedMask;
1112 return false;
1113 }
1114
1115 KnownZero = KnownOne = 0;
Chris Lattner6dce1a72006-02-07 06:56:34 +00001116 if (!V->hasOneUse()) { // Other users may use these bits.
Chris Lattner255d8912006-02-11 09:31:47 +00001117 if (Depth != 0) { // Not at the root.
1118 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
1119 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
Chris Lattner6dce1a72006-02-07 06:56:34 +00001120 return false;
Chris Lattner255d8912006-02-11 09:31:47 +00001121 }
Chris Lattner6dce1a72006-02-07 06:56:34 +00001122 // If this is the root being simplified, allow it to have multiple uses,
Chris Lattner255d8912006-02-11 09:31:47 +00001123 // just set the DemandedMask to all bits.
Chris Lattnerd5fa2142007-03-04 23:16:36 +00001124 DemandedMask = VTy->getBitMask();
Chris Lattner255d8912006-02-11 09:31:47 +00001125 } else if (DemandedMask == 0) { // Not demanding any bits from V.
Chris Lattnerd5fa2142007-03-04 23:16:36 +00001126 if (V != UndefValue::get(VTy))
1127 return UpdateValueUsesWith(V, UndefValue::get(VTy));
Chris Lattner74c51a02006-02-07 08:05:22 +00001128 return false;
Chris Lattner6dce1a72006-02-07 06:56:34 +00001129 } else if (Depth == 6) { // Limit search depth.
1130 return false;
1131 }
1132
1133 Instruction *I = dyn_cast<Instruction>(V);
1134 if (!I) return false; // Only analyze instructions.
1135
Chris Lattnerd5fa2142007-03-04 23:16:36 +00001136 DemandedMask &= VTy->getBitMask();
Chris Lattnere3158302006-05-04 17:33:35 +00001137
Reid Spencer3da59db2006-11-27 01:05:10 +00001138 uint64_t KnownZero2 = 0, KnownOne2 = 0;
Chris Lattner6dce1a72006-02-07 06:56:34 +00001139 switch (I->getOpcode()) {
1140 default: break;
1141 case Instruction::And:
Chris Lattner255d8912006-02-11 09:31:47 +00001142 // If either the LHS or the RHS are Zero, the result is zero.
1143 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1144 KnownZero, KnownOne, Depth+1))
1145 return true;
1146 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1147
1148 // If something is known zero on the RHS, the bits aren't demanded on the
1149 // LHS.
1150 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownZero,
1151 KnownZero2, KnownOne2, Depth+1))
1152 return true;
1153 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1154
Reid Spencer3da59db2006-11-27 01:05:10 +00001155 // If all of the demanded bits are known 1 on one side, return the other.
Chris Lattner255d8912006-02-11 09:31:47 +00001156 // These bits cannot contribute to the result of the 'and'.
1157 if ((DemandedMask & ~KnownZero2 & KnownOne) == (DemandedMask & ~KnownZero2))
1158 return UpdateValueUsesWith(I, I->getOperand(0));
1159 if ((DemandedMask & ~KnownZero & KnownOne2) == (DemandedMask & ~KnownZero))
1160 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattnerf8c36f52006-02-12 08:02:11 +00001161
1162 // If all of the demanded bits in the inputs are known zeros, return zero.
1163 if ((DemandedMask & (KnownZero|KnownZero2)) == DemandedMask)
Chris Lattnerd5fa2142007-03-04 23:16:36 +00001164 return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
Chris Lattnerf8c36f52006-02-12 08:02:11 +00001165
Chris Lattner255d8912006-02-11 09:31:47 +00001166 // If the RHS is a constant, see if we can simplify it.
Chris Lattnerf8c36f52006-02-12 08:02:11 +00001167 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~KnownZero2))
Chris Lattner255d8912006-02-11 09:31:47 +00001168 return UpdateValueUsesWith(I, I);
1169
1170 // Output known-1 bits are only known if set in both the LHS & RHS.
1171 KnownOne &= KnownOne2;
1172 // Output known-0 are known to be clear if zero in either the LHS | RHS.
1173 KnownZero |= KnownZero2;
1174 break;
1175 case Instruction::Or:
1176 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1177 KnownZero, KnownOne, Depth+1))
1178 return true;
1179 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1180 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownOne,
1181 KnownZero2, KnownOne2, Depth+1))
1182 return true;
1183 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1184
1185 // If all of the demanded bits are known zero on one side, return the other.
1186 // These bits cannot contribute to the result of the 'or'.
Jeff Cohenbce48052006-02-18 03:20:33 +00001187 if ((DemandedMask & ~KnownOne2 & KnownZero) == (DemandedMask & ~KnownOne2))
Chris Lattner255d8912006-02-11 09:31:47 +00001188 return UpdateValueUsesWith(I, I->getOperand(0));
Jeff Cohenbce48052006-02-18 03:20:33 +00001189 if ((DemandedMask & ~KnownOne & KnownZero2) == (DemandedMask & ~KnownOne))
Chris Lattner255d8912006-02-11 09:31:47 +00001190 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattnerf8c36f52006-02-12 08:02:11 +00001191
1192 // If all of the potentially set bits on one side are known to be set on
1193 // the other side, just use the 'other' side.
1194 if ((DemandedMask & (~KnownZero) & KnownOne2) ==
1195 (DemandedMask & (~KnownZero)))
1196 return UpdateValueUsesWith(I, I->getOperand(0));
Nate Begeman368e18d2006-02-16 21:11:51 +00001197 if ((DemandedMask & (~KnownZero2) & KnownOne) ==
1198 (DemandedMask & (~KnownZero2)))
1199 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner255d8912006-02-11 09:31:47 +00001200
1201 // If the RHS is a constant, see if we can simplify it.
1202 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1203 return UpdateValueUsesWith(I, I);
1204
1205 // Output known-0 bits are only known if clear in both the LHS & RHS.
1206 KnownZero &= KnownZero2;
1207 // Output known-1 are known to be set if set in either the LHS | RHS.
1208 KnownOne |= KnownOne2;
1209 break;
1210 case Instruction::Xor: {
1211 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1212 KnownZero, KnownOne, Depth+1))
1213 return true;
1214 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1215 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1216 KnownZero2, KnownOne2, Depth+1))
1217 return true;
1218 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1219
1220 // If all of the demanded bits are known zero on one side, return the other.
1221 // These bits cannot contribute to the result of the 'xor'.
1222 if ((DemandedMask & KnownZero) == DemandedMask)
1223 return UpdateValueUsesWith(I, I->getOperand(0));
1224 if ((DemandedMask & KnownZero2) == DemandedMask)
1225 return UpdateValueUsesWith(I, I->getOperand(1));
1226
1227 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1228 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
1229 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1230 uint64_t KnownOneOut = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
1231
Chris Lattnerf2f16432006-11-27 19:55:07 +00001232 // If all of the demanded bits are known to be zero on one side or the
1233 // other, turn this into an *inclusive* or.
Chris Lattnerf8c36f52006-02-12 08:02:11 +00001234 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerf2f16432006-11-27 19:55:07 +00001235 if ((DemandedMask & ~KnownZero & ~KnownZero2) == 0) {
1236 Instruction *Or =
1237 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1238 I->getName());
1239 InsertNewInstBefore(Or, *I);
1240 return UpdateValueUsesWith(I, Or);
Chris Lattner6dce1a72006-02-07 06:56:34 +00001241 }
Chris Lattner255d8912006-02-11 09:31:47 +00001242
Chris Lattnerf8c36f52006-02-12 08:02:11 +00001243 // If all of the demanded bits on one side are known, and all of the set
1244 // bits on that side are also known to be set on the other side, turn this
1245 // into an AND, as we know the bits will be cleared.
1246 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1247 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask) { // all known
1248 if ((KnownOne & KnownOne2) == KnownOne) {
Chris Lattnerd5fa2142007-03-04 23:16:36 +00001249 Constant *AndC = ConstantInt::get(VTy, ~KnownOne & DemandedMask);
Chris Lattnerf8c36f52006-02-12 08:02:11 +00001250 Instruction *And =
1251 BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
1252 InsertNewInstBefore(And, *I);
1253 return UpdateValueUsesWith(I, And);
1254 }
1255 }
1256
Chris Lattner255d8912006-02-11 09:31:47 +00001257 // If the RHS is a constant, see if we can simplify it.
1258 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1259 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1260 return UpdateValueUsesWith(I, I);
1261
1262 KnownZero = KnownZeroOut;
1263 KnownOne = KnownOneOut;
1264 break;
1265 }
1266 case Instruction::Select:
1267 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
1268 KnownZero, KnownOne, Depth+1))
1269 return true;
1270 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1271 KnownZero2, KnownOne2, Depth+1))
1272 return true;
1273 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1274 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1275
1276 // If the operands are constants, see if we can simplify them.
1277 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1278 return UpdateValueUsesWith(I, I);
1279 if (ShrinkDemandedConstant(I, 2, DemandedMask))
1280 return UpdateValueUsesWith(I, I);
1281
1282 // Only known if known in both the LHS and RHS.
1283 KnownOne &= KnownOne2;
1284 KnownZero &= KnownZero2;
1285 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00001286 case Instruction::Trunc:
1287 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1288 KnownZero, KnownOne, Depth+1))
1289 return true;
1290 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1291 break;
1292 case Instruction::BitCast:
Chris Lattner42a75512007-01-15 02:27:26 +00001293 if (!I->getOperand(0)->getType()->isInteger())
Reid Spencer3da59db2006-11-27 01:05:10 +00001294 return false;
Chris Lattnerf6bd07c2006-09-16 03:14:10 +00001295
Reid Spencer3da59db2006-11-27 01:05:10 +00001296 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1297 KnownZero, KnownOne, Depth+1))
1298 return true;
1299 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1300 break;
1301 case Instruction::ZExt: {
1302 // Compute the bits in the result that are not present in the input.
Reid Spencerc1030572007-01-19 21:13:56 +00001303 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1304 uint64_t NotIn = ~SrcTy->getBitMask();
Chris Lattnerd5fa2142007-03-04 23:16:36 +00001305 uint64_t NewBits = VTy->getBitMask() & NotIn;
Chris Lattner255d8912006-02-11 09:31:47 +00001306
Reid Spencerc1030572007-01-19 21:13:56 +00001307 DemandedMask &= SrcTy->getBitMask();
Reid Spencer3da59db2006-11-27 01:05:10 +00001308 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1309 KnownZero, KnownOne, Depth+1))
1310 return true;
1311 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1312 // The top bits are known to be zero.
1313 KnownZero |= NewBits;
1314 break;
1315 }
1316 case Instruction::SExt: {
1317 // Compute the bits in the result that are not present in the input.
Reid Spencerc1030572007-01-19 21:13:56 +00001318 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1319 uint64_t NotIn = ~SrcTy->getBitMask();
Chris Lattnerd5fa2142007-03-04 23:16:36 +00001320 uint64_t NewBits = VTy->getBitMask() & NotIn;
Reid Spencer3da59db2006-11-27 01:05:10 +00001321
1322 // Get the sign bit for the source type
1323 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
Reid Spencerc1030572007-01-19 21:13:56 +00001324 int64_t InputDemandedBits = DemandedMask & SrcTy->getBitMask();
Chris Lattnerf345fe42006-02-13 22:41:07 +00001325
Reid Spencer3da59db2006-11-27 01:05:10 +00001326 // If any of the sign extended bits are demanded, we know that the sign
1327 // bit is demanded.
1328 if (NewBits & DemandedMask)
1329 InputDemandedBits |= InSignBit;
Chris Lattnerf345fe42006-02-13 22:41:07 +00001330
Reid Spencer3da59db2006-11-27 01:05:10 +00001331 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1332 KnownZero, KnownOne, Depth+1))
1333 return true;
1334 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner255d8912006-02-11 09:31:47 +00001335
Reid Spencer3da59db2006-11-27 01:05:10 +00001336 // If the sign bit of the input is known set or clear, then we know the
1337 // top bits of the result.
Chris Lattner6dce1a72006-02-07 06:56:34 +00001338
Reid Spencer3da59db2006-11-27 01:05:10 +00001339 // If the input sign bit is known zero, or if the NewBits are not demanded
1340 // convert this into a zero extension.
1341 if ((KnownZero & InSignBit) || (NewBits & ~DemandedMask) == NewBits) {
1342 // Convert to ZExt cast
Chris Lattnerd5fa2142007-03-04 23:16:36 +00001343 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
Reid Spencer3da59db2006-11-27 01:05:10 +00001344 return UpdateValueUsesWith(I, NewCast);
1345 } else if (KnownOne & InSignBit) { // Input sign bit known set
1346 KnownOne |= NewBits;
1347 KnownZero &= ~NewBits;
1348 } else { // Input sign bit unknown
1349 KnownZero &= ~NewBits;
1350 KnownOne &= ~NewBits;
Chris Lattner6dce1a72006-02-07 06:56:34 +00001351 }
Chris Lattner255d8912006-02-11 09:31:47 +00001352 break;
Chris Lattner6dce1a72006-02-07 06:56:34 +00001353 }
Chris Lattnerb4a2f052006-11-09 05:12:27 +00001354 case Instruction::Add:
1355 // If there is a constant on the RHS, there are a variety of xformations
1356 // we can do.
1357 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1358 // If null, this should be simplified elsewhere. Some of the xforms here
1359 // won't work if the RHS is zero.
1360 if (RHS->isNullValue())
1361 break;
1362
1363 // Figure out what the input bits are. If the top bits of the and result
1364 // are not demanded, then the add doesn't demand them from its input
1365 // either.
1366
1367 // Shift the demanded mask up so that it's at the top of the uint64_t.
Chris Lattnerd5fa2142007-03-04 23:16:36 +00001368 unsigned BitWidth = VTy->getPrimitiveSizeInBits();
Chris Lattnerb4a2f052006-11-09 05:12:27 +00001369 unsigned NLZ = CountLeadingZeros_64(DemandedMask << (64-BitWidth));
1370
1371 // If the top bit of the output is demanded, demand everything from the
1372 // input. Otherwise, we demand all the input bits except NLZ top bits.
Jeff Cohendfc12992007-01-08 20:17:17 +00001373 uint64_t InDemandedBits = ~0ULL >> (64-BitWidth+NLZ);
Chris Lattnerb4a2f052006-11-09 05:12:27 +00001374
1375 // Find information about known zero/one bits in the input.
1376 if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits,
1377 KnownZero2, KnownOne2, Depth+1))
1378 return true;
1379
1380 // If the RHS of the add has bits set that can't affect the input, reduce
1381 // the constant.
1382 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1383 return UpdateValueUsesWith(I, I);
1384
1385 // Avoid excess work.
1386 if (KnownZero2 == 0 && KnownOne2 == 0)
1387 break;
1388
1389 // Turn it into OR if input bits are zero.
1390 if ((KnownZero2 & RHS->getZExtValue()) == RHS->getZExtValue()) {
1391 Instruction *Or =
1392 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1393 I->getName());
1394 InsertNewInstBefore(Or, *I);
1395 return UpdateValueUsesWith(I, Or);
1396 }
1397
1398 // We can say something about the output known-zero and known-one bits,
1399 // depending on potential carries from the input constant and the
1400 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1401 // bits set and the RHS constant is 0x01001, then we know we have a known
1402 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1403
1404 // To compute this, we first compute the potential carry bits. These are
1405 // the bits which may be modified. I'm not aware of a better way to do
1406 // this scan.
1407 uint64_t RHSVal = RHS->getZExtValue();
1408
1409 bool CarryIn = false;
1410 uint64_t CarryBits = 0;
1411 uint64_t CurBit = 1;
1412 for (unsigned i = 0; i != BitWidth; ++i, CurBit <<= 1) {
1413 // Record the current carry in.
1414 if (CarryIn) CarryBits |= CurBit;
1415
1416 bool CarryOut;
1417
1418 // This bit has a carry out unless it is "zero + zero" or
1419 // "zero + anything" with no carry in.
1420 if ((KnownZero2 & CurBit) && ((RHSVal & CurBit) == 0)) {
1421 CarryOut = false; // 0 + 0 has no carry out, even with carry in.
1422 } else if (!CarryIn &&
1423 ((KnownZero2 & CurBit) || ((RHSVal & CurBit) == 0))) {
1424 CarryOut = false; // 0 + anything has no carry out if no carry in.
1425 } else {
1426 // Otherwise, we have to assume we have a carry out.
1427 CarryOut = true;
1428 }
1429
1430 // This stage's carry out becomes the next stage's carry-in.
1431 CarryIn = CarryOut;
1432 }
1433
1434 // Now that we know which bits have carries, compute the known-1/0 sets.
1435
1436 // Bits are known one if they are known zero in one operand and one in the
1437 // other, and there is no input carry.
1438 KnownOne = ((KnownZero2 & RHSVal) | (KnownOne2 & ~RHSVal)) & ~CarryBits;
1439
1440 // Bits are known zero if they are known zero in both operands and there
1441 // is no input carry.
1442 KnownZero = KnownZero2 & ~RHSVal & ~CarryBits;
Chris Lattner783ccdb2007-03-05 00:02:29 +00001443 } else {
1444 // If the high-bits of this ADD are not demanded, then it does not demand
1445 // the high bits of its LHS or RHS.
1446 if ((DemandedMask & VTy->getSignBit()) == 0) {
1447 // Right fill the mask of bits for this ADD to demand the most
1448 // significant bit and all those below it.
1449 unsigned NLZ = CountLeadingZeros_64(DemandedMask);
1450 uint64_t DemandedFromOps = ~0ULL >> NLZ;
1451 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1452 KnownZero2, KnownOne2, Depth+1))
1453 return true;
1454 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1455 KnownZero2, KnownOne2, Depth+1))
1456 return true;
1457 }
1458 }
1459 break;
1460 case Instruction::Sub:
1461 // If the high-bits of this SUB are not demanded, then it does not demand
1462 // the high bits of its LHS or RHS.
1463 if ((DemandedMask & VTy->getSignBit()) == 0) {
1464 // Right fill the mask of bits for this SUB to demand the most
1465 // significant bit and all those below it.
1466 unsigned NLZ = CountLeadingZeros_64(DemandedMask);
1467 uint64_t DemandedFromOps = ~0ULL >> NLZ;
1468 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1469 KnownZero2, KnownOne2, Depth+1))
1470 return true;
1471 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1472 KnownZero2, KnownOne2, Depth+1))
1473 return true;
Chris Lattnerb4a2f052006-11-09 05:12:27 +00001474 }
1475 break;
Chris Lattner6dce1a72006-02-07 06:56:34 +00001476 case Instruction::Shl:
Reid Spencerb83eb642006-10-20 07:07:24 +00001477 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1478 uint64_t ShiftAmt = SA->getZExtValue();
1479 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask >> ShiftAmt,
Chris Lattner255d8912006-02-11 09:31:47 +00001480 KnownZero, KnownOne, Depth+1))
1481 return true;
1482 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Reid Spencerb83eb642006-10-20 07:07:24 +00001483 KnownZero <<= ShiftAmt;
1484 KnownOne <<= ShiftAmt;
1485 KnownZero |= (1ULL << ShiftAmt) - 1; // low bits known zero.
Chris Lattner255d8912006-02-11 09:31:47 +00001486 }
Chris Lattner6dce1a72006-02-07 06:56:34 +00001487 break;
Reid Spencer3822ff52006-11-08 06:47:33 +00001488 case Instruction::LShr:
1489 // For a logical shift right
1490 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1491 unsigned ShiftAmt = SA->getZExtValue();
1492
1493 // Compute the new bits that are at the top now.
1494 uint64_t HighBits = (1ULL << ShiftAmt)-1;
Chris Lattnerd5fa2142007-03-04 23:16:36 +00001495 HighBits <<= VTy->getBitWidth() - ShiftAmt;
1496 uint64_t TypeMask = VTy->getBitMask();
Reid Spencer3822ff52006-11-08 06:47:33 +00001497 // Unsigned shift right.
1498 if (SimplifyDemandedBits(I->getOperand(0),
1499 (DemandedMask << ShiftAmt) & TypeMask,
1500 KnownZero, KnownOne, Depth+1))
1501 return true;
1502 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1503 KnownZero &= TypeMask;
1504 KnownOne &= TypeMask;
1505 KnownZero >>= ShiftAmt;
1506 KnownOne >>= ShiftAmt;
1507 KnownZero |= HighBits; // high bits known zero.
1508 }
1509 break;
1510 case Instruction::AShr:
Chris Lattnerb7363792006-09-18 04:31:40 +00001511 // If this is an arithmetic shift right and only the low-bit is set, we can
1512 // always convert this into a logical shr, even if the shift amount is
1513 // variable. The low bit of the shift cannot be an input sign bit unless
1514 // the shift amount is >= the size of the datatype, which is undefined.
Reid Spencer3822ff52006-11-08 06:47:33 +00001515 if (DemandedMask == 1) {
1516 // Perform the logical shift right.
Reid Spencercc46cdb2007-02-02 14:08:20 +00001517 Value *NewVal = BinaryOperator::createLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00001518 I->getOperand(0), I->getOperand(1), I->getName());
Reid Spencer811b0cb2006-10-26 19:19:06 +00001519 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
Chris Lattnerb7363792006-09-18 04:31:40 +00001520 return UpdateValueUsesWith(I, NewVal);
1521 }
1522
Reid Spencerb83eb642006-10-20 07:07:24 +00001523 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1524 unsigned ShiftAmt = SA->getZExtValue();
Chris Lattner255d8912006-02-11 09:31:47 +00001525
1526 // Compute the new bits that are at the top now.
Reid Spencerb83eb642006-10-20 07:07:24 +00001527 uint64_t HighBits = (1ULL << ShiftAmt)-1;
Chris Lattnerd5fa2142007-03-04 23:16:36 +00001528 HighBits <<= VTy->getBitWidth() - ShiftAmt;
1529 uint64_t TypeMask = VTy->getBitMask();
Reid Spencer3822ff52006-11-08 06:47:33 +00001530 // Signed shift right.
1531 if (SimplifyDemandedBits(I->getOperand(0),
1532 (DemandedMask << ShiftAmt) & TypeMask,
1533 KnownZero, KnownOne, Depth+1))
1534 return true;
1535 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1536 KnownZero &= TypeMask;
1537 KnownOne &= TypeMask;
1538 KnownZero >>= ShiftAmt;
1539 KnownOne >>= ShiftAmt;
Chris Lattner255d8912006-02-11 09:31:47 +00001540
Reid Spencer3822ff52006-11-08 06:47:33 +00001541 // Handle the sign bits.
Chris Lattnerd5fa2142007-03-04 23:16:36 +00001542 uint64_t SignBit = 1ULL << (VTy->getBitWidth()-1);
Reid Spencer3822ff52006-11-08 06:47:33 +00001543 SignBit >>= ShiftAmt; // Adjust to where it is now in the mask.
Chris Lattner255d8912006-02-11 09:31:47 +00001544
Reid Spencer3822ff52006-11-08 06:47:33 +00001545 // If the input sign bit is known to be zero, or if none of the top bits
1546 // are demanded, turn this into an unsigned shift right.
1547 if ((KnownZero & SignBit) || (HighBits & ~DemandedMask) == HighBits) {
1548 // Perform the logical shift right.
Reid Spencercc46cdb2007-02-02 14:08:20 +00001549 Value *NewVal = BinaryOperator::createLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00001550 I->getOperand(0), SA, I->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00001551 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1552 return UpdateValueUsesWith(I, NewVal);
1553 } else if (KnownOne & SignBit) { // New bits are known one.
1554 KnownOne |= HighBits;
Chris Lattner6dce1a72006-02-07 06:56:34 +00001555 }
Chris Lattner255d8912006-02-11 09:31:47 +00001556 }
Chris Lattner6dce1a72006-02-07 06:56:34 +00001557 break;
1558 }
Chris Lattner255d8912006-02-11 09:31:47 +00001559
1560 // If the client is only demanding bits that we know, return the known
1561 // constant.
1562 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask)
Chris Lattnerd5fa2142007-03-04 23:16:36 +00001563 return UpdateValueUsesWith(I, ConstantInt::get(VTy, KnownOne));
Chris Lattner6dce1a72006-02-07 06:56:34 +00001564 return false;
1565}
1566
Reid Spencer8cb68342007-03-12 17:25:59 +00001567/// SimplifyDemandedBits - This function attempts to replace V with a simpler
1568/// value based on the demanded bits. When this function is called, it is known
1569/// that only the bits set in DemandedMask of the result of V are ever used
1570/// downstream. Consequently, depending on the mask and V, it may be possible
1571/// to replace V with a constant or one of its operands. In such cases, this
1572/// function does the replacement and returns true. In all other cases, it
1573/// returns false after analyzing the expression and setting KnownOne and known
1574/// to be one in the expression. KnownZero contains all the bits that are known
1575/// to be zero in the expression. These are provided to potentially allow the
1576/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
1577/// the expression. KnownOne and KnownZero always follow the invariant that
1578/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
1579/// the bits in KnownOne and KnownZero may only be accurate for those bits set
1580/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
1581/// and KnownOne must all be the same.
1582bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
1583 APInt& KnownZero, APInt& KnownOne,
1584 unsigned Depth) {
1585 assert(V != 0 && "Null pointer of Value???");
1586 assert(Depth <= 6 && "Limit Search Depth");
1587 uint32_t BitWidth = DemandedMask.getBitWidth();
1588 const IntegerType *VTy = cast<IntegerType>(V->getType());
1589 assert(VTy->getBitWidth() == BitWidth &&
1590 KnownZero.getBitWidth() == BitWidth &&
1591 KnownOne.getBitWidth() == BitWidth &&
1592 "Value *V, DemandedMask, KnownZero and KnownOne \
1593 must have same BitWidth");
1594 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
1595 // We know all of the bits for a constant!
1596 KnownOne = CI->getValue() & DemandedMask;
1597 KnownZero = ~KnownOne & DemandedMask;
1598 return false;
1599 }
1600
Zhou Sheng96704452007-03-14 03:21:24 +00001601 KnownZero.clear();
1602 KnownOne.clear();
Reid Spencer8cb68342007-03-12 17:25:59 +00001603 if (!V->hasOneUse()) { // Other users may use these bits.
1604 if (Depth != 0) { // Not at the root.
1605 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
1606 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
1607 return false;
1608 }
1609 // If this is the root being simplified, allow it to have multiple uses,
1610 // just set the DemandedMask to all bits.
1611 DemandedMask = APInt::getAllOnesValue(BitWidth);
1612 } else if (DemandedMask == 0) { // Not demanding any bits from V.
1613 if (V != UndefValue::get(VTy))
1614 return UpdateValueUsesWith(V, UndefValue::get(VTy));
1615 return false;
1616 } else if (Depth == 6) { // Limit search depth.
1617 return false;
1618 }
1619
1620 Instruction *I = dyn_cast<Instruction>(V);
1621 if (!I) return false; // Only analyze instructions.
1622
1623 DemandedMask &= APInt::getAllOnesValue(BitWidth);
1624
1625 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
1626 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
1627 switch (I->getOpcode()) {
1628 default: break;
1629 case Instruction::And:
1630 // If either the LHS or the RHS are Zero, the result is zero.
1631 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1632 RHSKnownZero, RHSKnownOne, Depth+1))
1633 return true;
1634 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1635 "Bits known to be one AND zero?");
1636
1637 // If something is known zero on the RHS, the bits aren't demanded on the
1638 // LHS.
1639 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
1640 LHSKnownZero, LHSKnownOne, Depth+1))
1641 return true;
1642 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1643 "Bits known to be one AND zero?");
1644
1645 // If all of the demanded bits are known 1 on one side, return the other.
1646 // These bits cannot contribute to the result of the 'and'.
1647 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
1648 (DemandedMask & ~LHSKnownZero))
1649 return UpdateValueUsesWith(I, I->getOperand(0));
1650 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
1651 (DemandedMask & ~RHSKnownZero))
1652 return UpdateValueUsesWith(I, I->getOperand(1));
1653
1654 // If all of the demanded bits in the inputs are known zeros, return zero.
1655 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
1656 return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
1657
1658 // If the RHS is a constant, see if we can simplify it.
1659 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
1660 return UpdateValueUsesWith(I, I);
1661
1662 // Output known-1 bits are only known if set in both the LHS & RHS.
1663 RHSKnownOne &= LHSKnownOne;
1664 // Output known-0 are known to be clear if zero in either the LHS | RHS.
1665 RHSKnownZero |= LHSKnownZero;
1666 break;
1667 case Instruction::Or:
1668 // If either the LHS or the RHS are One, the result is One.
1669 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1670 RHSKnownZero, RHSKnownOne, Depth+1))
1671 return true;
1672 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1673 "Bits known to be one AND zero?");
1674 // If something is known one on the RHS, the bits aren't demanded on the
1675 // LHS.
1676 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
1677 LHSKnownZero, LHSKnownOne, Depth+1))
1678 return true;
1679 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1680 "Bits known to be one AND zero?");
1681
1682 // If all of the demanded bits are known zero on one side, return the other.
1683 // These bits cannot contribute to the result of the 'or'.
1684 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
1685 (DemandedMask & ~LHSKnownOne))
1686 return UpdateValueUsesWith(I, I->getOperand(0));
1687 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
1688 (DemandedMask & ~RHSKnownOne))
1689 return UpdateValueUsesWith(I, I->getOperand(1));
1690
1691 // If all of the potentially set bits on one side are known to be set on
1692 // the other side, just use the 'other' side.
1693 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
1694 (DemandedMask & (~RHSKnownZero)))
1695 return UpdateValueUsesWith(I, I->getOperand(0));
1696 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
1697 (DemandedMask & (~LHSKnownZero)))
1698 return UpdateValueUsesWith(I, I->getOperand(1));
1699
1700 // If the RHS is a constant, see if we can simplify it.
1701 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1702 return UpdateValueUsesWith(I, I);
1703
1704 // Output known-0 bits are only known if clear in both the LHS & RHS.
1705 RHSKnownZero &= LHSKnownZero;
1706 // Output known-1 are known to be set if set in either the LHS | RHS.
1707 RHSKnownOne |= LHSKnownOne;
1708 break;
1709 case Instruction::Xor: {
1710 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1711 RHSKnownZero, RHSKnownOne, Depth+1))
1712 return true;
1713 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1714 "Bits known to be one AND zero?");
1715 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1716 LHSKnownZero, LHSKnownOne, Depth+1))
1717 return true;
1718 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1719 "Bits known to be one AND zero?");
1720
1721 // If all of the demanded bits are known zero on one side, return the other.
1722 // These bits cannot contribute to the result of the 'xor'.
1723 if ((DemandedMask & RHSKnownZero) == DemandedMask)
1724 return UpdateValueUsesWith(I, I->getOperand(0));
1725 if ((DemandedMask & LHSKnownZero) == DemandedMask)
1726 return UpdateValueUsesWith(I, I->getOperand(1));
1727
1728 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1729 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1730 (RHSKnownOne & LHSKnownOne);
1731 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1732 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1733 (RHSKnownOne & LHSKnownZero);
1734
1735 // If all of the demanded bits are known to be zero on one side or the
1736 // other, turn this into an *inclusive* or.
1737 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1738 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1739 Instruction *Or =
1740 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1741 I->getName());
1742 InsertNewInstBefore(Or, *I);
1743 return UpdateValueUsesWith(I, Or);
1744 }
1745
1746 // If all of the demanded bits on one side are known, and all of the set
1747 // bits on that side are also known to be set on the other side, turn this
1748 // into an AND, as we know the bits will be cleared.
1749 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1750 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1751 // all known
1752 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1753 Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
1754 Instruction *And =
1755 BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
1756 InsertNewInstBefore(And, *I);
1757 return UpdateValueUsesWith(I, And);
1758 }
1759 }
1760
1761 // If the RHS is a constant, see if we can simplify it.
1762 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1763 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1764 return UpdateValueUsesWith(I, I);
1765
1766 RHSKnownZero = KnownZeroOut;
1767 RHSKnownOne = KnownOneOut;
1768 break;
1769 }
1770 case Instruction::Select:
1771 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
1772 RHSKnownZero, RHSKnownOne, Depth+1))
1773 return true;
1774 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1775 LHSKnownZero, LHSKnownOne, Depth+1))
1776 return true;
1777 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1778 "Bits known to be one AND zero?");
1779 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1780 "Bits known to be one AND zero?");
1781
1782 // If the operands are constants, see if we can simplify them.
1783 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1784 return UpdateValueUsesWith(I, I);
1785 if (ShrinkDemandedConstant(I, 2, DemandedMask))
1786 return UpdateValueUsesWith(I, I);
1787
1788 // Only known if known in both the LHS and RHS.
1789 RHSKnownOne &= LHSKnownOne;
1790 RHSKnownZero &= LHSKnownZero;
1791 break;
1792 case Instruction::Trunc: {
1793 uint32_t truncBf =
1794 cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
1795 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask.zext(truncBf),
1796 RHSKnownZero.zext(truncBf), RHSKnownOne.zext(truncBf), Depth+1))
1797 return true;
1798 DemandedMask.trunc(BitWidth);
1799 RHSKnownZero.trunc(BitWidth);
1800 RHSKnownOne.trunc(BitWidth);
1801 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1802 "Bits known to be one AND zero?");
1803 break;
1804 }
1805 case Instruction::BitCast:
1806 if (!I->getOperand(0)->getType()->isInteger())
1807 return false;
1808
1809 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1810 RHSKnownZero, RHSKnownOne, Depth+1))
1811 return true;
1812 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1813 "Bits known to be one AND zero?");
1814 break;
1815 case Instruction::ZExt: {
1816 // Compute the bits in the result that are not present in the input.
1817 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1818 APInt NewBits(APInt::getAllOnesValue(BitWidth).shl(SrcTy->getBitWidth()));
1819
1820 DemandedMask &= SrcTy->getMask().zext(BitWidth);
1821 uint32_t zextBf = SrcTy->getBitWidth();
1822 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask.trunc(zextBf),
1823 RHSKnownZero.trunc(zextBf), RHSKnownOne.trunc(zextBf), Depth+1))
1824 return true;
1825 DemandedMask.zext(BitWidth);
1826 RHSKnownZero.zext(BitWidth);
1827 RHSKnownOne.zext(BitWidth);
1828 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1829 "Bits known to be one AND zero?");
1830 // The top bits are known to be zero.
1831 RHSKnownZero |= NewBits;
1832 break;
1833 }
1834 case Instruction::SExt: {
1835 // Compute the bits in the result that are not present in the input.
1836 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1837 APInt NewBits(APInt::getAllOnesValue(BitWidth).shl(SrcTy->getBitWidth()));
1838
1839 // Get the sign bit for the source type
1840 APInt InSignBit(APInt::getSignBit(SrcTy->getPrimitiveSizeInBits()));
1841 InSignBit.zext(BitWidth);
1842 APInt InputDemandedBits = DemandedMask &
1843 SrcTy->getMask().zext(BitWidth);
1844
1845 // If any of the sign extended bits are demanded, we know that the sign
1846 // bit is demanded.
1847 if ((NewBits & DemandedMask) != 0)
1848 InputDemandedBits |= InSignBit;
1849
1850 uint32_t sextBf = SrcTy->getBitWidth();
1851 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits.trunc(sextBf),
1852 RHSKnownZero.trunc(sextBf), RHSKnownOne.trunc(sextBf), Depth+1))
1853 return true;
1854 InputDemandedBits.zext(BitWidth);
1855 RHSKnownZero.zext(BitWidth);
1856 RHSKnownOne.zext(BitWidth);
1857 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1858 "Bits known to be one AND zero?");
1859
1860 // If the sign bit of the input is known set or clear, then we know the
1861 // top bits of the result.
1862
1863 // If the input sign bit is known zero, or if the NewBits are not demanded
1864 // convert this into a zero extension.
1865 if ((RHSKnownZero & InSignBit) != 0 || (NewBits & ~DemandedMask) == NewBits)
1866 {
1867 // Convert to ZExt cast
1868 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1869 return UpdateValueUsesWith(I, NewCast);
1870 } else if ((RHSKnownOne & InSignBit) != 0) { // Input sign bit known set
1871 RHSKnownOne |= NewBits;
1872 RHSKnownZero &= ~NewBits;
1873 } else { // Input sign bit unknown
1874 RHSKnownZero &= ~NewBits;
1875 RHSKnownOne &= ~NewBits;
1876 }
1877 break;
1878 }
1879 case Instruction::Add: {
1880 // Figure out what the input bits are. If the top bits of the and result
1881 // are not demanded, then the add doesn't demand them from its input
1882 // either.
1883 unsigned NLZ = DemandedMask.countLeadingZeros();
1884
1885 // If there is a constant on the RHS, there are a variety of xformations
1886 // we can do.
1887 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1888 // If null, this should be simplified elsewhere. Some of the xforms here
1889 // won't work if the RHS is zero.
1890 if (RHS->isZero())
1891 break;
1892
1893 // If the top bit of the output is demanded, demand everything from the
1894 // input. Otherwise, we demand all the input bits except NLZ top bits.
1895 APInt InDemandedBits(APInt::getAllOnesValue(BitWidth).lshr(NLZ));
1896
1897 // Find information about known zero/one bits in the input.
1898 if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits,
1899 LHSKnownZero, LHSKnownOne, Depth+1))
1900 return true;
1901
1902 // If the RHS of the add has bits set that can't affect the input, reduce
1903 // the constant.
1904 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1905 return UpdateValueUsesWith(I, I);
1906
1907 // Avoid excess work.
1908 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1909 break;
1910
1911 // Turn it into OR if input bits are zero.
1912 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1913 Instruction *Or =
1914 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1915 I->getName());
1916 InsertNewInstBefore(Or, *I);
1917 return UpdateValueUsesWith(I, Or);
1918 }
1919
1920 // We can say something about the output known-zero and known-one bits,
1921 // depending on potential carries from the input constant and the
1922 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1923 // bits set and the RHS constant is 0x01001, then we know we have a known
1924 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1925
1926 // To compute this, we first compute the potential carry bits. These are
1927 // the bits which may be modified. I'm not aware of a better way to do
1928 // this scan.
1929 APInt RHSVal(RHS->getValue());
1930
1931 bool CarryIn = false;
1932 APInt CarryBits(BitWidth, 0);
1933 const uint64_t *LHSKnownZeroRawVal = LHSKnownZero.getRawData(),
1934 *RHSRawVal = RHSVal.getRawData();
1935 for (uint32_t i = 0; i != RHSVal.getNumWords(); ++i) {
1936 uint64_t AddVal = ~LHSKnownZeroRawVal[i] + RHSRawVal[i],
1937 XorVal = ~LHSKnownZeroRawVal[i] ^ RHSRawVal[i];
1938 uint64_t WordCarryBits = AddVal ^ XorVal + CarryIn;
1939 if (AddVal < RHSRawVal[i])
1940 CarryIn = true;
1941 else
1942 CarryIn = false;
1943 CarryBits.setWordToValue(i, WordCarryBits);
1944 }
1945
1946 // Now that we know which bits have carries, compute the known-1/0 sets.
1947
1948 // Bits are known one if they are known zero in one operand and one in the
1949 // other, and there is no input carry.
1950 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1951 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1952
1953 // Bits are known zero if they are known zero in both operands and there
1954 // is no input carry.
1955 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1956 } else {
1957 // If the high-bits of this ADD are not demanded, then it does not demand
1958 // the high bits of its LHS or RHS.
1959 if ((DemandedMask & APInt::getSignBit(BitWidth)) == 0) {
1960 // Right fill the mask of bits for this ADD to demand the most
1961 // significant bit and all those below it.
1962 APInt DemandedFromOps = APInt::getAllOnesValue(BitWidth).lshr(NLZ);
1963 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1964 LHSKnownZero, LHSKnownOne, Depth+1))
1965 return true;
1966 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1967 LHSKnownZero, LHSKnownOne, Depth+1))
1968 return true;
1969 }
1970 }
1971 break;
1972 }
1973 case Instruction::Sub:
1974 // If the high-bits of this SUB are not demanded, then it does not demand
1975 // the high bits of its LHS or RHS.
1976 if ((DemandedMask & APInt::getSignBit(BitWidth)) == 0) {
1977 // Right fill the mask of bits for this SUB to demand the most
1978 // significant bit and all those below it.
1979 unsigned NLZ = DemandedMask.countLeadingZeros();
1980 APInt DemandedFromOps(APInt::getAllOnesValue(BitWidth).lshr(NLZ));
1981 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1982 LHSKnownZero, LHSKnownOne, Depth+1))
1983 return true;
1984 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1985 LHSKnownZero, LHSKnownOne, Depth+1))
1986 return true;
1987 }
1988 break;
1989 case Instruction::Shl:
1990 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1991 uint64_t ShiftAmt = SA->getZExtValue();
1992 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask.lshr(ShiftAmt),
1993 RHSKnownZero, RHSKnownOne, Depth+1))
1994 return true;
1995 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1996 "Bits known to be one AND zero?");
1997 RHSKnownZero <<= ShiftAmt;
1998 RHSKnownOne <<= ShiftAmt;
1999 // low bits known zero.
Zhou Shengadc14952007-03-14 09:07:33 +00002000 if (ShiftAmt)
2001 RHSKnownZero |= APInt::getAllOnesValue(ShiftAmt).zextOrCopy(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00002002 }
2003 break;
2004 case Instruction::LShr:
2005 // For a logical shift right
2006 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
2007 unsigned ShiftAmt = SA->getZExtValue();
2008
2009 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
2010 // Unsigned shift right.
2011 if (SimplifyDemandedBits(I->getOperand(0),
2012 (DemandedMask.shl(ShiftAmt)) & TypeMask,
2013 RHSKnownZero, RHSKnownOne, Depth+1))
2014 return true;
2015 assert((RHSKnownZero & RHSKnownOne) == 0 &&
2016 "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00002017 RHSKnownZero &= TypeMask;
2018 RHSKnownOne &= TypeMask;
2019 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
2020 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
Zhou Shengadc14952007-03-14 09:07:33 +00002021 if (ShiftAmt) {
2022 // Compute the new bits that are at the top now.
2023 APInt HighBits(APInt::getAllOnesValue(BitWidth).shl(
2024 BitWidth - ShiftAmt));
2025 RHSKnownZero |= HighBits; // high bits known zero.
2026 }
Reid Spencer8cb68342007-03-12 17:25:59 +00002027 }
2028 break;
2029 case Instruction::AShr:
2030 // If this is an arithmetic shift right and only the low-bit is set, we can
2031 // always convert this into a logical shr, even if the shift amount is
2032 // variable. The low bit of the shift cannot be an input sign bit unless
2033 // the shift amount is >= the size of the datatype, which is undefined.
2034 if (DemandedMask == 1) {
2035 // Perform the logical shift right.
2036 Value *NewVal = BinaryOperator::createLShr(
2037 I->getOperand(0), I->getOperand(1), I->getName());
2038 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
2039 return UpdateValueUsesWith(I, NewVal);
2040 }
2041
2042 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
2043 unsigned ShiftAmt = SA->getZExtValue();
2044
2045 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
2046 // Signed shift right.
2047 if (SimplifyDemandedBits(I->getOperand(0),
2048 (DemandedMask.shl(ShiftAmt)) & TypeMask,
2049 RHSKnownZero, RHSKnownOne, Depth+1))
2050 return true;
2051 assert((RHSKnownZero & RHSKnownOne) == 0 &&
2052 "Bits known to be one AND zero?");
2053 // Compute the new bits that are at the top now.
Zhou Shengadc14952007-03-14 09:07:33 +00002054 APInt HighBits(APInt::getAllOnesValue(BitWidth).shl(BitWidth - ShiftAmt));
Reid Spencer8cb68342007-03-12 17:25:59 +00002055 RHSKnownZero &= TypeMask;
2056 RHSKnownOne &= TypeMask;
2057 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
2058 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
2059
2060 // Handle the sign bits.
2061 APInt SignBit(APInt::getSignBit(BitWidth));
2062 // Adjust to where it is now in the mask.
2063 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
2064
2065 // If the input sign bit is known to be zero, or if none of the top bits
2066 // are demanded, turn this into an unsigned shift right.
2067 if ((RHSKnownZero & SignBit) != 0 ||
2068 (HighBits & ~DemandedMask) == HighBits) {
2069 // Perform the logical shift right.
2070 Value *NewVal = BinaryOperator::createLShr(
2071 I->getOperand(0), SA, I->getName());
2072 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
2073 return UpdateValueUsesWith(I, NewVal);
2074 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
2075 RHSKnownOne |= HighBits;
2076 }
2077 }
2078 break;
2079 }
2080
2081 // If the client is only demanding bits that we know, return the known
2082 // constant.
2083 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
2084 return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
2085 return false;
2086}
2087
Chris Lattner867b99f2006-10-05 06:55:50 +00002088
2089/// SimplifyDemandedVectorElts - The specified value producecs a vector with
2090/// 64 or fewer elements. DemandedElts contains the set of elements that are
2091/// actually used by the caller. This method analyzes which elements of the
2092/// operand are undef and returns that information in UndefElts.
2093///
2094/// If the information about demanded elements can be used to simplify the
2095/// operation, the operation is simplified, then the resultant value is
2096/// returned. This returns null if no change was made.
2097Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
2098 uint64_t &UndefElts,
2099 unsigned Depth) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00002100 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner867b99f2006-10-05 06:55:50 +00002101 assert(VWidth <= 64 && "Vector too wide to analyze!");
2102 uint64_t EltMask = ~0ULL >> (64-VWidth);
2103 assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
2104 "Invalid DemandedElts!");
2105
2106 if (isa<UndefValue>(V)) {
2107 // If the entire vector is undefined, just return this info.
2108 UndefElts = EltMask;
2109 return 0;
2110 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
2111 UndefElts = EltMask;
2112 return UndefValue::get(V->getType());
2113 }
2114
2115 UndefElts = 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +00002116 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
2117 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner867b99f2006-10-05 06:55:50 +00002118 Constant *Undef = UndefValue::get(EltTy);
2119
2120 std::vector<Constant*> Elts;
2121 for (unsigned i = 0; i != VWidth; ++i)
2122 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
2123 Elts.push_back(Undef);
2124 UndefElts |= (1ULL << i);
2125 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
2126 Elts.push_back(Undef);
2127 UndefElts |= (1ULL << i);
2128 } else { // Otherwise, defined.
2129 Elts.push_back(CP->getOperand(i));
2130 }
2131
2132 // If we changed the constant, return it.
Reid Spencer9d6565a2007-02-15 02:26:10 +00002133 Constant *NewCP = ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00002134 return NewCP != CP ? NewCP : 0;
2135 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00002136 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner867b99f2006-10-05 06:55:50 +00002137 // set to undef.
Reid Spencer9d6565a2007-02-15 02:26:10 +00002138 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner867b99f2006-10-05 06:55:50 +00002139 Constant *Zero = Constant::getNullValue(EltTy);
2140 Constant *Undef = UndefValue::get(EltTy);
2141 std::vector<Constant*> Elts;
2142 for (unsigned i = 0; i != VWidth; ++i)
2143 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
2144 UndefElts = DemandedElts ^ EltMask;
Reid Spencer9d6565a2007-02-15 02:26:10 +00002145 return ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00002146 }
2147
2148 if (!V->hasOneUse()) { // Other users may use these bits.
2149 if (Depth != 0) { // Not at the root.
2150 // TODO: Just compute the UndefElts information recursively.
2151 return false;
2152 }
2153 return false;
2154 } else if (Depth == 10) { // Limit search depth.
2155 return false;
2156 }
2157
2158 Instruction *I = dyn_cast<Instruction>(V);
2159 if (!I) return false; // Only analyze instructions.
2160
2161 bool MadeChange = false;
2162 uint64_t UndefElts2;
2163 Value *TmpV;
2164 switch (I->getOpcode()) {
2165 default: break;
2166
2167 case Instruction::InsertElement: {
2168 // If this is a variable index, we don't know which element it overwrites.
2169 // demand exactly the same input as we produce.
Reid Spencerb83eb642006-10-20 07:07:24 +00002170 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner867b99f2006-10-05 06:55:50 +00002171 if (Idx == 0) {
2172 // Note that we can't propagate undef elt info, because we don't know
2173 // which elt is getting updated.
2174 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
2175 UndefElts2, Depth+1);
2176 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
2177 break;
2178 }
2179
2180 // If this is inserting an element that isn't demanded, remove this
2181 // insertelement.
Reid Spencerb83eb642006-10-20 07:07:24 +00002182 unsigned IdxNo = Idx->getZExtValue();
Chris Lattner867b99f2006-10-05 06:55:50 +00002183 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
2184 return AddSoonDeadInstToWorklist(*I, 0);
2185
2186 // Otherwise, the element inserted overwrites whatever was there, so the
2187 // input demanded set is simpler than the output set.
2188 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
2189 DemandedElts & ~(1ULL << IdxNo),
2190 UndefElts, Depth+1);
2191 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
2192
2193 // The inserted element is defined.
2194 UndefElts |= 1ULL << IdxNo;
2195 break;
2196 }
2197
2198 case Instruction::And:
2199 case Instruction::Or:
2200 case Instruction::Xor:
2201 case Instruction::Add:
2202 case Instruction::Sub:
2203 case Instruction::Mul:
2204 // div/rem demand all inputs, because they don't want divide by zero.
2205 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
2206 UndefElts, Depth+1);
2207 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
2208 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
2209 UndefElts2, Depth+1);
2210 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
2211
2212 // Output elements are undefined if both are undefined. Consider things
2213 // like undef&0. The result is known zero, not undef.
2214 UndefElts &= UndefElts2;
2215 break;
2216
2217 case Instruction::Call: {
2218 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
2219 if (!II) break;
2220 switch (II->getIntrinsicID()) {
2221 default: break;
2222
2223 // Binary vector operations that work column-wise. A dest element is a
2224 // function of the corresponding input elements from the two inputs.
2225 case Intrinsic::x86_sse_sub_ss:
2226 case Intrinsic::x86_sse_mul_ss:
2227 case Intrinsic::x86_sse_min_ss:
2228 case Intrinsic::x86_sse_max_ss:
2229 case Intrinsic::x86_sse2_sub_sd:
2230 case Intrinsic::x86_sse2_mul_sd:
2231 case Intrinsic::x86_sse2_min_sd:
2232 case Intrinsic::x86_sse2_max_sd:
2233 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
2234 UndefElts, Depth+1);
2235 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
2236 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
2237 UndefElts2, Depth+1);
2238 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
2239
2240 // If only the low elt is demanded and this is a scalarizable intrinsic,
2241 // scalarize it now.
2242 if (DemandedElts == 1) {
2243 switch (II->getIntrinsicID()) {
2244 default: break;
2245 case Intrinsic::x86_sse_sub_ss:
2246 case Intrinsic::x86_sse_mul_ss:
2247 case Intrinsic::x86_sse2_sub_sd:
2248 case Intrinsic::x86_sse2_mul_sd:
2249 // TODO: Lower MIN/MAX/ABS/etc
2250 Value *LHS = II->getOperand(1);
2251 Value *RHS = II->getOperand(2);
2252 // Extract the element as scalars.
2253 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
2254 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
2255
2256 switch (II->getIntrinsicID()) {
2257 default: assert(0 && "Case stmts out of sync!");
2258 case Intrinsic::x86_sse_sub_ss:
2259 case Intrinsic::x86_sse2_sub_sd:
2260 TmpV = InsertNewInstBefore(BinaryOperator::createSub(LHS, RHS,
2261 II->getName()), *II);
2262 break;
2263 case Intrinsic::x86_sse_mul_ss:
2264 case Intrinsic::x86_sse2_mul_sd:
2265 TmpV = InsertNewInstBefore(BinaryOperator::createMul(LHS, RHS,
2266 II->getName()), *II);
2267 break;
2268 }
2269
2270 Instruction *New =
2271 new InsertElementInst(UndefValue::get(II->getType()), TmpV, 0U,
2272 II->getName());
2273 InsertNewInstBefore(New, *II);
2274 AddSoonDeadInstToWorklist(*II, 0);
2275 return New;
2276 }
2277 }
2278
2279 // Output elements are undefined if both are undefined. Consider things
2280 // like undef&0. The result is known zero, not undef.
2281 UndefElts &= UndefElts2;
2282 break;
2283 }
2284 break;
2285 }
2286 }
2287 return MadeChange ? I : 0;
2288}
2289
Reid Spencere4d87aa2006-12-23 06:05:41 +00002290/// @returns true if the specified compare instruction is
2291/// true when both operands are equal...
2292/// @brief Determine if the ICmpInst returns true if both operands are equal
2293static bool isTrueWhenEqual(ICmpInst &ICI) {
2294 ICmpInst::Predicate pred = ICI.getPredicate();
2295 return pred == ICmpInst::ICMP_EQ || pred == ICmpInst::ICMP_UGE ||
2296 pred == ICmpInst::ICMP_SGE || pred == ICmpInst::ICMP_ULE ||
2297 pred == ICmpInst::ICMP_SLE;
2298}
2299
Chris Lattner564a7272003-08-13 19:01:45 +00002300/// AssociativeOpt - Perform an optimization on an associative operator. This
2301/// function is designed to check a chain of associative operators for a
2302/// potential to apply a certain optimization. Since the optimization may be
2303/// applicable if the expression was reassociated, this checks the chain, then
2304/// reassociates the expression as necessary to expose the optimization
2305/// opportunity. This makes use of a special Functor, which must define
2306/// 'shouldApply' and 'apply' methods.
2307///
2308template<typename Functor>
2309Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
2310 unsigned Opcode = Root.getOpcode();
2311 Value *LHS = Root.getOperand(0);
2312
2313 // Quick check, see if the immediate LHS matches...
2314 if (F.shouldApply(LHS))
2315 return F.apply(Root);
2316
2317 // Otherwise, if the LHS is not of the same opcode as the root, return.
2318 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +00002319 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +00002320 // Should we apply this transform to the RHS?
2321 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
2322
2323 // If not to the RHS, check to see if we should apply to the LHS...
2324 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
2325 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
2326 ShouldApply = true;
2327 }
2328
2329 // If the functor wants to apply the optimization to the RHS of LHSI,
2330 // reassociate the expression from ((? op A) op B) to (? op (A op B))
2331 if (ShouldApply) {
2332 BasicBlock *BB = Root.getParent();
Misha Brukmanfd939082005-04-21 23:48:37 +00002333
Chris Lattner564a7272003-08-13 19:01:45 +00002334 // Now all of the instructions are in the current basic block, go ahead
2335 // and perform the reassociation.
2336 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
2337
2338 // First move the selected RHS to the LHS of the root...
2339 Root.setOperand(0, LHSI->getOperand(1));
2340
2341 // Make what used to be the LHS of the root be the user of the root...
2342 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +00002343 if (&Root == TmpLHSI) {
Chris Lattner15a76c02004-04-05 02:10:19 +00002344 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
2345 return 0;
2346 }
Chris Lattner65725312004-04-16 18:08:07 +00002347 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +00002348 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +00002349 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
2350 BasicBlock::iterator ARI = &Root; ++ARI;
2351 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
2352 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +00002353
2354 // Now propagate the ExtraOperand down the chain of instructions until we
2355 // get to LHSI.
2356 while (TmpLHSI != LHSI) {
2357 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +00002358 // Move the instruction to immediately before the chain we are
2359 // constructing to avoid breaking dominance properties.
2360 NextLHSI->getParent()->getInstList().remove(NextLHSI);
2361 BB->getInstList().insert(ARI, NextLHSI);
2362 ARI = NextLHSI;
2363
Chris Lattner564a7272003-08-13 19:01:45 +00002364 Value *NextOp = NextLHSI->getOperand(1);
2365 NextLHSI->setOperand(1, ExtraOperand);
2366 TmpLHSI = NextLHSI;
2367 ExtraOperand = NextOp;
2368 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002369
Chris Lattner564a7272003-08-13 19:01:45 +00002370 // Now that the instructions are reassociated, have the functor perform
2371 // the transformation...
2372 return F.apply(Root);
2373 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002374
Chris Lattner564a7272003-08-13 19:01:45 +00002375 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
2376 }
2377 return 0;
2378}
2379
2380
2381// AddRHS - Implements: X + X --> X << 1
2382struct AddRHS {
2383 Value *RHS;
2384 AddRHS(Value *rhs) : RHS(rhs) {}
2385 bool shouldApply(Value *LHS) const { return LHS == RHS; }
2386 Instruction *apply(BinaryOperator &Add) const {
Reid Spencercc46cdb2007-02-02 14:08:20 +00002387 return BinaryOperator::createShl(Add.getOperand(0),
Reid Spencer832254e2007-02-02 02:16:23 +00002388 ConstantInt::get(Add.getType(), 1));
Chris Lattner564a7272003-08-13 19:01:45 +00002389 }
2390};
2391
2392// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
2393// iff C1&C2 == 0
2394struct AddMaskingAnd {
2395 Constant *C2;
2396 AddMaskingAnd(Constant *c) : C2(c) {}
2397 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002398 ConstantInt *C1;
Misha Brukmanfd939082005-04-21 23:48:37 +00002399 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002400 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +00002401 }
2402 Instruction *apply(BinaryOperator &Add) const {
Chris Lattner48595f12004-06-10 02:07:29 +00002403 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +00002404 }
2405};
2406
Chris Lattner6e7ba452005-01-01 16:22:27 +00002407static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +00002408 InstCombiner *IC) {
Reid Spencer3da59db2006-11-27 01:05:10 +00002409 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Chris Lattner6e7ba452005-01-01 16:22:27 +00002410 if (Constant *SOC = dyn_cast<Constant>(SO))
Reid Spencer3da59db2006-11-27 01:05:10 +00002411 return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
Misha Brukmanfd939082005-04-21 23:48:37 +00002412
Reid Spencer3da59db2006-11-27 01:05:10 +00002413 return IC->InsertNewInstBefore(CastInst::create(
2414 CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
Chris Lattner6e7ba452005-01-01 16:22:27 +00002415 }
2416
Chris Lattner2eefe512004-04-09 19:05:30 +00002417 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +00002418 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
2419 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +00002420
Chris Lattner2eefe512004-04-09 19:05:30 +00002421 if (Constant *SOC = dyn_cast<Constant>(SO)) {
2422 if (ConstIsRHS)
Chris Lattner6e7ba452005-01-01 16:22:27 +00002423 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
2424 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +00002425 }
2426
2427 Value *Op0 = SO, *Op1 = ConstOperand;
2428 if (!ConstIsRHS)
2429 std::swap(Op0, Op1);
2430 Instruction *New;
Chris Lattner6e7ba452005-01-01 16:22:27 +00002431 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
2432 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Reid Spencere4d87aa2006-12-23 06:05:41 +00002433 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2434 New = CmpInst::create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
2435 SO->getName()+".cmp");
Chris Lattner326c0f32004-04-10 19:15:56 +00002436 else {
Chris Lattner2eefe512004-04-09 19:05:30 +00002437 assert(0 && "Unknown binary instruction type!");
Chris Lattner326c0f32004-04-10 19:15:56 +00002438 abort();
2439 }
Chris Lattner6e7ba452005-01-01 16:22:27 +00002440 return IC->InsertNewInstBefore(New, I);
2441}
2442
2443// FoldOpIntoSelect - Given an instruction with a select as one operand and a
2444// constant as the other operand, try to fold the binary operator into the
2445// select arguments. This also works for Cast instructions, which obviously do
2446// not have a second operand.
2447static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
2448 InstCombiner *IC) {
2449 // Don't modify shared select instructions
2450 if (!SI->hasOneUse()) return 0;
2451 Value *TV = SI->getOperand(1);
2452 Value *FV = SI->getOperand(2);
2453
2454 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +00002455 // Bool selects with constant operands can be folded to logical ops.
Reid Spencer4fe16d62007-01-11 18:21:29 +00002456 if (SI->getType() == Type::Int1Ty) return 0;
Chris Lattner956db272005-04-21 05:43:13 +00002457
Chris Lattner6e7ba452005-01-01 16:22:27 +00002458 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
2459 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
2460
2461 return new SelectInst(SI->getCondition(), SelectTrueVal,
2462 SelectFalseVal);
2463 }
2464 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +00002465}
2466
Chris Lattner4e998b22004-09-29 05:07:12 +00002467
2468/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
2469/// node as operand #0, see if we can fold the instruction into the PHI (which
2470/// is only possible if all operands to the PHI are constants).
2471Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
2472 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00002473 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002474 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner4e998b22004-09-29 05:07:12 +00002475
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002476 // Check to see if all of the operands of the PHI are constants. If there is
2477 // one non-constant value, remember the BB it is. If there is more than one
Chris Lattnerb3036682007-02-24 01:03:45 +00002478 // or if *it* is a PHI, bail out.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002479 BasicBlock *NonConstBB = 0;
2480 for (unsigned i = 0; i != NumPHIValues; ++i)
2481 if (!isa<Constant>(PN->getIncomingValue(i))) {
2482 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +00002483 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002484 NonConstBB = PN->getIncomingBlock(i);
2485
2486 // If the incoming non-constant value is in I's block, we have an infinite
2487 // loop.
2488 if (NonConstBB == I.getParent())
2489 return 0;
2490 }
2491
2492 // If there is exactly one non-constant value, we can insert a copy of the
2493 // operation in that block. However, if this is a critical edge, we would be
2494 // inserting the computation one some other paths (e.g. inside a loop). Only
2495 // do this if the pred block is unconditionally branching into the phi block.
2496 if (NonConstBB) {
2497 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
2498 if (!BI || !BI->isUnconditional()) return 0;
2499 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002500
2501 // Okay, we can do the transformation: create the new PHI node.
Chris Lattner6934a042007-02-11 01:23:03 +00002502 PHINode *NewPN = new PHINode(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +00002503 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner4e998b22004-09-29 05:07:12 +00002504 InsertNewInstBefore(NewPN, *PN);
Chris Lattner6934a042007-02-11 01:23:03 +00002505 NewPN->takeName(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +00002506
2507 // Next, add all of the operands to the PHI.
2508 if (I.getNumOperands() == 2) {
2509 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +00002510 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002511 Value *InV;
2512 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002513 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2514 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
2515 else
2516 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002517 } else {
2518 assert(PN->getIncomingBlock(i) == NonConstBB);
2519 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
2520 InV = BinaryOperator::create(BO->getOpcode(),
2521 PN->getIncomingValue(i), C, "phitmp",
2522 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +00002523 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2524 InV = CmpInst::create(CI->getOpcode(),
2525 CI->getPredicate(),
2526 PN->getIncomingValue(i), C, "phitmp",
2527 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002528 else
2529 assert(0 && "Unknown binop!");
2530
Chris Lattnerdbab3862007-03-02 21:28:56 +00002531 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002532 }
2533 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002534 }
Reid Spencer3da59db2006-11-27 01:05:10 +00002535 } else {
2536 CastInst *CI = cast<CastInst>(&I);
2537 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +00002538 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002539 Value *InV;
2540 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00002541 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002542 } else {
2543 assert(PN->getIncomingBlock(i) == NonConstBB);
Reid Spencer3da59db2006-11-27 01:05:10 +00002544 InV = CastInst::create(CI->getOpcode(), PN->getIncomingValue(i),
2545 I.getType(), "phitmp",
2546 NonConstBB->getTerminator());
Chris Lattnerdbab3862007-03-02 21:28:56 +00002547 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002548 }
2549 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002550 }
2551 }
2552 return ReplaceInstUsesWith(I, NewPN);
2553}
2554
Chris Lattner7e708292002-06-25 16:13:24 +00002555Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002556 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002557 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002558
Chris Lattner66331a42004-04-10 22:01:55 +00002559 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattnere87597f2004-10-16 18:11:37 +00002560 // X + undef -> undef
2561 if (isa<UndefValue>(RHS))
2562 return ReplaceInstUsesWith(I, RHS);
2563
Chris Lattner66331a42004-04-10 22:01:55 +00002564 // X + 0 --> X
Chris Lattner9919e3d2006-12-02 00:13:08 +00002565 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
Chris Lattner5e678e02005-10-17 17:56:38 +00002566 if (RHSC->isNullValue())
2567 return ReplaceInstUsesWith(I, LHS);
Chris Lattner8532cf62005-10-17 20:18:38 +00002568 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2569 if (CFP->isExactlyValue(-0.0))
2570 return ReplaceInstUsesWith(I, LHS);
Chris Lattner5e678e02005-10-17 17:56:38 +00002571 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002572
Chris Lattner66331a42004-04-10 22:01:55 +00002573 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002574 // X + (signbit) --> X ^ signbit
Chris Lattner74c51a02006-02-07 08:05:22 +00002575 uint64_t Val = CI->getZExtValue();
Chris Lattner1a074fc2006-02-07 07:00:41 +00002576 if (Val == (1ULL << (CI->getType()->getPrimitiveSizeInBits()-1)))
Chris Lattner48595f12004-06-10 02:07:29 +00002577 return BinaryOperator::createXor(LHS, RHS);
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002578
2579 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2580 // (X & 254)+1 -> (X&254)|1
2581 uint64_t KnownZero, KnownOne;
Reid Spencer9d6565a2007-02-15 02:26:10 +00002582 if (!isa<VectorType>(I.getType()) &&
Reid Spencerc1030572007-01-19 21:13:56 +00002583 SimplifyDemandedBits(&I, cast<IntegerType>(I.getType())->getBitMask(),
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002584 KnownZero, KnownOne))
2585 return &I;
Chris Lattner66331a42004-04-10 22:01:55 +00002586 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002587
2588 if (isa<PHINode>(LHS))
2589 if (Instruction *NV = FoldOpIntoPhi(I))
2590 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +00002591
Chris Lattner4f637d42006-01-06 17:59:59 +00002592 ConstantInt *XorRHS = 0;
2593 Value *XorLHS = 0;
Chris Lattnerc5eff442007-01-30 22:32:46 +00002594 if (isa<ConstantInt>(RHSC) &&
2595 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Chris Lattner5931c542005-09-24 23:43:33 +00002596 unsigned TySizeBits = I.getType()->getPrimitiveSizeInBits();
2597 int64_t RHSSExt = cast<ConstantInt>(RHSC)->getSExtValue();
2598 uint64_t RHSZExt = cast<ConstantInt>(RHSC)->getZExtValue();
2599
2600 uint64_t C0080Val = 1ULL << 31;
2601 int64_t CFF80Val = -C0080Val;
2602 unsigned Size = 32;
2603 do {
2604 if (TySizeBits > Size) {
2605 bool Found = false;
2606 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2607 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2608 if (RHSSExt == CFF80Val) {
2609 if (XorRHS->getZExtValue() == C0080Val)
2610 Found = true;
2611 } else if (RHSZExt == C0080Val) {
2612 if (XorRHS->getSExtValue() == CFF80Val)
2613 Found = true;
2614 }
2615 if (Found) {
2616 // This is a sign extend if the top bits are known zero.
Chris Lattner68d5ff22006-02-09 07:38:58 +00002617 uint64_t Mask = ~0ULL;
Chris Lattner3bedbd92006-02-07 07:27:52 +00002618 Mask <<= 64-(TySizeBits-Size);
Reid Spencerc1030572007-01-19 21:13:56 +00002619 Mask &= cast<IntegerType>(XorLHS->getType())->getBitMask();
Chris Lattner3bedbd92006-02-07 07:27:52 +00002620 if (!MaskedValueIsZero(XorLHS, Mask))
Chris Lattner5931c542005-09-24 23:43:33 +00002621 Size = 0; // Not a sign ext, but can't be any others either.
2622 goto FoundSExt;
2623 }
2624 }
2625 Size >>= 1;
2626 C0080Val >>= Size;
2627 CFF80Val >>= Size;
2628 } while (Size >= 8);
2629
2630FoundSExt:
2631 const Type *MiddleType = 0;
2632 switch (Size) {
2633 default: break;
Reid Spencerc5b206b2006-12-31 05:48:39 +00002634 case 32: MiddleType = Type::Int32Ty; break;
2635 case 16: MiddleType = Type::Int16Ty; break;
2636 case 8: MiddleType = Type::Int8Ty; break;
Chris Lattner5931c542005-09-24 23:43:33 +00002637 }
2638 if (MiddleType) {
Reid Spencerd977d862006-12-12 23:36:14 +00002639 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
Chris Lattner5931c542005-09-24 23:43:33 +00002640 InsertNewInstBefore(NewTrunc, I);
Reid Spencer3da59db2006-11-27 01:05:10 +00002641 return new SExtInst(NewTrunc, I.getType());
Chris Lattner5931c542005-09-24 23:43:33 +00002642 }
2643 }
Chris Lattner66331a42004-04-10 22:01:55 +00002644 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002645
Chris Lattner564a7272003-08-13 19:01:45 +00002646 // X + X --> X << 1
Chris Lattner42a75512007-01-15 02:27:26 +00002647 if (I.getType()->isInteger() && I.getType() != Type::Int1Ty) {
Chris Lattner564a7272003-08-13 19:01:45 +00002648 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +00002649
2650 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2651 if (RHSI->getOpcode() == Instruction::Sub)
2652 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2653 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2654 }
2655 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2656 if (LHSI->getOpcode() == Instruction::Sub)
2657 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2658 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2659 }
Robert Bocchino71698282004-07-27 21:02:21 +00002660 }
Chris Lattnere92d2f42003-08-13 04:18:28 +00002661
Chris Lattner5c4afb92002-05-08 22:46:53 +00002662 // -A + B --> B - A
Chris Lattner8d969642003-03-10 23:06:50 +00002663 if (Value *V = dyn_castNegVal(LHS))
Chris Lattner48595f12004-06-10 02:07:29 +00002664 return BinaryOperator::createSub(RHS, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002665
2666 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +00002667 if (!isa<Constant>(RHS))
2668 if (Value *V = dyn_castNegVal(RHS))
Chris Lattner48595f12004-06-10 02:07:29 +00002669 return BinaryOperator::createSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002670
Misha Brukmanfd939082005-04-21 23:48:37 +00002671
Chris Lattner50af16a2004-11-13 19:50:12 +00002672 ConstantInt *C2;
2673 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2674 if (X == RHS) // X*C + X --> X * (C+1)
2675 return BinaryOperator::createMul(RHS, AddOne(C2));
2676
2677 // X*C1 + X*C2 --> X * (C1+C2)
2678 ConstantInt *C1;
2679 if (X == dyn_castFoldableMul(RHS, C1))
2680 return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002681 }
2682
2683 // X + X*C --> X * (C+1)
Chris Lattner50af16a2004-11-13 19:50:12 +00002684 if (dyn_castFoldableMul(RHS, C2) == LHS)
2685 return BinaryOperator::createMul(LHS, AddOne(C2));
2686
Chris Lattnere617c9e2007-01-05 02:17:46 +00002687 // X + ~X --> -1 since ~X = -X-1
2688 if (dyn_castNotVal(LHS) == RHS ||
2689 dyn_castNotVal(RHS) == LHS)
2690 return ReplaceInstUsesWith(I, ConstantInt::getAllOnesValue(I.getType()));
2691
Chris Lattnerad3448c2003-02-18 19:57:07 +00002692
Chris Lattner564a7272003-08-13 19:01:45 +00002693 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002694 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnere617c9e2007-01-05 02:17:46 +00002695 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2696 return R;
Chris Lattnerc8802d22003-03-11 00:12:48 +00002697
Chris Lattner6b032052003-10-02 15:11:26 +00002698 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002699 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002700 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
2701 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
2702 return BinaryOperator::createSub(C, X);
Chris Lattner6b032052003-10-02 15:11:26 +00002703 }
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002704
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002705 // (X & FF00) + xx00 -> (X+xx00) & FF00
2706 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2707 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
2708 if (Anded == CRHS) {
2709 // See if all bits from the first bit set in the Add RHS up are included
2710 // in the mask. First, get the rightmost bit.
Reid Spencerb83eb642006-10-20 07:07:24 +00002711 uint64_t AddRHSV = CRHS->getZExtValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002712
2713 // Form a mask of all bits from the lowest bit added through the top.
2714 uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
Reid Spencerc1030572007-01-19 21:13:56 +00002715 AddRHSHighBits &= C2->getType()->getBitMask();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002716
2717 // See if the and mask includes all of these bits.
Reid Spencerb83eb642006-10-20 07:07:24 +00002718 uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getZExtValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00002719
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002720 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2721 // Okay, the xform is safe. Insert the new add pronto.
2722 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
2723 LHS->getName()), I);
2724 return BinaryOperator::createAnd(NewAdd, C2);
2725 }
2726 }
2727 }
2728
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002729 // Try to fold constant add into select arguments.
2730 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002731 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002732 return R;
Chris Lattner6b032052003-10-02 15:11:26 +00002733 }
2734
Reid Spencer1628cec2006-10-26 06:15:43 +00002735 // add (cast *A to intptrtype) B ->
2736 // cast (GEP (cast *A to sbyte*) B) ->
2737 // intptrtype
Andrew Lenharth16d79552006-09-19 18:24:51 +00002738 {
Reid Spencer3da59db2006-11-27 01:05:10 +00002739 CastInst *CI = dyn_cast<CastInst>(LHS);
2740 Value *Other = RHS;
Andrew Lenharth16d79552006-09-19 18:24:51 +00002741 if (!CI) {
2742 CI = dyn_cast<CastInst>(RHS);
2743 Other = LHS;
2744 }
Andrew Lenharth45633262006-09-20 15:37:57 +00002745 if (CI && CI->getType()->isSized() &&
Reid Spencerabaa8ca2007-01-08 16:32:00 +00002746 (CI->getType()->getPrimitiveSizeInBits() ==
2747 TD->getIntPtrType()->getPrimitiveSizeInBits())
Andrew Lenharth45633262006-09-20 15:37:57 +00002748 && isa<PointerType>(CI->getOperand(0)->getType())) {
Reid Spencer17212df2006-12-12 09:18:51 +00002749 Value *I2 = InsertCastBefore(Instruction::BitCast, CI->getOperand(0),
Reid Spencerc5b206b2006-12-31 05:48:39 +00002750 PointerType::get(Type::Int8Ty), I);
Andrew Lenharth45633262006-09-20 15:37:57 +00002751 I2 = InsertNewInstBefore(new GetElementPtrInst(I2, Other, "ctg2"), I);
Reid Spencer3da59db2006-11-27 01:05:10 +00002752 return new PtrToIntInst(I2, CI->getType());
Andrew Lenharth16d79552006-09-19 18:24:51 +00002753 }
2754 }
2755
Chris Lattner7e708292002-06-25 16:13:24 +00002756 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002757}
2758
Chris Lattner1ba5bcd2003-07-22 21:46:59 +00002759// isSignBit - Return true if the value represented by the constant only has the
2760// highest order bit set.
2761static bool isSignBit(ConstantInt *CI) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00002762 unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencer5a1e3e12007-03-19 20:58:18 +00002763 return CI->getValue() == APInt::getSignBit(NumBits);
Chris Lattner1ba5bcd2003-07-22 21:46:59 +00002764}
2765
Chris Lattner7e708292002-06-25 16:13:24 +00002766Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00002767 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002768
Chris Lattner233f7dc2002-08-12 21:17:25 +00002769 if (Op0 == Op1) // sub X, X -> 0
2770 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002771
Chris Lattner233f7dc2002-08-12 21:17:25 +00002772 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattner8d969642003-03-10 23:06:50 +00002773 if (Value *V = dyn_castNegVal(Op1))
Chris Lattner48595f12004-06-10 02:07:29 +00002774 return BinaryOperator::createAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002775
Chris Lattnere87597f2004-10-16 18:11:37 +00002776 if (isa<UndefValue>(Op0))
2777 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2778 if (isa<UndefValue>(Op1))
2779 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2780
Chris Lattnerd65460f2003-11-05 01:06:05 +00002781 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2782 // Replace (-1 - A) with (~A)...
Chris Lattnera2881962003-02-18 19:28:33 +00002783 if (C->isAllOnesValue())
2784 return BinaryOperator::createNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +00002785
Chris Lattnerd65460f2003-11-05 01:06:05 +00002786 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002787 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002788 if (match(Op1, m_Not(m_Value(X))))
2789 return BinaryOperator::createAdd(X,
Chris Lattner48595f12004-06-10 02:07:29 +00002790 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
Chris Lattner76b7a062007-01-15 07:02:54 +00002791 // -(X >>u 31) -> (X >>s 31)
2792 // -(X >>s 31) -> (X >>u 31)
Chris Lattnerbfe492b2004-03-13 00:11:49 +00002793 if (C->isNullValue()) {
Reid Spencer832254e2007-02-02 02:16:23 +00002794 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1))
Reid Spencer3822ff52006-11-08 06:47:33 +00002795 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002796 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00002797 // Check to see if we are shifting out everything but the sign bit.
Reid Spencerb83eb642006-10-20 07:07:24 +00002798 if (CU->getZExtValue() ==
2799 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002800 // Ok, the transformation is safe. Insert AShr.
Reid Spencer832254e2007-02-02 02:16:23 +00002801 return BinaryOperator::create(Instruction::AShr,
2802 SI->getOperand(0), CU, SI->getName());
Chris Lattner9c290672004-03-12 23:53:13 +00002803 }
2804 }
Reid Spencer3822ff52006-11-08 06:47:33 +00002805 }
2806 else if (SI->getOpcode() == Instruction::AShr) {
2807 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2808 // Check to see if we are shifting out everything but the sign bit.
2809 if (CU->getZExtValue() ==
2810 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00002811 // Ok, the transformation is safe. Insert LShr.
Reid Spencercc46cdb2007-02-02 14:08:20 +00002812 return BinaryOperator::createLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00002813 SI->getOperand(0), CU, SI->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00002814 }
2815 }
2816 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00002817 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002818
2819 // Try to fold constant sub into select arguments.
2820 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002821 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002822 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002823
2824 if (isa<PHINode>(Op0))
2825 if (Instruction *NV = FoldOpIntoPhi(I))
2826 return NV;
Chris Lattnerd65460f2003-11-05 01:06:05 +00002827 }
2828
Chris Lattner43d84d62005-04-07 16:15:25 +00002829 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2830 if (Op1I->getOpcode() == Instruction::Add &&
Chris Lattner9919e3d2006-12-02 00:13:08 +00002831 !Op0->getType()->isFPOrFPVector()) {
Chris Lattner08954a22005-04-07 16:28:01 +00002832 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Chris Lattner43d84d62005-04-07 16:15:25 +00002833 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002834 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Chris Lattner43d84d62005-04-07 16:15:25 +00002835 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002836 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2837 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2838 // C1-(X+C2) --> (C1-C2)-X
2839 return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
2840 Op1I->getOperand(0));
2841 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002842 }
2843
Chris Lattnerfd059242003-10-15 16:48:29 +00002844 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002845 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2846 // is not used by anyone else...
2847 //
Chris Lattner0517e722004-02-02 20:09:56 +00002848 if (Op1I->getOpcode() == Instruction::Sub &&
Chris Lattner9919e3d2006-12-02 00:13:08 +00002849 !Op1I->getType()->isFPOrFPVector()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002850 // Swap the two operands of the subexpr...
2851 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2852 Op1I->setOperand(0, IIOp1);
2853 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00002854
Chris Lattnera2881962003-02-18 19:28:33 +00002855 // Create the new top level add instruction...
Chris Lattner48595f12004-06-10 02:07:29 +00002856 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00002857 }
2858
2859 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2860 //
2861 if (Op1I->getOpcode() == Instruction::And &&
2862 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2863 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2864
Chris Lattnerf523d062004-06-09 05:08:07 +00002865 Value *NewNot =
2866 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattner48595f12004-06-10 02:07:29 +00002867 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00002868 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00002869
Reid Spencerac5209e2006-10-16 23:08:08 +00002870 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer1628cec2006-10-26 06:15:43 +00002871 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencerb83eb642006-10-20 07:07:24 +00002872 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Reid Spencer1628cec2006-10-26 06:15:43 +00002873 if (CSI->isNullValue())
Chris Lattner91ccc152004-10-06 15:08:25 +00002874 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Reid Spencer1628cec2006-10-26 06:15:43 +00002875 return BinaryOperator::createSDiv(Op1I->getOperand(0),
Chris Lattner91ccc152004-10-06 15:08:25 +00002876 ConstantExpr::getNeg(DivRHS));
2877
Chris Lattnerad3448c2003-02-18 19:57:07 +00002878 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002879 ConstantInt *C2 = 0;
Chris Lattner50af16a2004-11-13 19:50:12 +00002880 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Misha Brukmanfd939082005-04-21 23:48:37 +00002881 Constant *CP1 =
Chris Lattner50af16a2004-11-13 19:50:12 +00002882 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
Chris Lattner48595f12004-06-10 02:07:29 +00002883 return BinaryOperator::createMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00002884 }
Chris Lattner40371712002-05-09 01:29:19 +00002885 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002886 }
Chris Lattnera2881962003-02-18 19:28:33 +00002887
Chris Lattner9919e3d2006-12-02 00:13:08 +00002888 if (!Op0->getType()->isFPOrFPVector())
Chris Lattner7edc8c22005-04-07 17:14:51 +00002889 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2890 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00002891 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2892 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2893 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2894 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner7edc8c22005-04-07 17:14:51 +00002895 } else if (Op0I->getOpcode() == Instruction::Sub) {
2896 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
2897 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00002898 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002899
Chris Lattner50af16a2004-11-13 19:50:12 +00002900 ConstantInt *C1;
2901 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2902 if (X == Op1) { // X*C - X --> X * (C-1)
2903 Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
2904 return BinaryOperator::createMul(Op1, CP1);
2905 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00002906
Chris Lattner50af16a2004-11-13 19:50:12 +00002907 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2908 if (X == dyn_castFoldableMul(Op1, C2))
2909 return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
2910 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002911 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002912}
2913
Reid Spencere4d87aa2006-12-23 06:05:41 +00002914/// isSignBitCheck - Given an exploded icmp instruction, return true if it
Chris Lattner4cb170c2004-02-23 06:38:22 +00002915/// really just returns true if the most significant (sign) bit is set.
Reid Spencere4d87aa2006-12-23 06:05:41 +00002916static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS) {
2917 switch (pred) {
2918 case ICmpInst::ICMP_SLT:
2919 // True if LHS s< RHS and RHS == 0
2920 return RHS->isNullValue();
2921 case ICmpInst::ICMP_SLE:
2922 // True if LHS s<= RHS and RHS == -1
2923 return RHS->isAllOnesValue();
2924 case ICmpInst::ICMP_UGE:
2925 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2926 return RHS->getZExtValue() == (1ULL <<
2927 (RHS->getType()->getPrimitiveSizeInBits()-1));
2928 case ICmpInst::ICMP_UGT:
2929 // True if LHS u> RHS and RHS == high-bit-mask - 1
2930 return RHS->getZExtValue() ==
Chris Lattner484d3cf2005-04-24 06:59:08 +00002931 (1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1))-1;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002932 default:
2933 return false;
Chris Lattner4cb170c2004-02-23 06:38:22 +00002934 }
Chris Lattner4cb170c2004-02-23 06:38:22 +00002935}
2936
Chris Lattner7e708292002-06-25 16:13:24 +00002937Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002938 bool Changed = SimplifyCommutative(I);
Chris Lattnera2881962003-02-18 19:28:33 +00002939 Value *Op0 = I.getOperand(0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002940
Chris Lattnere87597f2004-10-16 18:11:37 +00002941 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2942 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2943
Chris Lattner233f7dc2002-08-12 21:17:25 +00002944 // Simplify mul instructions with a constant RHS...
Chris Lattnera2881962003-02-18 19:28:33 +00002945 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2946 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00002947
2948 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer832254e2007-02-02 02:16:23 +00002949 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnere92d2f42003-08-13 04:18:28 +00002950 if (SI->getOpcode() == Instruction::Shl)
2951 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattner48595f12004-06-10 02:07:29 +00002952 return BinaryOperator::createMul(SI->getOperand(0),
2953 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00002954
Chris Lattner515c97c2003-09-11 22:24:54 +00002955 if (CI->isNullValue())
2956 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2957 if (CI->equalsInt(1)) // X * 1 == X
2958 return ReplaceInstUsesWith(I, Op0);
2959 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner0af1fab2003-06-25 17:09:20 +00002960 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00002961
Reid Spencerb83eb642006-10-20 07:07:24 +00002962 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getZExtValue();
Chris Lattnerbcd7db52005-08-02 19:16:58 +00002963 if (isPowerOf2_64(Val)) { // Replace X*(2^C) with X << C
2964 uint64_t C = Log2_64(Val);
Reid Spencercc46cdb2007-02-02 14:08:20 +00002965 return BinaryOperator::createShl(Op0,
Reid Spencer832254e2007-02-02 02:16:23 +00002966 ConstantInt::get(Op0->getType(), C));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00002967 }
Robert Bocchino71698282004-07-27 21:02:21 +00002968 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattnera2881962003-02-18 19:28:33 +00002969 if (Op1F->isNullValue())
2970 return ReplaceInstUsesWith(I, Op1);
Chris Lattner6c1ce212002-04-29 22:24:47 +00002971
Chris Lattnera2881962003-02-18 19:28:33 +00002972 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2973 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2974 if (Op1F->getValue() == 1.0)
2975 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2976 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002977
2978 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2979 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2980 isa<ConstantInt>(Op0I->getOperand(1))) {
2981 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2982 Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
2983 Op1, "tmp");
2984 InsertNewInstBefore(Add, I);
2985 Value *C1C2 = ConstantExpr::getMul(Op1,
2986 cast<Constant>(Op0I->getOperand(1)));
2987 return BinaryOperator::createAdd(Add, C1C2);
2988
2989 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002990
2991 // Try to fold constant mul into select arguments.
2992 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002993 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002994 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002995
2996 if (isa<PHINode>(Op0))
2997 if (Instruction *NV = FoldOpIntoPhi(I))
2998 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002999 }
3000
Chris Lattnera4f445b2003-03-10 23:23:04 +00003001 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
3002 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattner48595f12004-06-10 02:07:29 +00003003 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00003004
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00003005 // If one of the operands of the multiply is a cast from a boolean value, then
3006 // we know the bool is either zero or one, so this is a 'masking' multiply.
3007 // See if we can simplify things based on how the boolean was originally
3008 // formed.
3009 CastInst *BoolCast = 0;
Reid Spencerc55b2432006-12-13 18:21:21 +00003010 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(0)))
Reid Spencer4fe16d62007-01-11 18:21:29 +00003011 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00003012 BoolCast = CI;
3013 if (!BoolCast)
Reid Spencerc55b2432006-12-13 18:21:21 +00003014 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
Reid Spencer4fe16d62007-01-11 18:21:29 +00003015 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00003016 BoolCast = CI;
3017 if (BoolCast) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003018 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00003019 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
3020 const Type *SCOpTy = SCIOp0->getType();
3021
Reid Spencere4d87aa2006-12-23 06:05:41 +00003022 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattner4cb170c2004-02-23 06:38:22 +00003023 // multiply into a shift/and combination.
3024 if (isa<ConstantInt>(SCIOp1) &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00003025 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1))) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00003026 // Shift the X value right to turn it into "all signbits".
Reid Spencer832254e2007-02-02 02:16:23 +00003027 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
Chris Lattner484d3cf2005-04-24 06:59:08 +00003028 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattner4cb170c2004-02-23 06:38:22 +00003029 Value *V =
Reid Spencer832254e2007-02-02 02:16:23 +00003030 InsertNewInstBefore(
3031 BinaryOperator::create(Instruction::AShr, SCIOp0, Amt,
Chris Lattner4cb170c2004-02-23 06:38:22 +00003032 BoolCast->getOperand(0)->getName()+
3033 ".mask"), I);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00003034
3035 // If the multiply type is not the same as the source type, sign extend
3036 // or truncate to the multiply type.
Reid Spencer17212df2006-12-12 09:18:51 +00003037 if (I.getType() != V->getType()) {
3038 unsigned SrcBits = V->getType()->getPrimitiveSizeInBits();
3039 unsigned DstBits = I.getType()->getPrimitiveSizeInBits();
3040 Instruction::CastOps opcode =
3041 (SrcBits == DstBits ? Instruction::BitCast :
3042 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
3043 V = InsertCastBefore(opcode, V, I.getType(), I);
3044 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003045
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00003046 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattner48595f12004-06-10 02:07:29 +00003047 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00003048 }
3049 }
3050 }
3051
Chris Lattner7e708292002-06-25 16:13:24 +00003052 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00003053}
3054
Reid Spencer1628cec2006-10-26 06:15:43 +00003055/// This function implements the transforms on div instructions that work
3056/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
3057/// used by the visitors to those instructions.
3058/// @brief Transforms common to all three div instructions
Reid Spencer3da59db2006-11-27 01:05:10 +00003059Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00003060 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00003061
Reid Spencer1628cec2006-10-26 06:15:43 +00003062 // undef / X -> 0
3063 if (isa<UndefValue>(Op0))
Chris Lattner857e8cd2004-12-12 21:48:58 +00003064 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Reid Spencer1628cec2006-10-26 06:15:43 +00003065
3066 // X / undef -> undef
Chris Lattner857e8cd2004-12-12 21:48:58 +00003067 if (isa<UndefValue>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00003068 return ReplaceInstUsesWith(I, Op1);
Chris Lattner857e8cd2004-12-12 21:48:58 +00003069
Reid Spencer1628cec2006-10-26 06:15:43 +00003070 // Handle cases involving: div X, (select Cond, Y, Z)
Chris Lattner8e49e082006-09-09 20:26:32 +00003071 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3072 // div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in the
Reid Spencer1628cec2006-10-26 06:15:43 +00003073 // same basic block, then we replace the select with Y, and the condition
3074 // of the select with false (if the cond value is in the same BB). If the
Chris Lattner8e49e082006-09-09 20:26:32 +00003075 // select has uses other than the div, this allows them to be simplified
Reid Spencer1628cec2006-10-26 06:15:43 +00003076 // also. Note that div X, Y is just as good as div X, 0 (undef)
Chris Lattner8e49e082006-09-09 20:26:32 +00003077 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
3078 if (ST->isNullValue()) {
3079 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3080 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003081 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Chris Lattner8e49e082006-09-09 20:26:32 +00003082 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3083 I.setOperand(1, SI->getOperand(2));
3084 else
3085 UpdateValueUsesWith(SI, SI->getOperand(2));
3086 return &I;
3087 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003088
Chris Lattner8e49e082006-09-09 20:26:32 +00003089 // Likewise for: div X, (Cond ? Y : 0) -> div X, Y
3090 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
3091 if (ST->isNullValue()) {
3092 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3093 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003094 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Chris Lattner8e49e082006-09-09 20:26:32 +00003095 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3096 I.setOperand(1, SI->getOperand(1));
3097 else
3098 UpdateValueUsesWith(SI, SI->getOperand(1));
3099 return &I;
3100 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003101 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003102
Reid Spencer1628cec2006-10-26 06:15:43 +00003103 return 0;
3104}
Misha Brukmanfd939082005-04-21 23:48:37 +00003105
Reid Spencer1628cec2006-10-26 06:15:43 +00003106/// This function implements the transforms common to both integer division
3107/// instructions (udiv and sdiv). It is called by the visitors to those integer
3108/// division instructions.
3109/// @brief Common integer divide transforms
Reid Spencer3da59db2006-11-27 01:05:10 +00003110Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003111 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3112
3113 if (Instruction *Common = commonDivTransforms(I))
3114 return Common;
3115
3116 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3117 // div X, 1 == X
3118 if (RHS->equalsInt(1))
3119 return ReplaceInstUsesWith(I, Op0);
3120
3121 // (X / C1) / C2 -> X / (C1*C2)
3122 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
3123 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
3124 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
3125 return BinaryOperator::create(I.getOpcode(), LHS->getOperand(0),
3126 ConstantExpr::getMul(RHS, LHSRHS));
Chris Lattnerbf70b832005-04-08 04:03:26 +00003127 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003128
3129 if (!RHS->isNullValue()) { // avoid X udiv 0
3130 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3131 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3132 return R;
3133 if (isa<PHINode>(Op0))
3134 if (Instruction *NV = FoldOpIntoPhi(I))
3135 return NV;
3136 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003137 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003138
Chris Lattnera2881962003-02-18 19:28:33 +00003139 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00003140 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00003141 if (LHS->equalsInt(0))
3142 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3143
Reid Spencer1628cec2006-10-26 06:15:43 +00003144 return 0;
3145}
3146
3147Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3148 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3149
3150 // Handle the integer div common cases
3151 if (Instruction *Common = commonIDivTransforms(I))
3152 return Common;
3153
3154 // X udiv C^2 -> X >> C
3155 // Check to see if this is an unsigned division with an exact power of 2,
3156 // if so, convert to a right shift.
3157 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
3158 if (uint64_t Val = C->getZExtValue()) // Don't break X / 0
3159 if (isPowerOf2_64(Val)) {
3160 uint64_t ShiftAmt = Log2_64(Val);
Reid Spencercc46cdb2007-02-02 14:08:20 +00003161 return BinaryOperator::createLShr(Op0,
Reid Spencer832254e2007-02-02 02:16:23 +00003162 ConstantInt::get(Op0->getType(), ShiftAmt));
Reid Spencer1628cec2006-10-26 06:15:43 +00003163 }
3164 }
3165
3166 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer832254e2007-02-02 02:16:23 +00003167 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003168 if (RHSI->getOpcode() == Instruction::Shl &&
3169 isa<ConstantInt>(RHSI->getOperand(0))) {
3170 uint64_t C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
3171 if (isPowerOf2_64(C1)) {
3172 Value *N = RHSI->getOperand(1);
Reid Spencer3da59db2006-11-27 01:05:10 +00003173 const Type *NTy = N->getType();
Reid Spencer1628cec2006-10-26 06:15:43 +00003174 if (uint64_t C2 = Log2_64(C1)) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003175 Constant *C2V = ConstantInt::get(NTy, C2);
3176 N = InsertNewInstBefore(BinaryOperator::createAdd(N, C2V, "tmp"), I);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003177 }
Reid Spencercc46cdb2007-02-02 14:08:20 +00003178 return BinaryOperator::createLShr(Op0, N);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003179 }
3180 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00003181 }
3182
Reid Spencer1628cec2006-10-26 06:15:43 +00003183 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3184 // where C1&C2 are powers of two.
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003185 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00003186 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003187 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3188 uint64_t TVA = STO->getZExtValue(), FVA = SFO->getZExtValue();
3189 if (isPowerOf2_64(TVA) && isPowerOf2_64(FVA)) {
3190 // Compute the shift amounts
3191 unsigned TSA = Log2_64(TVA), FSA = Log2_64(FVA);
3192 // Construct the "on true" case of the select
3193 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
3194 Instruction *TSI = BinaryOperator::createLShr(
3195 Op0, TC, SI->getName()+".t");
3196 TSI = InsertNewInstBefore(TSI, I);
3197
3198 // Construct the "on false" case of the select
3199 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
3200 Instruction *FSI = BinaryOperator::createLShr(
3201 Op0, FC, SI->getName()+".f");
3202 FSI = InsertNewInstBefore(FSI, I);
Reid Spencer1628cec2006-10-26 06:15:43 +00003203
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003204 // construct the select instruction and return it.
3205 return new SelectInst(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00003206 }
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003207 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00003208 return 0;
3209}
3210
Reid Spencer1628cec2006-10-26 06:15:43 +00003211Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3212 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3213
3214 // Handle the integer div common cases
3215 if (Instruction *Common = commonIDivTransforms(I))
3216 return Common;
3217
3218 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3219 // sdiv X, -1 == -X
3220 if (RHS->isAllOnesValue())
3221 return BinaryOperator::createNeg(Op0);
3222
3223 // -X/C -> X/-C
3224 if (Value *LHSNeg = dyn_castNegVal(Op0))
3225 return BinaryOperator::createSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
3226 }
3227
3228 // If the sign bits of both operands are zero (i.e. we can prove they are
3229 // unsigned inputs), turn this into a udiv.
Chris Lattner42a75512007-01-15 02:27:26 +00003230 if (I.getType()->isInteger()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003231 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
3232 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3233 return BinaryOperator::createUDiv(Op0, Op1, I.getName());
3234 }
3235 }
3236
3237 return 0;
3238}
3239
3240Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3241 return commonDivTransforms(I);
3242}
Chris Lattner3f5b8772002-05-06 16:14:14 +00003243
Chris Lattnerdb3f8732006-03-02 06:50:58 +00003244/// GetFactor - If we can prove that the specified value is at least a multiple
3245/// of some factor, return that factor.
3246static Constant *GetFactor(Value *V) {
3247 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
3248 return CI;
3249
3250 // Unless we can be tricky, we know this is a multiple of 1.
3251 Constant *Result = ConstantInt::get(V->getType(), 1);
3252
3253 Instruction *I = dyn_cast<Instruction>(V);
3254 if (!I) return Result;
3255
3256 if (I->getOpcode() == Instruction::Mul) {
3257 // Handle multiplies by a constant, etc.
3258 return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
3259 GetFactor(I->getOperand(1)));
3260 } else if (I->getOpcode() == Instruction::Shl) {
3261 // (X<<C) -> X * (1 << C)
3262 if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
3263 ShRHS = ConstantExpr::getShl(Result, ShRHS);
3264 return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
3265 }
3266 } else if (I->getOpcode() == Instruction::And) {
3267 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
3268 // X & 0xFFF0 is known to be a multiple of 16.
3269 unsigned Zeros = CountTrailingZeros_64(RHS->getZExtValue());
3270 if (Zeros != V->getType()->getPrimitiveSizeInBits())
3271 return ConstantExpr::getShl(Result,
Reid Spencer832254e2007-02-02 02:16:23 +00003272 ConstantInt::get(Result->getType(), Zeros));
Chris Lattnerdb3f8732006-03-02 06:50:58 +00003273 }
Reid Spencer3da59db2006-11-27 01:05:10 +00003274 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
Chris Lattnerdb3f8732006-03-02 06:50:58 +00003275 // Only handle int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00003276 if (!CI->isIntegerCast())
3277 return Result;
3278 Value *Op = CI->getOperand(0);
3279 return ConstantExpr::getCast(CI->getOpcode(), GetFactor(Op), V->getType());
Chris Lattnerdb3f8732006-03-02 06:50:58 +00003280 }
3281 return Result;
3282}
3283
Reid Spencer0a783f72006-11-02 01:53:59 +00003284/// This function implements the transforms on rem instructions that work
3285/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3286/// is used by the visitors to those instructions.
3287/// @brief Transforms common to all three rem instructions
3288Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00003289 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer0a783f72006-11-02 01:53:59 +00003290
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003291 // 0 % X == 0, we don't need to preserve faults!
3292 if (Constant *LHS = dyn_cast<Constant>(Op0))
3293 if (LHS->isNullValue())
3294 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3295
3296 if (isa<UndefValue>(Op0)) // undef % X -> 0
3297 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3298 if (isa<UndefValue>(Op1))
3299 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer0a783f72006-11-02 01:53:59 +00003300
3301 // Handle cases involving: rem X, (select Cond, Y, Z)
3302 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3303 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
3304 // the same basic block, then we replace the select with Y, and the
3305 // condition of the select with false (if the cond value is in the same
3306 // BB). If the select has uses other than the div, this allows them to be
3307 // simplified also.
3308 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
3309 if (ST->isNullValue()) {
3310 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3311 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003312 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Reid Spencer0a783f72006-11-02 01:53:59 +00003313 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3314 I.setOperand(1, SI->getOperand(2));
3315 else
3316 UpdateValueUsesWith(SI, SI->getOperand(2));
Chris Lattner5b73c082004-07-06 07:01:22 +00003317 return &I;
3318 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003319 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
3320 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
3321 if (ST->isNullValue()) {
3322 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3323 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003324 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Reid Spencer0a783f72006-11-02 01:53:59 +00003325 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3326 I.setOperand(1, SI->getOperand(1));
3327 else
3328 UpdateValueUsesWith(SI, SI->getOperand(1));
3329 return &I;
3330 }
Chris Lattner11a49f22005-11-05 07:28:37 +00003331 }
Chris Lattner5b73c082004-07-06 07:01:22 +00003332
Reid Spencer0a783f72006-11-02 01:53:59 +00003333 return 0;
3334}
3335
3336/// This function implements the transforms common to both integer remainder
3337/// instructions (urem and srem). It is called by the visitors to those integer
3338/// remainder instructions.
3339/// @brief Common integer remainder transforms
3340Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3341 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3342
3343 if (Instruction *common = commonRemTransforms(I))
3344 return common;
3345
Chris Lattner857e8cd2004-12-12 21:48:58 +00003346 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003347 // X % 0 == undef, we don't need to preserve faults!
3348 if (RHS->equalsInt(0))
3349 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3350
Chris Lattnera2881962003-02-18 19:28:33 +00003351 if (RHS->equalsInt(1)) // X % 1 == 0
3352 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3353
Chris Lattner97943922006-02-28 05:49:21 +00003354 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3355 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3356 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3357 return R;
3358 } else if (isa<PHINode>(Op0I)) {
3359 if (Instruction *NV = FoldOpIntoPhi(I))
3360 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00003361 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003362 // (X * C1) % C2 --> 0 iff C1 % C2 == 0
3363 if (ConstantExpr::getSRem(GetFactor(Op0I), RHS)->isNullValue())
Chris Lattnerdb3f8732006-03-02 06:50:58 +00003364 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner97943922006-02-28 05:49:21 +00003365 }
Chris Lattnera2881962003-02-18 19:28:33 +00003366 }
3367
Reid Spencer0a783f72006-11-02 01:53:59 +00003368 return 0;
3369}
3370
3371Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3372 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3373
3374 if (Instruction *common = commonIRemTransforms(I))
3375 return common;
3376
3377 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3378 // X urem C^2 -> X and C
3379 // Check to see if this is an unsigned remainder with an exact power of 2,
3380 // if so, convert to a bitwise and.
3381 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3382 if (isPowerOf2_64(C->getZExtValue()))
3383 return BinaryOperator::createAnd(Op0, SubOne(C));
3384 }
3385
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003386 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003387 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3388 if (RHSI->getOpcode() == Instruction::Shl &&
3389 isa<ConstantInt>(RHSI->getOperand(0))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00003390 unsigned C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003391 if (isPowerOf2_64(C1)) {
3392 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
3393 Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
3394 "tmp"), I);
3395 return BinaryOperator::createAnd(Op0, Add);
3396 }
3397 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003398 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003399
Reid Spencer0a783f72006-11-02 01:53:59 +00003400 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3401 // where C1&C2 are powers of two.
3402 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3403 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3404 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3405 // STO == 0 and SFO == 0 handled above.
3406 if (isPowerOf2_64(STO->getZExtValue()) &&
3407 isPowerOf2_64(SFO->getZExtValue())) {
3408 Value *TrueAnd = InsertNewInstBefore(
3409 BinaryOperator::createAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
3410 Value *FalseAnd = InsertNewInstBefore(
3411 BinaryOperator::createAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
3412 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
3413 }
3414 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003415 }
3416
Chris Lattner3f5b8772002-05-06 16:14:14 +00003417 return 0;
3418}
3419
Reid Spencer0a783f72006-11-02 01:53:59 +00003420Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3421 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3422
3423 if (Instruction *common = commonIRemTransforms(I))
3424 return common;
3425
3426 if (Value *RHSNeg = dyn_castNegVal(Op1))
3427 if (!isa<ConstantInt>(RHSNeg) ||
3428 cast<ConstantInt>(RHSNeg)->getSExtValue() > 0) {
3429 // X % -Y -> X % Y
3430 AddUsesToWorkList(I);
3431 I.setOperand(1, RHSNeg);
3432 return &I;
3433 }
3434
3435 // If the top bits of both operands are zero (i.e. we can prove they are
3436 // unsigned inputs), turn this into a urem.
3437 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
3438 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3439 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
3440 return BinaryOperator::createURem(Op0, Op1, I.getName());
3441 }
3442
3443 return 0;
3444}
3445
3446Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003447 return commonRemTransforms(I);
3448}
3449
Chris Lattner8b170942002-08-09 23:47:40 +00003450// isMaxValueMinusOne - return true if this is Max-1
Reid Spencere4d87aa2006-12-23 06:05:41 +00003451static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
Reid Spencer3a2a9fb2007-03-19 21:10:28 +00003452 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
Reid Spencere4d87aa2006-12-23 06:05:41 +00003453 if (isSigned) {
3454 // Calculate 0111111111..11111
Reid Spencer3a2a9fb2007-03-19 21:10:28 +00003455 APInt Val(APInt::getSignedMaxValue(TypeBits));
3456 return C->getValue() == Val-1;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003457 }
Reid Spencer3a2a9fb2007-03-19 21:10:28 +00003458 return C->getValue() == APInt::getAllOnesValue(TypeBits) - 1;
Chris Lattner8b170942002-08-09 23:47:40 +00003459}
3460
3461// isMinValuePlusOne - return true if this is Min+1
Reid Spencere4d87aa2006-12-23 06:05:41 +00003462static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
3463 if (isSigned) {
3464 // Calculate 1111111111000000000000
Reid Spencer727992c2007-03-19 21:08:07 +00003465 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
3466 APInt Val(APInt::getSignedMinValue(TypeBits));
3467 return C->getValue() == Val+1;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003468 }
Reid Spencer727992c2007-03-19 21:08:07 +00003469 return C->getValue() == 1; // unsigned
Chris Lattner8b170942002-08-09 23:47:40 +00003470}
3471
Chris Lattner457dd822004-06-09 07:59:58 +00003472// isOneBitSet - Return true if there is exactly one bit set in the specified
3473// constant.
3474static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer44e33e62007-03-19 21:04:43 +00003475 return CI->getValue().countPopulation() == 1;
Chris Lattner457dd822004-06-09 07:59:58 +00003476}
3477
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003478#if 0 // Currently unused
3479// isLowOnes - Return true if the constant is of the form 0+1+.
3480static bool isLowOnes(const ConstantInt *CI) {
Reid Spencerb83eb642006-10-20 07:07:24 +00003481 uint64_t V = CI->getZExtValue();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003482
3483 // There won't be bits set in parts that the type doesn't contain.
Reid Spencerb83eb642006-10-20 07:07:24 +00003484 V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003485
3486 uint64_t U = V+1; // If it is low ones, this should be a power of two.
3487 return U && V && (U & V) == 0;
3488}
3489#endif
3490
3491// isHighOnes - Return true if the constant is of the form 1+0+.
3492// This is the same as lowones(~X).
3493static bool isHighOnes(const ConstantInt *CI) {
Reid Spencerb83eb642006-10-20 07:07:24 +00003494 uint64_t V = ~CI->getZExtValue();
Chris Lattner2b83af22005-08-07 07:03:10 +00003495 if (~V == 0) return false; // 0's does not match "1+"
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003496
3497 // There won't be bits set in parts that the type doesn't contain.
Reid Spencerb83eb642006-10-20 07:07:24 +00003498 V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003499
3500 uint64_t U = V+1; // If it is low ones, this should be a power of two.
3501 return U && V && (U & V) == 0;
3502}
3503
Reid Spencere4d87aa2006-12-23 06:05:41 +00003504/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003505/// are carefully arranged to allow folding of expressions such as:
3506///
3507/// (A < B) | (A > B) --> (A != B)
3508///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003509/// Note that this is only valid if the first and second predicates have the
3510/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003511///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003512/// Three bits are used to represent the condition, as follows:
3513/// 0 A > B
3514/// 1 A == B
3515/// 2 A < B
3516///
3517/// <=> Value Definition
3518/// 000 0 Always false
3519/// 001 1 A > B
3520/// 010 2 A == B
3521/// 011 3 A >= B
3522/// 100 4 A < B
3523/// 101 5 A != B
3524/// 110 6 A <= B
3525/// 111 7 Always true
3526///
3527static unsigned getICmpCode(const ICmpInst *ICI) {
3528 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003529 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00003530 case ICmpInst::ICMP_UGT: return 1; // 001
3531 case ICmpInst::ICMP_SGT: return 1; // 001
3532 case ICmpInst::ICMP_EQ: return 2; // 010
3533 case ICmpInst::ICMP_UGE: return 3; // 011
3534 case ICmpInst::ICMP_SGE: return 3; // 011
3535 case ICmpInst::ICMP_ULT: return 4; // 100
3536 case ICmpInst::ICMP_SLT: return 4; // 100
3537 case ICmpInst::ICMP_NE: return 5; // 101
3538 case ICmpInst::ICMP_ULE: return 6; // 110
3539 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003540 // True -> 7
3541 default:
Reid Spencere4d87aa2006-12-23 06:05:41 +00003542 assert(0 && "Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003543 return 0;
3544 }
3545}
3546
Reid Spencere4d87aa2006-12-23 06:05:41 +00003547/// getICmpValue - This is the complement of getICmpCode, which turns an
3548/// opcode and two operands into either a constant true or false, or a brand
3549/// new /// ICmp instruction. The sign is passed in to determine which kind
3550/// of predicate to use in new icmp instructions.
3551static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3552 switch (code) {
3553 default: assert(0 && "Illegal ICmp code!");
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003554 case 0: return ConstantInt::getFalse();
Reid Spencere4d87aa2006-12-23 06:05:41 +00003555 case 1:
3556 if (sign)
3557 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3558 else
3559 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3560 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
3561 case 3:
3562 if (sign)
3563 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3564 else
3565 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3566 case 4:
3567 if (sign)
3568 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3569 else
3570 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3571 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
3572 case 6:
3573 if (sign)
3574 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3575 else
3576 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003577 case 7: return ConstantInt::getTrue();
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003578 }
3579}
3580
Reid Spencere4d87aa2006-12-23 06:05:41 +00003581static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3582 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3583 (ICmpInst::isSignedPredicate(p1) &&
3584 (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
3585 (ICmpInst::isSignedPredicate(p2) &&
3586 (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
3587}
3588
3589namespace {
3590// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3591struct FoldICmpLogical {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003592 InstCombiner &IC;
3593 Value *LHS, *RHS;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003594 ICmpInst::Predicate pred;
3595 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3596 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3597 pred(ICI->getPredicate()) {}
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003598 bool shouldApply(Value *V) const {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003599 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3600 if (PredicatesFoldable(pred, ICI->getPredicate()))
3601 return (ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS ||
3602 ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003603 return false;
3604 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003605 Instruction *apply(Instruction &Log) const {
3606 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3607 if (ICI->getOperand(0) != LHS) {
3608 assert(ICI->getOperand(1) == LHS);
3609 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003610 }
3611
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003612 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003613 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003614 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003615 unsigned Code;
3616 switch (Log.getOpcode()) {
3617 case Instruction::And: Code = LHSCode & RHSCode; break;
3618 case Instruction::Or: Code = LHSCode | RHSCode; break;
3619 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner021c1902003-09-22 20:33:34 +00003620 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003621 }
3622
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003623 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3624 ICmpInst::isSignedPredicate(ICI->getPredicate());
3625
3626 Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003627 if (Instruction *I = dyn_cast<Instruction>(RV))
3628 return I;
3629 // Otherwise, it's a constant boolean value...
3630 return IC.ReplaceInstUsesWith(Log, RV);
3631 }
3632};
Chris Lattnerd23b5ba2006-11-15 04:53:24 +00003633} // end anonymous namespace
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003634
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003635// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3636// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +00003637// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003638Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003639 ConstantInt *OpRHS,
3640 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003641 BinaryOperator &TheAnd) {
3642 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00003643 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +00003644 if (!Op->isShift())
Chris Lattner48595f12004-06-10 02:07:29 +00003645 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00003646
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003647 switch (Op->getOpcode()) {
3648 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003649 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003650 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Chris Lattner6934a042007-02-11 01:23:03 +00003651 Instruction *And = BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003652 InsertNewInstBefore(And, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003653 And->takeName(Op);
Chris Lattner48595f12004-06-10 02:07:29 +00003654 return BinaryOperator::createXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003655 }
3656 break;
3657 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003658 if (Together == AndRHS) // (X | C) & C --> C
3659 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003660
Chris Lattner6e7ba452005-01-01 16:22:27 +00003661 if (Op->hasOneUse() && Together != OpRHS) {
3662 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Chris Lattner6934a042007-02-11 01:23:03 +00003663 Instruction *Or = BinaryOperator::createOr(X, Together);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003664 InsertNewInstBefore(Or, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003665 Or->takeName(Op);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003666 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003667 }
3668 break;
3669 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00003670 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003671 // Adding a one to a single bit bit-field should be turned into an XOR
3672 // of the bit. First thing to check is to see if this AND is with a
3673 // single bit constant.
Reid Spencerb83eb642006-10-20 07:07:24 +00003674 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getZExtValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003675
3676 // Clear bits that are not part of the constant.
Reid Spencerc1030572007-01-19 21:13:56 +00003677 AndRHSV &= AndRHS->getType()->getBitMask();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003678
3679 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00003680 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003681 // Ok, at this point, we know that we are masking the result of the
3682 // ADD down to exactly one bit. If the constant we are adding has
3683 // no bits set below this bit, then we can eliminate the ADD.
Reid Spencerb83eb642006-10-20 07:07:24 +00003684 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getZExtValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00003685
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003686 // Check to see if any bits below the one bit set in AndRHSV are set.
3687 if ((AddRHS & (AndRHSV-1)) == 0) {
3688 // If not, the only thing that can effect the output of the AND is
3689 // the bit specified by AndRHSV. If that bit is set, the effect of
3690 // the XOR is to toggle the bit. If it is clear, then the ADD has
3691 // no effect.
3692 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3693 TheAnd.setOperand(0, X);
3694 return &TheAnd;
3695 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003696 // Pull the XOR out of the AND.
Chris Lattner6934a042007-02-11 01:23:03 +00003697 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003698 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003699 NewAnd->takeName(Op);
Chris Lattner48595f12004-06-10 02:07:29 +00003700 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003701 }
3702 }
3703 }
3704 }
3705 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00003706
3707 case Instruction::Shl: {
3708 // We know that the AND will not produce any of the bits shifted in, so if
3709 // the anded constant includes them, clear them now!
3710 //
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003711 Constant *AllOne = ConstantInt::getAllOnesValue(AndRHS->getType());
Chris Lattner0c967662004-09-24 15:21:34 +00003712 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
3713 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00003714
Chris Lattner0c967662004-09-24 15:21:34 +00003715 if (CI == ShlMask) { // Masking out bits that the shift already masks
3716 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3717 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00003718 TheAnd.setOperand(1, CI);
3719 return &TheAnd;
3720 }
3721 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00003722 }
Reid Spencer3822ff52006-11-08 06:47:33 +00003723 case Instruction::LShr:
3724 {
Chris Lattner62a355c2003-09-19 19:05:02 +00003725 // We know that the AND will not produce any of the bits shifted in, so if
3726 // the anded constant includes them, clear them now! This only applies to
3727 // unsigned shifts, because a signed shr may bring in set bits!
3728 //
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003729 Constant *AllOne = ConstantInt::getAllOnesValue(AndRHS->getType());
Reid Spencer3822ff52006-11-08 06:47:33 +00003730 Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
3731 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00003732
Reid Spencer3822ff52006-11-08 06:47:33 +00003733 if (CI == ShrMask) { // Masking out bits that the shift already masks.
3734 return ReplaceInstUsesWith(TheAnd, Op);
3735 } else if (CI != AndRHS) {
3736 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3737 return &TheAnd;
3738 }
3739 break;
3740 }
3741 case Instruction::AShr:
3742 // Signed shr.
3743 // See if this is shifting in some sign extension, then masking it out
3744 // with an and.
3745 if (Op->hasOneUse()) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003746 Constant *AllOne = ConstantInt::getAllOnesValue(AndRHS->getType());
Reid Spencer3822ff52006-11-08 06:47:33 +00003747 Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
Reid Spencer7eb76382006-12-13 17:19:09 +00003748 Constant *C = ConstantExpr::getAnd(AndRHS, ShrMask);
3749 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +00003750 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +00003751 // Make the argument unsigned.
3752 Value *ShVal = Op->getOperand(0);
Reid Spencer832254e2007-02-02 02:16:23 +00003753 ShVal = InsertNewInstBefore(
Reid Spencercc46cdb2007-02-02 14:08:20 +00003754 BinaryOperator::createLShr(ShVal, OpRHS,
Reid Spencer832254e2007-02-02 02:16:23 +00003755 Op->getName()), TheAnd);
Reid Spencer7eb76382006-12-13 17:19:09 +00003756 return BinaryOperator::createAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00003757 }
Chris Lattner62a355c2003-09-19 19:05:02 +00003758 }
3759 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003760 }
3761 return 0;
3762}
3763
Chris Lattner8b170942002-08-09 23:47:40 +00003764
Chris Lattnera96879a2004-09-29 17:40:11 +00003765/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3766/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +00003767/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3768/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +00003769/// insert new instructions.
3770Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003771 bool isSigned, bool Inside,
3772 Instruction &IB) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003773 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +00003774 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +00003775 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003776
Chris Lattnera96879a2004-09-29 17:40:11 +00003777 if (Inside) {
3778 if (Lo == Hi) // Trivially false.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003779 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +00003780
Reid Spencere4d87aa2006-12-23 06:05:41 +00003781 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003782 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003783 ICmpInst::Predicate pred = (isSigned ?
3784 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3785 return new ICmpInst(pred, V, Hi);
3786 }
3787
3788 // Emit V-Lo <u Hi-Lo
3789 Constant *NegLo = ConstantExpr::getNeg(Lo);
3790 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003791 InsertNewInstBefore(Add, IB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003792 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3793 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003794 }
3795
3796 if (Lo == Hi) // Trivially true.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003797 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +00003798
Reid Spencere4d87aa2006-12-23 06:05:41 +00003799 // V < Min || V >= Hi ->'V > Hi-1'
Chris Lattnera96879a2004-09-29 17:40:11 +00003800 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003801 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003802 ICmpInst::Predicate pred = (isSigned ?
3803 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3804 return new ICmpInst(pred, V, Hi);
3805 }
Reid Spencerb83eb642006-10-20 07:07:24 +00003806
Reid Spencere4d87aa2006-12-23 06:05:41 +00003807 // Emit V-Lo > Hi-1-Lo
3808 Constant *NegLo = ConstantExpr::getNeg(Lo);
3809 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003810 InsertNewInstBefore(Add, IB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003811 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3812 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003813}
3814
Chris Lattner7203e152005-09-18 07:22:02 +00003815// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3816// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3817// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3818// not, since all 1s are not contiguous.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003819static bool isRunOfOnes(ConstantInt *Val, unsigned &MB, unsigned &ME) {
Reid Spencerb83eb642006-10-20 07:07:24 +00003820 uint64_t V = Val->getZExtValue();
Chris Lattner7203e152005-09-18 07:22:02 +00003821 if (!isShiftedMask_64(V)) return false;
3822
3823 // look for the first zero bit after the run of ones
3824 MB = 64-CountLeadingZeros_64((V - 1) ^ V);
3825 // look for the first non-zero bit
3826 ME = 64-CountLeadingZeros_64(V);
3827 return true;
3828}
3829
3830
3831
3832/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3833/// where isSub determines whether the operator is a sub. If we can fold one of
3834/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00003835///
3836/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3837/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3838/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3839///
3840/// return (A +/- B).
3841///
3842Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003843 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +00003844 Instruction &I) {
3845 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3846 if (!LHSI || LHSI->getNumOperands() != 2 ||
3847 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3848
3849 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3850
3851 switch (LHSI->getOpcode()) {
3852 default: return 0;
3853 case Instruction::And:
Chris Lattner7203e152005-09-18 07:22:02 +00003854 if (ConstantExpr::getAnd(N, Mask) == Mask) {
3855 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Reid Spencerb83eb642006-10-20 07:07:24 +00003856 if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0)
Chris Lattner7203e152005-09-18 07:22:02 +00003857 break;
3858
3859 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3860 // part, we don't need any explicit masks to take them out of A. If that
3861 // is all N is, ignore it.
3862 unsigned MB, ME;
3863 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerc1030572007-01-19 21:13:56 +00003864 uint64_t Mask = cast<IntegerType>(RHS->getType())->getBitMask();
Chris Lattner3bedbd92006-02-07 07:27:52 +00003865 Mask >>= 64-MB+1;
3866 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00003867 break;
3868 }
3869 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00003870 return 0;
3871 case Instruction::Or:
3872 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00003873 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Reid Spencerb83eb642006-10-20 07:07:24 +00003874 if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0 &&
Chris Lattner7203e152005-09-18 07:22:02 +00003875 ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattnerc8e77562005-09-18 04:24:45 +00003876 break;
3877 return 0;
3878 }
3879
3880 Instruction *New;
3881 if (isSub)
3882 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
3883 else
3884 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
3885 return InsertNewInstBefore(New, I);
3886}
3887
Chris Lattner7e708292002-06-25 16:13:24 +00003888Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003889 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00003890 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003891
Chris Lattnere87597f2004-10-16 18:11:37 +00003892 if (isa<UndefValue>(Op1)) // X & undef -> 0
3893 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3894
Chris Lattner6e7ba452005-01-01 16:22:27 +00003895 // and X, X = X
3896 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00003897 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003898
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003899 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00003900 // purpose is to compute bits we don't care about.
Chris Lattner255d8912006-02-11 09:31:47 +00003901 uint64_t KnownZero, KnownOne;
Reid Spencer9d6565a2007-02-15 02:26:10 +00003902 if (!isa<VectorType>(I.getType())) {
Reid Spencerc1030572007-01-19 21:13:56 +00003903 if (SimplifyDemandedBits(&I, cast<IntegerType>(I.getType())->getBitMask(),
Chris Lattner696ee0a2007-01-18 22:16:33 +00003904 KnownZero, KnownOne))
Chris Lattner9ca96412006-02-08 03:25:32 +00003905 return &I;
Chris Lattner696ee0a2007-01-18 22:16:33 +00003906 } else {
Reid Spencer9d6565a2007-02-15 02:26:10 +00003907 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
Chris Lattner696ee0a2007-01-18 22:16:33 +00003908 if (CP->isAllOnesValue())
3909 return ReplaceInstUsesWith(I, I.getOperand(0));
3910 }
3911 }
Chris Lattner9ca96412006-02-08 03:25:32 +00003912
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003913 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner7560c3a2006-02-08 07:34:50 +00003914 uint64_t AndRHSMask = AndRHS->getZExtValue();
Reid Spencerc1030572007-01-19 21:13:56 +00003915 uint64_t TypeMask = cast<IntegerType>(Op0->getType())->getBitMask();
Chris Lattner7560c3a2006-02-08 07:34:50 +00003916 uint64_t NotAndRHS = AndRHSMask^TypeMask;
Chris Lattner6e7ba452005-01-01 16:22:27 +00003917
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003918 // Optimize a variety of ((val OP C1) & C2) combinations...
Reid Spencer832254e2007-02-02 02:16:23 +00003919 if (isa<BinaryOperator>(Op0)) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003920 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003921 Value *Op0LHS = Op0I->getOperand(0);
3922 Value *Op0RHS = Op0I->getOperand(1);
3923 switch (Op0I->getOpcode()) {
3924 case Instruction::Xor:
3925 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00003926 // If the mask is only needed on one incoming arm, push it up.
3927 if (Op0I->hasOneUse()) {
3928 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3929 // Not masking anything out for the LHS, move to RHS.
3930 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
3931 Op0RHS->getName()+".masked");
3932 InsertNewInstBefore(NewRHS, I);
3933 return BinaryOperator::create(
3934 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003935 }
Chris Lattner3bedbd92006-02-07 07:27:52 +00003936 if (!isa<Constant>(Op0RHS) &&
Chris Lattnerad1e3022005-01-23 20:26:55 +00003937 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3938 // Not masking anything out for the RHS, move to LHS.
3939 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
3940 Op0LHS->getName()+".masked");
3941 InsertNewInstBefore(NewLHS, I);
3942 return BinaryOperator::create(
3943 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3944 }
3945 }
3946
Chris Lattner6e7ba452005-01-01 16:22:27 +00003947 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00003948 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00003949 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3950 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3951 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3952 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3953 return BinaryOperator::createAnd(V, AndRHS);
3954 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3955 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00003956 break;
3957
3958 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00003959 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3960 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3961 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3962 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3963 return BinaryOperator::createAnd(V, AndRHS);
Chris Lattnerc8e77562005-09-18 04:24:45 +00003964 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00003965 }
3966
Chris Lattner58403262003-07-23 19:25:52 +00003967 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003968 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003969 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00003970 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00003971 // If this is an integer truncation or change from signed-to-unsigned, and
3972 // if the source is an and/or with immediate, transform it. This
3973 // frequently occurs for bitfield accesses.
3974 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00003975 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00003976 CastOp->getNumOperands() == 2)
Chris Lattner7560c3a2006-02-08 07:34:50 +00003977 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
Chris Lattner2b83af22005-08-07 07:03:10 +00003978 if (CastOp->getOpcode() == Instruction::And) {
3979 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00003980 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
3981 // This will fold the two constants together, which may allow
3982 // other simplifications.
Reid Spencerd977d862006-12-12 23:36:14 +00003983 Instruction *NewCast = CastInst::createTruncOrBitCast(
3984 CastOp->getOperand(0), I.getType(),
3985 CastOp->getName()+".shrunk");
Chris Lattner2b83af22005-08-07 07:03:10 +00003986 NewCast = InsertNewInstBefore(NewCast, I);
Reid Spencer3da59db2006-11-27 01:05:10 +00003987 // trunc_or_bitcast(C1)&C2
Reid Spencerd977d862006-12-12 23:36:14 +00003988 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00003989 C3 = ConstantExpr::getAnd(C3, AndRHS);
Chris Lattner2b83af22005-08-07 07:03:10 +00003990 return BinaryOperator::createAnd(NewCast, C3);
3991 } else if (CastOp->getOpcode() == Instruction::Or) {
3992 // Change: and (cast (or X, C1) to T), C2
3993 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattnerbb4e7b22006-12-12 19:11:20 +00003994 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Chris Lattner2b83af22005-08-07 07:03:10 +00003995 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3996 return ReplaceInstUsesWith(I, AndRHS);
3997 }
3998 }
Chris Lattner06782f82003-07-23 19:36:21 +00003999 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004000
4001 // Try to fold constant and into select arguments.
4002 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004003 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004004 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004005 if (isa<PHINode>(Op0))
4006 if (Instruction *NV = FoldOpIntoPhi(I))
4007 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00004008 }
4009
Chris Lattner8d969642003-03-10 23:06:50 +00004010 Value *Op0NotVal = dyn_castNotVal(Op0);
4011 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00004012
Chris Lattner5b62aa72004-06-18 06:07:51 +00004013 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
4014 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4015
Misha Brukmancb6267b2004-07-30 12:50:08 +00004016 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00004017 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattner48595f12004-06-10 02:07:29 +00004018 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
4019 I.getName()+".demorgan");
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00004020 InsertNewInstBefore(Or, I);
Chris Lattnera2881962003-02-18 19:28:33 +00004021 return BinaryOperator::createNot(Or);
4022 }
Chris Lattner2082ad92006-02-13 23:07:23 +00004023
4024 {
4025 Value *A = 0, *B = 0;
Chris Lattner2082ad92006-02-13 23:07:23 +00004026 if (match(Op0, m_Or(m_Value(A), m_Value(B))))
4027 if (A == Op1 || B == Op1) // (A | ?) & A --> A
4028 return ReplaceInstUsesWith(I, Op1);
4029 if (match(Op1, m_Or(m_Value(A), m_Value(B))))
4030 if (A == Op0 || B == Op0) // A & (A | ?) --> A
4031 return ReplaceInstUsesWith(I, Op0);
Chris Lattner64daab52006-04-01 08:03:55 +00004032
4033 if (Op0->hasOneUse() &&
4034 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
4035 if (A == Op1) { // (A^B)&A -> A&(A^B)
4036 I.swapOperands(); // Simplify below
4037 std::swap(Op0, Op1);
4038 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
4039 cast<BinaryOperator>(Op0)->swapOperands();
4040 I.swapOperands(); // Simplify below
4041 std::swap(Op0, Op1);
4042 }
4043 }
4044 if (Op1->hasOneUse() &&
4045 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
4046 if (B == Op0) { // B&(A^B) -> B&(B^A)
4047 cast<BinaryOperator>(Op1)->swapOperands();
4048 std::swap(A, B);
4049 }
4050 if (A == Op0) { // A&(A^B) -> A & ~B
4051 Instruction *NotB = BinaryOperator::createNot(B, "tmp");
4052 InsertNewInstBefore(NotB, I);
4053 return BinaryOperator::createAnd(A, NotB);
4054 }
4055 }
Chris Lattner2082ad92006-02-13 23:07:23 +00004056 }
4057
Reid Spencere4d87aa2006-12-23 06:05:41 +00004058 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4059 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
4060 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004061 return R;
4062
Chris Lattner955f3312004-09-28 21:48:02 +00004063 Value *LHSVal, *RHSVal;
4064 ConstantInt *LHSCst, *RHSCst;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004065 ICmpInst::Predicate LHSCC, RHSCC;
4066 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
4067 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
4068 if (LHSVal == RHSVal && // Found (X icmp C1) & (X icmp C2)
4069 // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
4070 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
4071 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
4072 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
4073 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE) {
Chris Lattner955f3312004-09-28 21:48:02 +00004074 // Ensure that the larger constant is on the RHS.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004075 ICmpInst::Predicate GT = ICmpInst::isSignedPredicate(LHSCC) ?
4076 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
4077 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
4078 ICmpInst *LHS = cast<ICmpInst>(Op0);
Reid Spencer579dca12007-01-12 04:24:46 +00004079 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
Chris Lattner955f3312004-09-28 21:48:02 +00004080 std::swap(LHS, RHS);
4081 std::swap(LHSCst, RHSCst);
4082 std::swap(LHSCC, RHSCC);
4083 }
4084
Reid Spencere4d87aa2006-12-23 06:05:41 +00004085 // At this point, we know we have have two icmp instructions
Chris Lattner955f3312004-09-28 21:48:02 +00004086 // comparing a value against two constants and and'ing the result
4087 // together. Because of the above check, we know that we only have
Reid Spencere4d87aa2006-12-23 06:05:41 +00004088 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
4089 // (from the FoldICmpLogical check above), that the two constants
4090 // are not equal and that the larger constant is on the RHS
Chris Lattner955f3312004-09-28 21:48:02 +00004091 assert(LHSCst != RHSCst && "Compares not folded above?");
4092
4093 switch (LHSCC) {
4094 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004095 case ICmpInst::ICMP_EQ:
Chris Lattner955f3312004-09-28 21:48:02 +00004096 switch (RHSCC) {
4097 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004098 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
4099 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
4100 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004101 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004102 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
4103 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
4104 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
Chris Lattner955f3312004-09-28 21:48:02 +00004105 return ReplaceInstUsesWith(I, LHS);
4106 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004107 case ICmpInst::ICMP_NE:
Chris Lattner955f3312004-09-28 21:48:02 +00004108 switch (RHSCC) {
4109 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004110 case ICmpInst::ICMP_ULT:
4111 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
4112 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
4113 break; // (X != 13 & X u< 15) -> no change
4114 case ICmpInst::ICMP_SLT:
4115 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
4116 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
4117 break; // (X != 13 & X s< 15) -> no change
4118 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
4119 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
4120 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
Chris Lattner955f3312004-09-28 21:48:02 +00004121 return ReplaceInstUsesWith(I, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004122 case ICmpInst::ICMP_NE:
4123 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Chris Lattner955f3312004-09-28 21:48:02 +00004124 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4125 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
4126 LHSVal->getName()+".off");
4127 InsertNewInstBefore(Add, I);
Chris Lattner424db022007-01-27 23:08:34 +00004128 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
4129 ConstantInt::get(Add->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +00004130 }
4131 break; // (X != 13 & X != 15) -> no change
4132 }
4133 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004134 case ICmpInst::ICMP_ULT:
Chris Lattner955f3312004-09-28 21:48:02 +00004135 switch (RHSCC) {
4136 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004137 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
4138 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004139 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004140 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
4141 break;
4142 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
4143 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
Chris Lattner955f3312004-09-28 21:48:02 +00004144 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004145 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
4146 break;
Chris Lattner955f3312004-09-28 21:48:02 +00004147 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004148 break;
4149 case ICmpInst::ICMP_SLT:
Chris Lattner955f3312004-09-28 21:48:02 +00004150 switch (RHSCC) {
4151 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004152 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
4153 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004154 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004155 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
4156 break;
4157 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
4158 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
Chris Lattner955f3312004-09-28 21:48:02 +00004159 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004160 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
4161 break;
Chris Lattner955f3312004-09-28 21:48:02 +00004162 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004163 break;
4164 case ICmpInst::ICMP_UGT:
4165 switch (RHSCC) {
4166 default: assert(0 && "Unknown integer condition code!");
4167 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X > 13
4168 return ReplaceInstUsesWith(I, LHS);
4169 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
4170 return ReplaceInstUsesWith(I, RHS);
4171 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
4172 break;
4173 case ICmpInst::ICMP_NE:
4174 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
4175 return new ICmpInst(LHSCC, LHSVal, RHSCst);
4176 break; // (X u> 13 & X != 15) -> no change
4177 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) ->(X-14) <u 1
4178 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false,
4179 true, I);
4180 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
4181 break;
4182 }
4183 break;
4184 case ICmpInst::ICMP_SGT:
4185 switch (RHSCC) {
4186 default: assert(0 && "Unknown integer condition code!");
4187 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X s> 13
4188 return ReplaceInstUsesWith(I, LHS);
4189 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
4190 return ReplaceInstUsesWith(I, RHS);
4191 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
4192 break;
4193 case ICmpInst::ICMP_NE:
4194 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
4195 return new ICmpInst(LHSCC, LHSVal, RHSCst);
4196 break; // (X s> 13 & X != 15) -> no change
4197 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) ->(X-14) s< 1
4198 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true,
4199 true, I);
4200 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
4201 break;
4202 }
4203 break;
Chris Lattner955f3312004-09-28 21:48:02 +00004204 }
4205 }
4206 }
4207
Chris Lattner6fc205f2006-05-05 06:39:07 +00004208 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004209 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4210 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4211 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4212 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00004213 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004214 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004215 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4216 I.getType(), TD) &&
4217 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4218 I.getType(), TD)) {
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004219 Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
4220 Op1C->getOperand(0),
4221 I.getName());
4222 InsertNewInstBefore(NewOp, I);
4223 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4224 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004225 }
Chris Lattnere511b742006-11-14 07:46:50 +00004226
4227 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004228 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4229 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4230 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004231 SI0->getOperand(1) == SI1->getOperand(1) &&
4232 (SI0->hasOneUse() || SI1->hasOneUse())) {
4233 Instruction *NewOp =
4234 InsertNewInstBefore(BinaryOperator::createAnd(SI0->getOperand(0),
4235 SI1->getOperand(0),
4236 SI0->getName()), I);
Reid Spencer832254e2007-02-02 02:16:23 +00004237 return BinaryOperator::create(SI1->getOpcode(), NewOp,
4238 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004239 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004240 }
4241
Chris Lattner7e708292002-06-25 16:13:24 +00004242 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004243}
4244
Chris Lattnerafe91a52006-06-15 19:07:26 +00004245/// CollectBSwapParts - Look to see if the specified value defines a single byte
4246/// in the result. If it does, and if the specified byte hasn't been filled in
4247/// yet, fill it in and return false.
Chris Lattner535014f2007-02-15 22:52:10 +00004248static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00004249 Instruction *I = dyn_cast<Instruction>(V);
4250 if (I == 0) return true;
4251
4252 // If this is an or instruction, it is an inner node of the bswap.
4253 if (I->getOpcode() == Instruction::Or)
4254 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
4255 CollectBSwapParts(I->getOperand(1), ByteValues);
4256
4257 // If this is a shift by a constant int, and it is "24", then its operand
4258 // defines a byte. We only handle unsigned types here.
Reid Spencer832254e2007-02-02 02:16:23 +00004259 if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00004260 // Not shifting the entire input by N-1 bytes?
Reid Spencerb83eb642006-10-20 07:07:24 +00004261 if (cast<ConstantInt>(I->getOperand(1))->getZExtValue() !=
Chris Lattnerafe91a52006-06-15 19:07:26 +00004262 8*(ByteValues.size()-1))
4263 return true;
4264
4265 unsigned DestNo;
4266 if (I->getOpcode() == Instruction::Shl) {
4267 // X << 24 defines the top byte with the lowest of the input bytes.
4268 DestNo = ByteValues.size()-1;
4269 } else {
4270 // X >>u 24 defines the low byte with the highest of the input bytes.
4271 DestNo = 0;
4272 }
4273
4274 // If the destination byte value is already defined, the values are or'd
4275 // together, which isn't a bswap (unless it's an or of the same bits).
4276 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
4277 return true;
4278 ByteValues[DestNo] = I->getOperand(0);
4279 return false;
4280 }
4281
4282 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
4283 // don't have this.
4284 Value *Shift = 0, *ShiftLHS = 0;
4285 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
4286 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
4287 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
4288 return true;
4289 Instruction *SI = cast<Instruction>(Shift);
4290
4291 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
Reid Spencerb83eb642006-10-20 07:07:24 +00004292 if (ShiftAmt->getZExtValue() & 7 ||
4293 ShiftAmt->getZExtValue() > 8*ByteValues.size())
Chris Lattnerafe91a52006-06-15 19:07:26 +00004294 return true;
4295
4296 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
4297 unsigned DestByte;
4298 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
Reid Spencerb83eb642006-10-20 07:07:24 +00004299 if (AndAmt->getZExtValue() == uint64_t(0xFF) << 8*DestByte)
Chris Lattnerafe91a52006-06-15 19:07:26 +00004300 break;
4301 // Unknown mask for bswap.
4302 if (DestByte == ByteValues.size()) return true;
4303
Reid Spencerb83eb642006-10-20 07:07:24 +00004304 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
Chris Lattnerafe91a52006-06-15 19:07:26 +00004305 unsigned SrcByte;
4306 if (SI->getOpcode() == Instruction::Shl)
4307 SrcByte = DestByte - ShiftBytes;
4308 else
4309 SrcByte = DestByte + ShiftBytes;
4310
4311 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
4312 if (SrcByte != ByteValues.size()-DestByte-1)
4313 return true;
4314
4315 // If the destination byte value is already defined, the values are or'd
4316 // together, which isn't a bswap (unless it's an or of the same bits).
4317 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
4318 return true;
4319 ByteValues[DestByte] = SI->getOperand(0);
4320 return false;
4321}
4322
4323/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4324/// If so, insert the new bswap intrinsic and return it.
4325Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Reid Spencer832254e2007-02-02 02:16:23 +00004326 // We cannot bswap one byte.
Reid Spencerc5b206b2006-12-31 05:48:39 +00004327 if (I.getType() == Type::Int8Ty)
Chris Lattnerafe91a52006-06-15 19:07:26 +00004328 return 0;
4329
4330 /// ByteValues - For each byte of the result, we keep track of which value
4331 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00004332 SmallVector<Value*, 8> ByteValues;
Reid Spencera54b7cb2007-01-12 07:05:14 +00004333 ByteValues.resize(TD->getTypeSize(I.getType()));
Chris Lattnerafe91a52006-06-15 19:07:26 +00004334
4335 // Try to find all the pieces corresponding to the bswap.
4336 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
4337 CollectBSwapParts(I.getOperand(1), ByteValues))
4338 return 0;
4339
4340 // Check to see if all of the bytes come from the same value.
4341 Value *V = ByteValues[0];
4342 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4343
4344 // Check to make sure that all of the bytes come from the same value.
4345 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4346 if (ByteValues[i] != V)
4347 return 0;
4348
4349 // If they do then *success* we can turn this into a bswap. Figure out what
4350 // bswap to make it into.
4351 Module *M = I.getParent()->getParent()->getParent();
Chris Lattnered36b2f2006-07-11 18:31:26 +00004352 const char *FnName = 0;
Reid Spencerc5b206b2006-12-31 05:48:39 +00004353 if (I.getType() == Type::Int16Ty)
Chris Lattnerafe91a52006-06-15 19:07:26 +00004354 FnName = "llvm.bswap.i16";
Reid Spencerc5b206b2006-12-31 05:48:39 +00004355 else if (I.getType() == Type::Int32Ty)
Chris Lattnerafe91a52006-06-15 19:07:26 +00004356 FnName = "llvm.bswap.i32";
Reid Spencerc5b206b2006-12-31 05:48:39 +00004357 else if (I.getType() == Type::Int64Ty)
Chris Lattnerafe91a52006-06-15 19:07:26 +00004358 FnName = "llvm.bswap.i64";
4359 else
4360 assert(0 && "Unknown integer type!");
Chris Lattner92141962007-01-07 06:58:05 +00004361 Constant *F = M->getOrInsertFunction(FnName, I.getType(), I.getType(), NULL);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004362 return new CallInst(F, V);
4363}
4364
4365
Chris Lattner7e708292002-06-25 16:13:24 +00004366Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004367 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004368 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004369
Chris Lattnere87597f2004-10-16 18:11:37 +00004370 if (isa<UndefValue>(Op1))
4371 return ReplaceInstUsesWith(I, // X | undef -> -1
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004372 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004373
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004374 // or X, X = X
4375 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00004376 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004377
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004378 // See if we can simplify any instructions used by the instruction whose sole
4379 // purpose is to compute bits we don't care about.
4380 uint64_t KnownZero, KnownOne;
Reid Spencer9d6565a2007-02-15 02:26:10 +00004381 if (!isa<VectorType>(I.getType()) &&
Reid Spencerc1030572007-01-19 21:13:56 +00004382 SimplifyDemandedBits(&I, cast<IntegerType>(I.getType())->getBitMask(),
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004383 KnownZero, KnownOne))
4384 return &I;
4385
Chris Lattner3f5b8772002-05-06 16:14:14 +00004386 // or X, -1 == -1
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004387 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00004388 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004389 // (X & C1) | C2 --> (X | C2) & (C1|C2)
4390 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattner6934a042007-02-11 01:23:03 +00004391 Instruction *Or = BinaryOperator::createOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004392 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00004393 Or->takeName(Op0);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004394 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
4395 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004396
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004397 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4398 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattner6934a042007-02-11 01:23:03 +00004399 Instruction *Or = BinaryOperator::createOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004400 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00004401 Or->takeName(Op0);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004402 return BinaryOperator::createXor(Or,
4403 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004404 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004405
4406 // Try to fold constant and into select arguments.
4407 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004408 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004409 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004410 if (isa<PHINode>(Op0))
4411 if (Instruction *NV = FoldOpIntoPhi(I))
4412 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004413 }
4414
Chris Lattner4f637d42006-01-06 17:59:59 +00004415 Value *A = 0, *B = 0;
4416 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004417
4418 if (match(Op0, m_And(m_Value(A), m_Value(B))))
4419 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4420 return ReplaceInstUsesWith(I, Op1);
4421 if (match(Op1, m_And(m_Value(A), m_Value(B))))
4422 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4423 return ReplaceInstUsesWith(I, Op0);
4424
Chris Lattner6423d4c2006-07-10 20:25:24 +00004425 // (A | B) | C and A | (B | C) -> bswap if possible.
4426 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004427 if (match(Op0, m_Or(m_Value(), m_Value())) ||
Chris Lattner6423d4c2006-07-10 20:25:24 +00004428 match(Op1, m_Or(m_Value(), m_Value())) ||
4429 (match(Op0, m_Shift(m_Value(), m_Value())) &&
4430 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00004431 if (Instruction *BSwap = MatchBSwap(I))
4432 return BSwap;
4433 }
4434
Chris Lattner6e4c6492005-05-09 04:58:36 +00004435 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4436 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattner3bedbd92006-02-07 07:27:52 +00004437 MaskedValueIsZero(Op1, C1->getZExtValue())) {
Chris Lattner6934a042007-02-11 01:23:03 +00004438 Instruction *NOr = BinaryOperator::createOr(A, Op1);
4439 InsertNewInstBefore(NOr, I);
4440 NOr->takeName(Op0);
4441 return BinaryOperator::createXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004442 }
4443
4444 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4445 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattner3bedbd92006-02-07 07:27:52 +00004446 MaskedValueIsZero(Op0, C1->getZExtValue())) {
Chris Lattner6934a042007-02-11 01:23:03 +00004447 Instruction *NOr = BinaryOperator::createOr(A, Op0);
4448 InsertNewInstBefore(NOr, I);
4449 NOr->takeName(Op0);
4450 return BinaryOperator::createXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004451 }
4452
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004453 // (A & C1)|(B & C2)
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004454 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004455 match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
4456
4457 if (A == B) // (A & C1)|(A & C2) == A & (C1|C2)
4458 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
4459
4460
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00004461 // If we have: ((V + N) & C1) | (V & C2)
4462 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4463 // replace with V+N.
4464 if (C1 == ConstantExpr::getNot(C2)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00004465 Value *V1 = 0, *V2 = 0;
Reid Spencerb83eb642006-10-20 07:07:24 +00004466 if ((C2->getZExtValue() & (C2->getZExtValue()+1)) == 0 && // C2 == 0+1+
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00004467 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4468 // Add commutes, try both ways.
Chris Lattner3bedbd92006-02-07 07:27:52 +00004469 if (V1 == B && MaskedValueIsZero(V2, C2->getZExtValue()))
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00004470 return ReplaceInstUsesWith(I, A);
Chris Lattner3bedbd92006-02-07 07:27:52 +00004471 if (V2 == B && MaskedValueIsZero(V1, C2->getZExtValue()))
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00004472 return ReplaceInstUsesWith(I, A);
4473 }
4474 // Or commutes, try both ways.
Reid Spencerb83eb642006-10-20 07:07:24 +00004475 if ((C1->getZExtValue() & (C1->getZExtValue()+1)) == 0 &&
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00004476 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4477 // Add commutes, try both ways.
Chris Lattner3bedbd92006-02-07 07:27:52 +00004478 if (V1 == A && MaskedValueIsZero(V2, C1->getZExtValue()))
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00004479 return ReplaceInstUsesWith(I, B);
Chris Lattner3bedbd92006-02-07 07:27:52 +00004480 if (V2 == A && MaskedValueIsZero(V1, C1->getZExtValue()))
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00004481 return ReplaceInstUsesWith(I, B);
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004482 }
4483 }
4484 }
Chris Lattnere511b742006-11-14 07:46:50 +00004485
4486 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004487 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4488 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4489 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004490 SI0->getOperand(1) == SI1->getOperand(1) &&
4491 (SI0->hasOneUse() || SI1->hasOneUse())) {
4492 Instruction *NewOp =
4493 InsertNewInstBefore(BinaryOperator::createOr(SI0->getOperand(0),
4494 SI1->getOperand(0),
4495 SI0->getName()), I);
Reid Spencer832254e2007-02-02 02:16:23 +00004496 return BinaryOperator::create(SI1->getOpcode(), NewOp,
4497 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004498 }
4499 }
Chris Lattner67ca7682003-08-12 19:11:07 +00004500
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004501 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
4502 if (A == Op1) // ~A | A == -1
Misha Brukmanfd939082005-04-21 23:48:37 +00004503 return ReplaceInstUsesWith(I,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004504 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004505 } else {
4506 A = 0;
4507 }
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004508 // Note, A is still live here!
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004509 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
4510 if (Op0 == B)
Misha Brukmanfd939082005-04-21 23:48:37 +00004511 return ReplaceInstUsesWith(I,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004512 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattnera27231a2003-03-10 23:13:59 +00004513
Misha Brukmancb6267b2004-07-30 12:50:08 +00004514 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004515 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4516 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
4517 I.getName()+".demorgan"), I);
4518 return BinaryOperator::createNot(And);
4519 }
Chris Lattnera27231a2003-03-10 23:13:59 +00004520 }
Chris Lattnera2881962003-02-18 19:28:33 +00004521
Reid Spencere4d87aa2006-12-23 06:05:41 +00004522 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4523 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4524 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004525 return R;
4526
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004527 Value *LHSVal, *RHSVal;
4528 ConstantInt *LHSCst, *RHSCst;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004529 ICmpInst::Predicate LHSCC, RHSCC;
4530 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
4531 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
4532 if (LHSVal == RHSVal && // Found (X icmp C1) | (X icmp C2)
4533 // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
4534 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
4535 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
4536 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
4537 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE) {
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004538 // Ensure that the larger constant is on the RHS.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004539 ICmpInst::Predicate GT = ICmpInst::isSignedPredicate(LHSCC) ?
4540 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
4541 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
4542 ICmpInst *LHS = cast<ICmpInst>(Op0);
Reid Spencer579dca12007-01-12 04:24:46 +00004543 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004544 std::swap(LHS, RHS);
4545 std::swap(LHSCst, RHSCst);
4546 std::swap(LHSCC, RHSCC);
4547 }
4548
Reid Spencere4d87aa2006-12-23 06:05:41 +00004549 // At this point, we know we have have two icmp instructions
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004550 // comparing a value against two constants and or'ing the result
4551 // together. Because of the above check, we know that we only have
Reid Spencere4d87aa2006-12-23 06:05:41 +00004552 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4553 // FoldICmpLogical check above), that the two constants are not
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004554 // equal.
4555 assert(LHSCst != RHSCst && "Compares not folded above?");
4556
4557 switch (LHSCC) {
4558 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004559 case ICmpInst::ICMP_EQ:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004560 switch (RHSCC) {
4561 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004562 case ICmpInst::ICMP_EQ:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004563 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
4564 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4565 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
4566 LHSVal->getName()+".off");
4567 InsertNewInstBefore(Add, I);
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004568 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004569 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004570 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004571 break; // (X == 13 | X == 15) -> no change
4572 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4573 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
Chris Lattner240d6f42005-04-19 06:04:18 +00004574 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004575 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4576 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4577 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004578 return ReplaceInstUsesWith(I, RHS);
4579 }
4580 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004581 case ICmpInst::ICMP_NE:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004582 switch (RHSCC) {
4583 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004584 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4585 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4586 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004587 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004588 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4589 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4590 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004591 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004592 }
4593 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004594 case ICmpInst::ICMP_ULT:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004595 switch (RHSCC) {
4596 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004597 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004598 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004599 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) ->(X-13) u> 2
4600 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false,
4601 false, I);
4602 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4603 break;
4604 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4605 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004606 return ReplaceInstUsesWith(I, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004607 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4608 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004609 }
4610 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004611 case ICmpInst::ICMP_SLT:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004612 switch (RHSCC) {
4613 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004614 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4615 break;
4616 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) ->(X-13) s> 2
4617 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true,
4618 false, I);
4619 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4620 break;
4621 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4622 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4623 return ReplaceInstUsesWith(I, RHS);
4624 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4625 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004626 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004627 break;
4628 case ICmpInst::ICMP_UGT:
4629 switch (RHSCC) {
4630 default: assert(0 && "Unknown integer condition code!");
4631 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4632 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4633 return ReplaceInstUsesWith(I, LHS);
4634 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4635 break;
4636 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4637 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004638 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004639 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4640 break;
4641 }
4642 break;
4643 case ICmpInst::ICMP_SGT:
4644 switch (RHSCC) {
4645 default: assert(0 && "Unknown integer condition code!");
4646 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4647 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4648 return ReplaceInstUsesWith(I, LHS);
4649 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4650 break;
4651 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4652 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004653 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004654 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4655 break;
4656 }
4657 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004658 }
4659 }
4660 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004661
4662 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004663 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
Chris Lattner6fc205f2006-05-05 06:39:07 +00004664 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004665 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4666 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00004667 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004668 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004669 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4670 I.getType(), TD) &&
4671 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4672 I.getType(), TD)) {
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004673 Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
4674 Op1C->getOperand(0),
4675 I.getName());
4676 InsertNewInstBefore(NewOp, I);
4677 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4678 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004679 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004680
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004681
Chris Lattner7e708292002-06-25 16:13:24 +00004682 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004683}
4684
Chris Lattnerc317d392004-02-16 01:20:27 +00004685// XorSelf - Implements: X ^ X --> 0
4686struct XorSelf {
4687 Value *RHS;
4688 XorSelf(Value *rhs) : RHS(rhs) {}
4689 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4690 Instruction *apply(BinaryOperator &Xor) const {
4691 return &Xor;
4692 }
4693};
Chris Lattner3f5b8772002-05-06 16:14:14 +00004694
4695
Chris Lattner7e708292002-06-25 16:13:24 +00004696Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004697 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004698 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004699
Chris Lattnere87597f2004-10-16 18:11:37 +00004700 if (isa<UndefValue>(Op1))
4701 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
4702
Chris Lattnerc317d392004-02-16 01:20:27 +00004703 // xor X, X = 0, even if X is nested in a sequence of Xor's.
4704 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
4705 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattner233f7dc2002-08-12 21:17:25 +00004706 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00004707 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004708
4709 // See if we can simplify any instructions used by the instruction whose sole
4710 // purpose is to compute bits we don't care about.
4711 uint64_t KnownZero, KnownOne;
Reid Spencer9d6565a2007-02-15 02:26:10 +00004712 if (!isa<VectorType>(I.getType()) &&
Reid Spencerc1030572007-01-19 21:13:56 +00004713 SimplifyDemandedBits(&I, cast<IntegerType>(I.getType())->getBitMask(),
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004714 KnownZero, KnownOne))
4715 return &I;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004716
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004717 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00004718 // xor (icmp A, B), true = not (icmp A, B) = !icmp A, B
4719 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004720 if (RHS == ConstantInt::getTrue() && ICI->hasOneUse())
Reid Spencere4d87aa2006-12-23 06:05:41 +00004721 return new ICmpInst(ICI->getInversePredicate(),
4722 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00004723
Reid Spencere4d87aa2006-12-23 06:05:41 +00004724 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00004725 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00004726 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4727 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattner48595f12004-06-10 02:07:29 +00004728 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4729 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattner7c4049c2004-01-12 19:35:11 +00004730 ConstantInt::get(I.getType(), 1));
Chris Lattner48595f12004-06-10 02:07:29 +00004731 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00004732 }
Chris Lattner5b62aa72004-06-18 06:07:51 +00004733
4734 // ~(~X & Y) --> (X | ~Y)
4735 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
4736 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4737 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4738 Instruction *NotY =
Misha Brukmanfd939082005-04-21 23:48:37 +00004739 BinaryOperator::createNot(Op0I->getOperand(1),
Chris Lattner5b62aa72004-06-18 06:07:51 +00004740 Op0I->getOperand(1)->getName()+".not");
4741 InsertNewInstBefore(NotY, I);
4742 return BinaryOperator::createOr(Op0NotVal, NotY);
4743 }
4744 }
Misha Brukmanfd939082005-04-21 23:48:37 +00004745
Chris Lattnereca0c5c2003-07-23 21:37:07 +00004746 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004747 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00004748 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00004749 if (RHS->isAllOnesValue()) {
Chris Lattner48595f12004-06-10 02:07:29 +00004750 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
4751 return BinaryOperator::createSub(
4752 ConstantExpr::getSub(NegOp0CI,
Chris Lattner7c4049c2004-01-12 19:35:11 +00004753 ConstantInt::get(I.getType(), 1)),
Chris Lattner689d24b2003-11-04 23:37:10 +00004754 Op0I->getOperand(0));
Chris Lattner7c4049c2004-01-12 19:35:11 +00004755 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00004756 } else if (Op0I->getOpcode() == Instruction::Or) {
4757 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
4758 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getZExtValue())) {
4759 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4760 // Anything in both C1 and C2 is known to be zero, remove it from
4761 // NewRHS.
4762 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
4763 NewRHS = ConstantExpr::getAnd(NewRHS,
4764 ConstantExpr::getNot(CommonBits));
Chris Lattnerdbab3862007-03-02 21:28:56 +00004765 AddToWorkList(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00004766 I.setOperand(0, Op0I->getOperand(0));
4767 I.setOperand(1, NewRHS);
4768 return &I;
4769 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00004770 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00004771 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004772
4773 // Try to fold constant and into select arguments.
4774 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004775 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004776 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004777 if (isa<PHINode>(Op0))
4778 if (Instruction *NV = FoldOpIntoPhi(I))
4779 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004780 }
4781
Chris Lattner8d969642003-03-10 23:06:50 +00004782 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00004783 if (X == Op1)
4784 return ReplaceInstUsesWith(I,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004785 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00004786
Chris Lattner8d969642003-03-10 23:06:50 +00004787 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00004788 if (X == Op0)
Chris Lattner318bf792007-03-18 22:51:34 +00004789 return ReplaceInstUsesWith(I, ConstantInt::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00004790
Chris Lattner318bf792007-03-18 22:51:34 +00004791
4792 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
4793 if (Op1I) {
4794 Value *A, *B;
4795 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
4796 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00004797 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00004798 I.swapOperands();
4799 std::swap(Op0, Op1);
Chris Lattner318bf792007-03-18 22:51:34 +00004800 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00004801 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00004802 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00004803 }
Chris Lattner318bf792007-03-18 22:51:34 +00004804 } else if (match(Op1I, m_Xor(m_Value(A), m_Value(B)))) {
4805 if (Op0 == A) // A^(A^B) == B
4806 return ReplaceInstUsesWith(I, B);
4807 else if (Op0 == B) // A^(B^A) == B
4808 return ReplaceInstUsesWith(I, A);
4809 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
4810 if (A == Op0) // A^(A&B) -> A^(B&A)
Chris Lattner64daab52006-04-01 08:03:55 +00004811 Op1I->swapOperands();
Chris Lattner318bf792007-03-18 22:51:34 +00004812 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattner64daab52006-04-01 08:03:55 +00004813 I.swapOperands(); // Simplified below.
4814 std::swap(Op0, Op1);
4815 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00004816 }
Chris Lattner318bf792007-03-18 22:51:34 +00004817 }
4818
4819 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
4820 if (Op0I) {
4821 Value *A, *B;
4822 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
4823 if (A == Op1) // (B|A)^B == (A|B)^B
4824 std::swap(A, B);
4825 if (B == Op1) { // (A|B)^B == A & ~B
4826 Instruction *NotB =
4827 InsertNewInstBefore(BinaryOperator::createNot(Op1, "tmp"), I);
4828 return BinaryOperator::createAnd(A, NotB);
Chris Lattnercb40a372003-03-10 18:24:17 +00004829 }
Chris Lattner318bf792007-03-18 22:51:34 +00004830 } else if (match(Op0I, m_Xor(m_Value(A), m_Value(B)))) {
4831 if (Op1 == A) // (A^B)^A == B
4832 return ReplaceInstUsesWith(I, B);
4833 else if (Op1 == B) // (B^A)^A == B
4834 return ReplaceInstUsesWith(I, A);
4835 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
4836 if (A == Op1) // (A&B)^A -> (B&A)^A
4837 std::swap(A, B);
4838 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattnerae1ab392006-04-01 22:05:01 +00004839 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner318bf792007-03-18 22:51:34 +00004840 Instruction *N =
4841 InsertNewInstBefore(BinaryOperator::createNot(A, "tmp"), I);
Chris Lattner64daab52006-04-01 08:03:55 +00004842 return BinaryOperator::createAnd(N, Op1);
4843 }
Chris Lattnercb40a372003-03-10 18:24:17 +00004844 }
Chris Lattner318bf792007-03-18 22:51:34 +00004845 }
4846
4847 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
4848 if (Op0I && Op1I && Op0I->isShift() &&
4849 Op0I->getOpcode() == Op1I->getOpcode() &&
4850 Op0I->getOperand(1) == Op1I->getOperand(1) &&
4851 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
4852 Instruction *NewOp =
4853 InsertNewInstBefore(BinaryOperator::createXor(Op0I->getOperand(0),
4854 Op1I->getOperand(0),
4855 Op0I->getName()), I);
4856 return BinaryOperator::create(Op1I->getOpcode(), NewOp,
4857 Op1I->getOperand(1));
4858 }
4859
4860 if (Op0I && Op1I) {
4861 Value *A, *B, *C, *D;
4862 // (A & B)^(A | B) -> A ^ B
4863 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4864 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
4865 if ((A == C && B == D) || (A == D && B == C))
4866 return BinaryOperator::createXor(A, B);
4867 }
4868 // (A | B)^(A & B) -> A ^ B
4869 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
4870 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4871 if ((A == C && B == D) || (A == D && B == C))
4872 return BinaryOperator::createXor(A, B);
4873 }
4874
4875 // (A & B)^(C & D)
4876 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
4877 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4878 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4879 // (X & Y)^(X & Y) -> (Y^Z) & X
4880 Value *X = 0, *Y = 0, *Z = 0;
4881 if (A == C)
4882 X = A, Y = B, Z = D;
4883 else if (A == D)
4884 X = A, Y = B, Z = C;
4885 else if (B == C)
4886 X = B, Y = A, Z = D;
4887 else if (B == D)
4888 X = B, Y = A, Z = C;
4889
4890 if (X) {
4891 Instruction *NewOp =
4892 InsertNewInstBefore(BinaryOperator::createXor(Y, Z, Op0->getName()), I);
4893 return BinaryOperator::createAnd(NewOp, X);
4894 }
4895 }
4896 }
4897
Reid Spencere4d87aa2006-12-23 06:05:41 +00004898 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4899 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4900 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004901 return R;
4902
Chris Lattner6fc205f2006-05-05 06:39:07 +00004903 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004904 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
Chris Lattner6fc205f2006-05-05 06:39:07 +00004905 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004906 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4907 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00004908 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004909 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004910 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4911 I.getType(), TD) &&
4912 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4913 I.getType(), TD)) {
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004914 Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
4915 Op1C->getOperand(0),
4916 I.getName());
4917 InsertNewInstBefore(NewOp, I);
4918 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4919 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004920 }
Chris Lattnere511b742006-11-14 07:46:50 +00004921
Chris Lattner7e708292002-06-25 16:13:24 +00004922 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004923}
4924
Chris Lattnera96879a2004-09-29 17:40:11 +00004925/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4926/// overflowed for this type.
4927static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
4928 ConstantInt *In2) {
4929 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
4930
Reid Spencerc5b206b2006-12-31 05:48:39 +00004931 return cast<ConstantInt>(Result)->getZExtValue() <
4932 cast<ConstantInt>(In1)->getZExtValue();
Chris Lattnera96879a2004-09-29 17:40:11 +00004933}
4934
Chris Lattner574da9b2005-01-13 20:14:25 +00004935/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4936/// code necessary to compute the offset from the base pointer (without adding
4937/// in the base pointer). Return the result as a signed integer of intptr size.
4938static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4939 TargetData &TD = IC.getTargetData();
4940 gep_type_iterator GTI = gep_type_begin(GEP);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004941 const Type *IntPtrTy = TD.getIntPtrType();
4942 Value *Result = Constant::getNullValue(IntPtrTy);
Chris Lattner574da9b2005-01-13 20:14:25 +00004943
4944 // Build a mask for high order bits.
Chris Lattner1a074fc2006-02-07 07:00:41 +00004945 uint64_t PtrSizeMask = ~0ULL >> (64-TD.getPointerSize()*8);
Chris Lattner574da9b2005-01-13 20:14:25 +00004946
Chris Lattner574da9b2005-01-13 20:14:25 +00004947 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
4948 Value *Op = GEP->getOperand(i);
Chris Lattner0b84c802005-01-13 23:26:48 +00004949 uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004950 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
Chris Lattner574da9b2005-01-13 20:14:25 +00004951 if (Constant *OpC = dyn_cast<Constant>(Op)) {
4952 if (!OpC->isNullValue()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00004953 OpC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
Chris Lattner574da9b2005-01-13 20:14:25 +00004954 Scale = ConstantExpr::getMul(OpC, Scale);
4955 if (Constant *RC = dyn_cast<Constant>(Result))
4956 Result = ConstantExpr::getAdd(RC, Scale);
4957 else {
4958 // Emit an add instruction.
4959 Result = IC.InsertNewInstBefore(
4960 BinaryOperator::createAdd(Result, Scale,
4961 GEP->getName()+".offs"), I);
4962 }
4963 }
4964 } else {
Chris Lattner6f7f02f2005-01-14 17:17:59 +00004965 // Convert to correct type.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004966 Op = IC.InsertNewInstBefore(CastInst::createSExtOrBitCast(Op, IntPtrTy,
Chris Lattner6f7f02f2005-01-14 17:17:59 +00004967 Op->getName()+".c"), I);
4968 if (Size != 1)
Chris Lattner5bdf04c2005-01-13 20:40:58 +00004969 // We'll let instcombine(mul) convert this to a shl if possible.
4970 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
4971 GEP->getName()+".idx"), I);
Chris Lattner574da9b2005-01-13 20:14:25 +00004972
4973 // Emit an add instruction.
Chris Lattner5bdf04c2005-01-13 20:40:58 +00004974 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
Chris Lattner574da9b2005-01-13 20:14:25 +00004975 GEP->getName()+".offs"), I);
4976 }
4977 }
4978 return Result;
4979}
4980
Reid Spencere4d87aa2006-12-23 06:05:41 +00004981/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner574da9b2005-01-13 20:14:25 +00004982/// else. At this point we know that the GEP is on the LHS of the comparison.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004983Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
4984 ICmpInst::Predicate Cond,
4985 Instruction &I) {
Chris Lattner574da9b2005-01-13 20:14:25 +00004986 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattnere9d782b2005-01-13 22:25:21 +00004987
4988 if (CastInst *CI = dyn_cast<CastInst>(RHS))
4989 if (isa<PointerType>(CI->getOperand(0)->getType()))
4990 RHS = CI->getOperand(0);
4991
Chris Lattner574da9b2005-01-13 20:14:25 +00004992 Value *PtrBase = GEPLHS->getOperand(0);
4993 if (PtrBase == RHS) {
4994 // As an optimization, we don't actually have to compute the actual value of
Reid Spencere4d87aa2006-12-23 06:05:41 +00004995 // OFFSET if this is a icmp_eq or icmp_ne comparison, just return whether
4996 // each index is zero or not.
4997 if (Cond == ICmpInst::ICMP_EQ || Cond == ICmpInst::ICMP_NE) {
Chris Lattnere9d782b2005-01-13 22:25:21 +00004998 Instruction *InVal = 0;
Chris Lattnerad5fec12005-01-28 19:32:01 +00004999 gep_type_iterator GTI = gep_type_begin(GEPLHS);
5000 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattnere9d782b2005-01-13 22:25:21 +00005001 bool EmitIt = true;
5002 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
5003 if (isa<UndefValue>(C)) // undef index -> undef.
5004 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
5005 if (C->isNullValue())
5006 EmitIt = false;
Chris Lattnerad5fec12005-01-28 19:32:01 +00005007 else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
5008 EmitIt = false; // This is indexing into a zero sized array?
Misha Brukmanfd939082005-04-21 23:48:37 +00005009 } else if (isa<ConstantInt>(C))
Chris Lattnere9d782b2005-01-13 22:25:21 +00005010 return ReplaceInstUsesWith(I, // No comparison is needed here.
Reid Spencer579dca12007-01-12 04:24:46 +00005011 ConstantInt::get(Type::Int1Ty,
5012 Cond == ICmpInst::ICMP_NE));
Chris Lattnere9d782b2005-01-13 22:25:21 +00005013 }
5014
5015 if (EmitIt) {
Misha Brukmanfd939082005-04-21 23:48:37 +00005016 Instruction *Comp =
Reid Spencere4d87aa2006-12-23 06:05:41 +00005017 new ICmpInst(Cond, GEPLHS->getOperand(i),
Chris Lattnere9d782b2005-01-13 22:25:21 +00005018 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
5019 if (InVal == 0)
5020 InVal = Comp;
5021 else {
5022 InVal = InsertNewInstBefore(InVal, I);
5023 InsertNewInstBefore(Comp, I);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005024 if (Cond == ICmpInst::ICMP_NE) // True if any are unequal
Chris Lattnere9d782b2005-01-13 22:25:21 +00005025 InVal = BinaryOperator::createOr(InVal, Comp);
5026 else // True if all are equal
5027 InVal = BinaryOperator::createAnd(InVal, Comp);
5028 }
5029 }
5030 }
5031
5032 if (InVal)
5033 return InVal;
5034 else
Reid Spencere4d87aa2006-12-23 06:05:41 +00005035 // No comparison is needed here, all indexes = 0
Reid Spencer579dca12007-01-12 04:24:46 +00005036 ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5037 Cond == ICmpInst::ICMP_EQ));
Chris Lattnere9d782b2005-01-13 22:25:21 +00005038 }
Chris Lattner574da9b2005-01-13 20:14:25 +00005039
Reid Spencere4d87aa2006-12-23 06:05:41 +00005040 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00005041 // the result to fold to a constant!
5042 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
5043 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
5044 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005045 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
5046 Constant::getNullValue(Offset->getType()));
Chris Lattner574da9b2005-01-13 20:14:25 +00005047 }
5048 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00005049 // If the base pointers are different, but the indices are the same, just
5050 // compare the base pointer.
5051 if (PtrBase != GEPRHS->getOperand(0)) {
5052 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00005053 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00005054 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00005055 if (IndicesTheSame)
5056 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5057 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5058 IndicesTheSame = false;
5059 break;
5060 }
5061
5062 // If all indices are the same, just compare the base pointers.
5063 if (IndicesTheSame)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005064 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
5065 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera70b66d2005-04-25 20:17:30 +00005066
5067 // Otherwise, the base pointers are different and the indices are
5068 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00005069 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00005070 }
Chris Lattner574da9b2005-01-13 20:14:25 +00005071
Chris Lattnere9d782b2005-01-13 22:25:21 +00005072 // If one of the GEPs has all zero indices, recurse.
5073 bool AllZeros = true;
5074 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5075 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5076 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5077 AllZeros = false;
5078 break;
5079 }
5080 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005081 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5082 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005083
5084 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00005085 AllZeros = true;
5086 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5087 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5088 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5089 AllZeros = false;
5090 break;
5091 }
5092 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005093 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005094
Chris Lattner4401c9c2005-01-14 00:20:05 +00005095 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5096 // If the GEPs only differ by one index, compare it.
5097 unsigned NumDifferences = 0; // Keep track of # differences.
5098 unsigned DiffOperand = 0; // The operand that differs.
5099 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5100 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00005101 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5102 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005103 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00005104 NumDifferences = 2;
5105 break;
5106 } else {
5107 if (NumDifferences++) break;
5108 DiffOperand = i;
5109 }
5110 }
5111
5112 if (NumDifferences == 0) // SAME GEP?
5113 return ReplaceInstUsesWith(I, // No comparison is needed here.
Reid Spencer579dca12007-01-12 04:24:46 +00005114 ConstantInt::get(Type::Int1Ty,
5115 Cond == ICmpInst::ICMP_EQ));
Chris Lattner4401c9c2005-01-14 00:20:05 +00005116 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005117 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5118 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005119 // Make sure we do a signed comparison here.
5120 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005121 }
5122 }
5123
Reid Spencere4d87aa2006-12-23 06:05:41 +00005124 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00005125 // the result to fold to a constant!
5126 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5127 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5128 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
5129 Value *L = EmitGEPOffset(GEPLHS, I, *this);
5130 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005131 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner574da9b2005-01-13 20:14:25 +00005132 }
5133 }
5134 return 0;
5135}
5136
Reid Spencere4d87aa2006-12-23 06:05:41 +00005137Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5138 bool Changed = SimplifyCompare(I);
Chris Lattner8b170942002-08-09 23:47:40 +00005139 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005140
Chris Lattner58e97462007-01-14 19:42:17 +00005141 // Fold trivial predicates.
5142 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5143 return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
5144 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5145 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5146
5147 // Simplify 'fcmp pred X, X'
5148 if (Op0 == Op1) {
5149 switch (I.getPredicate()) {
5150 default: assert(0 && "Unknown predicate!");
5151 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5152 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5153 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
5154 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5155 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5156 case FCmpInst::FCMP_OLT: // True if ordered and less than
5157 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
5158 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5159
5160 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5161 case FCmpInst::FCMP_ULT: // True if unordered or less than
5162 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5163 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5164 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5165 I.setPredicate(FCmpInst::FCMP_UNO);
5166 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5167 return &I;
5168
5169 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5170 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5171 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5172 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5173 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5174 I.setPredicate(FCmpInst::FCMP_ORD);
5175 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5176 return &I;
5177 }
5178 }
5179
Reid Spencere4d87aa2006-12-23 06:05:41 +00005180 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Reid Spencer4fe16d62007-01-11 18:21:29 +00005181 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Chris Lattnere87597f2004-10-16 18:11:37 +00005182
Reid Spencere4d87aa2006-12-23 06:05:41 +00005183 // Handle fcmp with constant RHS
5184 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5185 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5186 switch (LHSI->getOpcode()) {
5187 case Instruction::PHI:
5188 if (Instruction *NV = FoldOpIntoPhi(I))
5189 return NV;
5190 break;
5191 case Instruction::Select:
5192 // If either operand of the select is a constant, we can fold the
5193 // comparison into the select arms, which will cause one to be
5194 // constant folded and the select turned into a bitwise or.
5195 Value *Op1 = 0, *Op2 = 0;
5196 if (LHSI->hasOneUse()) {
5197 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5198 // Fold the known value into the constant operand.
5199 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5200 // Insert a new FCmp of the other select operand.
5201 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5202 LHSI->getOperand(2), RHSC,
5203 I.getName()), I);
5204 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5205 // Fold the known value into the constant operand.
5206 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5207 // Insert a new FCmp of the other select operand.
5208 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5209 LHSI->getOperand(1), RHSC,
5210 I.getName()), I);
5211 }
5212 }
5213
5214 if (Op1)
5215 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
5216 break;
5217 }
5218 }
5219
5220 return Changed ? &I : 0;
5221}
5222
5223Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5224 bool Changed = SimplifyCompare(I);
5225 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5226 const Type *Ty = Op0->getType();
5227
5228 // icmp X, X
5229 if (Op0 == Op1)
Reid Spencer579dca12007-01-12 04:24:46 +00005230 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5231 isTrueWhenEqual(I)));
Reid Spencere4d87aa2006-12-23 06:05:41 +00005232
5233 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Reid Spencer4fe16d62007-01-11 18:21:29 +00005234 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Reid Spencere4d87aa2006-12-23 06:05:41 +00005235
5236 // icmp of GlobalValues can never equal each other as long as they aren't
5237 // external weak linkage type.
5238 if (GlobalValue *GV0 = dyn_cast<GlobalValue>(Op0))
5239 if (GlobalValue *GV1 = dyn_cast<GlobalValue>(Op1))
5240 if (!GV0->hasExternalWeakLinkage() || !GV1->hasExternalWeakLinkage())
Reid Spencer579dca12007-01-12 04:24:46 +00005241 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5242 !isTrueWhenEqual(I)));
Reid Spencere4d87aa2006-12-23 06:05:41 +00005243
5244 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner711b3402004-11-14 07:33:16 +00005245 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanfd939082005-04-21 23:48:37 +00005246 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5247 isa<ConstantPointerNull>(Op0)) &&
5248 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner711b3402004-11-14 07:33:16 +00005249 isa<ConstantPointerNull>(Op1)))
Reid Spencer579dca12007-01-12 04:24:46 +00005250 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5251 !isTrueWhenEqual(I)));
Chris Lattner8b170942002-08-09 23:47:40 +00005252
Reid Spencere4d87aa2006-12-23 06:05:41 +00005253 // icmp's with boolean values can always be turned into bitwise operations
Reid Spencer4fe16d62007-01-11 18:21:29 +00005254 if (Ty == Type::Int1Ty) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005255 switch (I.getPredicate()) {
5256 default: assert(0 && "Invalid icmp instruction!");
5257 case ICmpInst::ICMP_EQ: { // icmp eq bool %A, %B -> ~(A^B)
Chris Lattner48595f12004-06-10 02:07:29 +00005258 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner8b170942002-08-09 23:47:40 +00005259 InsertNewInstBefore(Xor, I);
Chris Lattnerde90b762003-11-03 04:25:02 +00005260 return BinaryOperator::createNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00005261 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00005262 case ICmpInst::ICMP_NE: // icmp eq bool %A, %B -> A^B
Chris Lattner5dbef222004-08-11 00:50:51 +00005263 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00005264
Reid Spencere4d87aa2006-12-23 06:05:41 +00005265 case ICmpInst::ICMP_UGT:
5266 case ICmpInst::ICMP_SGT:
5267 std::swap(Op0, Op1); // Change icmp gt -> icmp lt
Chris Lattner5dbef222004-08-11 00:50:51 +00005268 // FALL THROUGH
Reid Spencere4d87aa2006-12-23 06:05:41 +00005269 case ICmpInst::ICMP_ULT:
5270 case ICmpInst::ICMP_SLT: { // icmp lt bool A, B -> ~X & Y
Chris Lattner5dbef222004-08-11 00:50:51 +00005271 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
5272 InsertNewInstBefore(Not, I);
5273 return BinaryOperator::createAnd(Not, Op1);
5274 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00005275 case ICmpInst::ICMP_UGE:
5276 case ICmpInst::ICMP_SGE:
5277 std::swap(Op0, Op1); // Change icmp ge -> icmp le
Chris Lattner5dbef222004-08-11 00:50:51 +00005278 // FALL THROUGH
Reid Spencere4d87aa2006-12-23 06:05:41 +00005279 case ICmpInst::ICMP_ULE:
5280 case ICmpInst::ICMP_SLE: { // icmp le bool %A, %B -> ~A | B
Chris Lattner5dbef222004-08-11 00:50:51 +00005281 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
5282 InsertNewInstBefore(Not, I);
5283 return BinaryOperator::createOr(Not, Op1);
5284 }
5285 }
Chris Lattner8b170942002-08-09 23:47:40 +00005286 }
5287
Chris Lattner2be51ae2004-06-09 04:24:29 +00005288 // See if we are doing a comparison between a constant and an instruction that
5289 // can be folded into the comparison.
Chris Lattner8b170942002-08-09 23:47:40 +00005290 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005291 switch (I.getPredicate()) {
5292 default: break;
5293 case ICmpInst::ICMP_ULT: // A <u MIN -> FALSE
5294 if (CI->isMinValue(false))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005295 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005296 if (CI->isMaxValue(false)) // A <u MAX -> A != MAX
5297 return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
5298 if (isMinValuePlusOne(CI,false)) // A <u MIN+1 -> A == MIN
5299 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5300 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005301
Reid Spencere4d87aa2006-12-23 06:05:41 +00005302 case ICmpInst::ICMP_SLT:
5303 if (CI->isMinValue(true)) // A <s MIN -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005304 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005305 if (CI->isMaxValue(true)) // A <s MAX -> A != MAX
5306 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5307 if (isMinValuePlusOne(CI,true)) // A <s MIN+1 -> A == MIN
5308 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5309 break;
5310
5311 case ICmpInst::ICMP_UGT:
5312 if (CI->isMaxValue(false)) // A >u MAX -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005313 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005314 if (CI->isMinValue(false)) // A >u MIN -> A != MIN
5315 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5316 if (isMaxValueMinusOne(CI, false)) // A >u MAX-1 -> A == MAX
5317 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5318 break;
5319
5320 case ICmpInst::ICMP_SGT:
5321 if (CI->isMaxValue(true)) // A >s MAX -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005322 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005323 if (CI->isMinValue(true)) // A >s MIN -> A != MIN
5324 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5325 if (isMaxValueMinusOne(CI, true)) // A >s MAX-1 -> A == MAX
5326 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5327 break;
5328
5329 case ICmpInst::ICMP_ULE:
5330 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005331 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005332 if (CI->isMinValue(false)) // A <=u MIN -> A == MIN
5333 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5334 if (isMaxValueMinusOne(CI,false)) // A <=u MAX-1 -> A != MAX
5335 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5336 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005337
Reid Spencere4d87aa2006-12-23 06:05:41 +00005338 case ICmpInst::ICMP_SLE:
5339 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005340 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005341 if (CI->isMinValue(true)) // A <=s MIN -> A == MIN
5342 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5343 if (isMaxValueMinusOne(CI,true)) // A <=s MAX-1 -> A != MAX
5344 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5345 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005346
Reid Spencere4d87aa2006-12-23 06:05:41 +00005347 case ICmpInst::ICMP_UGE:
5348 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005349 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005350 if (CI->isMaxValue(false)) // A >=u MAX -> A == MAX
5351 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5352 if (isMinValuePlusOne(CI,false)) // A >=u MIN-1 -> A != MIN
5353 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5354 break;
5355
5356 case ICmpInst::ICMP_SGE:
5357 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005358 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005359 if (CI->isMaxValue(true)) // A >=s MAX -> A == MAX
5360 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5361 if (isMinValuePlusOne(CI,true)) // A >=s MIN-1 -> A != MIN
5362 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5363 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005364 }
5365
Reid Spencere4d87aa2006-12-23 06:05:41 +00005366 // If we still have a icmp le or icmp ge instruction, turn it into the
5367 // appropriate icmp lt or icmp gt instruction. Since the border cases have
Chris Lattnera96879a2004-09-29 17:40:11 +00005368 // already been handled above, this requires little checking.
5369 //
Reid Spencere4d87aa2006-12-23 06:05:41 +00005370 if (I.getPredicate() == ICmpInst::ICMP_ULE)
5371 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5372 if (I.getPredicate() == ICmpInst::ICMP_SLE)
5373 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5374 if (I.getPredicate() == ICmpInst::ICMP_UGE)
5375 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5376 if (I.getPredicate() == ICmpInst::ICMP_SGE)
5377 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005378
5379 // See if we can fold the comparison based on bits known to be zero or one
5380 // in the input.
5381 uint64_t KnownZero, KnownOne;
Reid Spencerc1030572007-01-19 21:13:56 +00005382 if (SimplifyDemandedBits(Op0, cast<IntegerType>(Ty)->getBitMask(),
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005383 KnownZero, KnownOne, 0))
5384 return &I;
5385
5386 // Given the known and unknown bits, compute a range that the LHS could be
5387 // in.
5388 if (KnownOne | KnownZero) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005389 // Compute the Min, Max and RHS values based on the known bits. For the
5390 // EQ and NE we use unsigned values.
Reid Spencerb3307b22006-12-23 19:17:57 +00005391 uint64_t UMin = 0, UMax = 0, URHSVal = 0;
5392 int64_t SMin = 0, SMax = 0, SRHSVal = 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005393 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
5394 SRHSVal = CI->getSExtValue();
5395 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, SMin,
5396 SMax);
5397 } else {
5398 URHSVal = CI->getZExtValue();
5399 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, UMin,
5400 UMax);
5401 }
5402 switch (I.getPredicate()) { // LE/GE have been folded already.
5403 default: assert(0 && "Unknown icmp opcode!");
5404 case ICmpInst::ICMP_EQ:
5405 if (UMax < URHSVal || UMin > URHSVal)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005406 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005407 break;
5408 case ICmpInst::ICMP_NE:
5409 if (UMax < URHSVal || UMin > URHSVal)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005410 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005411 break;
5412 case ICmpInst::ICMP_ULT:
5413 if (UMax < URHSVal)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005414 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005415 if (UMin > URHSVal)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005416 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005417 break;
5418 case ICmpInst::ICMP_UGT:
5419 if (UMin > URHSVal)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005420 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005421 if (UMax < URHSVal)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005422 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005423 break;
5424 case ICmpInst::ICMP_SLT:
5425 if (SMax < SRHSVal)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005426 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005427 if (SMin > SRHSVal)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005428 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005429 break;
5430 case ICmpInst::ICMP_SGT:
5431 if (SMin > SRHSVal)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005432 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005433 if (SMax < SRHSVal)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005434 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005435 break;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005436 }
5437 }
5438
Reid Spencere4d87aa2006-12-23 06:05:41 +00005439 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer1628cec2006-10-26 06:15:43 +00005440 // instruction, see if that instruction also has constants so that the
Reid Spencere4d87aa2006-12-23 06:05:41 +00005441 // instruction can be folded into the icmp
Chris Lattner3c6a0d42004-05-25 06:32:08 +00005442 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner648e3bc2004-09-23 21:52:49 +00005443 switch (LHSI->getOpcode()) {
5444 case Instruction::And:
5445 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
5446 LHSI->getOperand(0)->hasOneUse()) {
Chris Lattnere695a3b2006-09-18 05:27:43 +00005447 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
5448
Reid Spencere4d87aa2006-12-23 06:05:41 +00005449 // If the LHS is an AND of a truncating cast, we can widen the
Chris Lattnere695a3b2006-09-18 05:27:43 +00005450 // and/compare to be the input width without changing the value
5451 // produced, eliminating a cast.
5452 if (CastInst *Cast = dyn_cast<CastInst>(LHSI->getOperand(0))) {
5453 // We can do this transformation if either the AND constant does not
5454 // have its sign bit set or if it is an equality comparison.
5455 // Extending a relational comparison when we're checking the sign
5456 // bit would not work.
Reid Spencer3da59db2006-11-27 01:05:10 +00005457 if (Cast->hasOneUse() && isa<TruncInst>(Cast) &&
Chris Lattnere695a3b2006-09-18 05:27:43 +00005458 (I.isEquality() ||
5459 (AndCST->getZExtValue() == (uint64_t)AndCST->getSExtValue()) &&
5460 (CI->getZExtValue() == (uint64_t)CI->getSExtValue()))) {
5461 ConstantInt *NewCST;
5462 ConstantInt *NewCI;
Reid Spencerc5b206b2006-12-31 05:48:39 +00005463 NewCST = ConstantInt::get(Cast->getOperand(0)->getType(),
5464 AndCST->getZExtValue());
5465 NewCI = ConstantInt::get(Cast->getOperand(0)->getType(),
5466 CI->getZExtValue());
Chris Lattnere695a3b2006-09-18 05:27:43 +00005467 Instruction *NewAnd =
5468 BinaryOperator::createAnd(Cast->getOperand(0), NewCST,
5469 LHSI->getName());
5470 InsertNewInstBefore(NewAnd, I);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005471 return new ICmpInst(I.getPredicate(), NewAnd, NewCI);
Chris Lattnere695a3b2006-09-18 05:27:43 +00005472 }
5473 }
5474
Chris Lattner648e3bc2004-09-23 21:52:49 +00005475 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
5476 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
5477 // happens a LOT in code produced by the C front-end, for bitfield
5478 // access.
Reid Spencer832254e2007-02-02 02:16:23 +00005479 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
5480 if (Shift && !Shift->isShift())
5481 Shift = 0;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005482
Reid Spencerb83eb642006-10-20 07:07:24 +00005483 ConstantInt *ShAmt;
5484 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005485 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
5486 const Type *AndTy = AndCST->getType(); // Type of the and.
Misha Brukmanfd939082005-04-21 23:48:37 +00005487
Chris Lattner648e3bc2004-09-23 21:52:49 +00005488 // We can fold this as long as we can't shift unknown bits
5489 // into the mask. This can only happen with signed shift
5490 // rights, as they sign-extend.
5491 if (ShAmt) {
Chris Lattner65b72ba2006-09-18 04:22:48 +00005492 bool CanFold = Shift->isLogicalShift();
Chris Lattner648e3bc2004-09-23 21:52:49 +00005493 if (!CanFold) {
5494 // To test for the bad case of the signed shr, see if any
5495 // of the bits shifted in could be tested after the mask.
Reid Spencerb83eb642006-10-20 07:07:24 +00005496 int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getZExtValue();
Chris Lattnerd7e31cf2005-06-17 01:29:28 +00005497 if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
5498
Reid Spencer832254e2007-02-02 02:16:23 +00005499 Constant *OShAmt = ConstantInt::get(AndTy, ShAmtVal);
Misha Brukmanfd939082005-04-21 23:48:37 +00005500 Constant *ShVal =
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005501 ConstantExpr::getShl(ConstantInt::getAllOnesValue(AndTy),
5502 OShAmt);
Chris Lattner648e3bc2004-09-23 21:52:49 +00005503 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
5504 CanFold = true;
5505 }
Misha Brukmanfd939082005-04-21 23:48:37 +00005506
Chris Lattner648e3bc2004-09-23 21:52:49 +00005507 if (CanFold) {
Chris Lattner0cba71b2004-09-28 17:54:07 +00005508 Constant *NewCst;
5509 if (Shift->getOpcode() == Instruction::Shl)
Reid Spencer3822ff52006-11-08 06:47:33 +00005510 NewCst = ConstantExpr::getLShr(CI, ShAmt);
Chris Lattner0cba71b2004-09-28 17:54:07 +00005511 else
5512 NewCst = ConstantExpr::getShl(CI, ShAmt);
Chris Lattner83c4ec02004-09-27 19:29:18 +00005513
Chris Lattner648e3bc2004-09-23 21:52:49 +00005514 // Check to see if we are shifting out any of the bits being
5515 // compared.
5516 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
5517 // If we shifted bits out, the fold is not going to work out.
5518 // As a special case, check to see if this means that the
5519 // result is always true or false now.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005520 if (I.getPredicate() == ICmpInst::ICMP_EQ)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005521 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005522 if (I.getPredicate() == ICmpInst::ICMP_NE)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005523 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner648e3bc2004-09-23 21:52:49 +00005524 } else {
5525 I.setOperand(1, NewCst);
Chris Lattner0cba71b2004-09-28 17:54:07 +00005526 Constant *NewAndCST;
5527 if (Shift->getOpcode() == Instruction::Shl)
Reid Spencer3822ff52006-11-08 06:47:33 +00005528 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
Chris Lattner0cba71b2004-09-28 17:54:07 +00005529 else
5530 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
5531 LHSI->setOperand(1, NewAndCST);
Reid Spencer8c5a53a2007-01-04 05:23:51 +00005532 LHSI->setOperand(0, Shift->getOperand(0));
Chris Lattnerdbab3862007-03-02 21:28:56 +00005533 AddToWorkList(Shift); // Shift is dead.
Chris Lattner648e3bc2004-09-23 21:52:49 +00005534 AddUsesToWorkList(I);
5535 return &I;
Chris Lattner5eb91942004-07-21 19:50:44 +00005536 }
5537 }
Chris Lattner457dd822004-06-09 07:59:58 +00005538 }
Chris Lattner65b72ba2006-09-18 04:22:48 +00005539
5540 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
5541 // preferable because it allows the C<<Y expression to be hoisted out
5542 // of a loop if Y is invariant and X is not.
5543 if (Shift && Shift->hasOneUse() && CI->isNullValue() &&
Chris Lattner6d7ca922006-09-18 18:27:05 +00005544 I.isEquality() && !Shift->isArithmeticShift() &&
5545 isa<Instruction>(Shift->getOperand(0))) {
Chris Lattner65b72ba2006-09-18 04:22:48 +00005546 // Compute C << Y.
5547 Value *NS;
Reid Spencer3822ff52006-11-08 06:47:33 +00005548 if (Shift->getOpcode() == Instruction::LShr) {
Reid Spencercc46cdb2007-02-02 14:08:20 +00005549 NS = BinaryOperator::createShl(AndCST,
Reid Spencer832254e2007-02-02 02:16:23 +00005550 Shift->getOperand(1), "tmp");
Chris Lattner65b72ba2006-09-18 04:22:48 +00005551 } else {
Reid Spencer7eb76382006-12-13 17:19:09 +00005552 // Insert a logical shift.
Reid Spencercc46cdb2007-02-02 14:08:20 +00005553 NS = BinaryOperator::createLShr(AndCST,
Reid Spencer832254e2007-02-02 02:16:23 +00005554 Shift->getOperand(1), "tmp");
Chris Lattner65b72ba2006-09-18 04:22:48 +00005555 }
5556 InsertNewInstBefore(cast<Instruction>(NS), I);
5557
Chris Lattner65b72ba2006-09-18 04:22:48 +00005558 // Compute X & (C << Y).
Reid Spencer8c5a53a2007-01-04 05:23:51 +00005559 Instruction *NewAnd = BinaryOperator::createAnd(
5560 Shift->getOperand(0), NS, LHSI->getName());
Chris Lattner65b72ba2006-09-18 04:22:48 +00005561 InsertNewInstBefore(NewAnd, I);
5562
5563 I.setOperand(0, NewAnd);
5564 return &I;
5565 }
Chris Lattner648e3bc2004-09-23 21:52:49 +00005566 }
5567 break;
Chris Lattner83c4ec02004-09-27 19:29:18 +00005568
Reid Spencere4d87aa2006-12-23 06:05:41 +00005569 case Instruction::Shl: // (icmp pred (shl X, ShAmt), CI)
Reid Spencerb83eb642006-10-20 07:07:24 +00005570 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Chris Lattner65b72ba2006-09-18 04:22:48 +00005571 if (I.isEquality()) {
Chris Lattnere17a1282005-06-15 20:53:31 +00005572 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
5573
5574 // Check that the shift amount is in range. If not, don't perform
5575 // undefined shifts. When the shift is visited it will be
5576 // simplified.
Reid Spencerb83eb642006-10-20 07:07:24 +00005577 if (ShAmt->getZExtValue() >= TypeBits)
Chris Lattnere17a1282005-06-15 20:53:31 +00005578 break;
5579
Chris Lattner18d19ca2004-09-28 18:22:15 +00005580 // If we are comparing against bits always shifted out, the
5581 // comparison cannot succeed.
Misha Brukmanfd939082005-04-21 23:48:37 +00005582 Constant *Comp =
Reid Spencer3822ff52006-11-08 06:47:33 +00005583 ConstantExpr::getShl(ConstantExpr::getLShr(CI, ShAmt), ShAmt);
Chris Lattner18d19ca2004-09-28 18:22:15 +00005584 if (Comp != CI) {// Comparing against a bit that we know is zero.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005585 bool IsICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
Reid Spencer579dca12007-01-12 04:24:46 +00005586 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
Chris Lattner18d19ca2004-09-28 18:22:15 +00005587 return ReplaceInstUsesWith(I, Cst);
5588 }
5589
5590 if (LHSI->hasOneUse()) {
5591 // Otherwise strength reduce the shift into an and.
Reid Spencerb83eb642006-10-20 07:07:24 +00005592 unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
Chris Lattner18d19ca2004-09-28 18:22:15 +00005593 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
Reid Spencerc5b206b2006-12-31 05:48:39 +00005594 Constant *Mask = ConstantInt::get(CI->getType(), Val);
Misha Brukmanfd939082005-04-21 23:48:37 +00005595
Chris Lattner18d19ca2004-09-28 18:22:15 +00005596 Instruction *AndI =
5597 BinaryOperator::createAnd(LHSI->getOperand(0),
5598 Mask, LHSI->getName()+".mask");
5599 Value *And = InsertNewInstBefore(AndI, I);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005600 return new ICmpInst(I.getPredicate(), And,
Reid Spencer3822ff52006-11-08 06:47:33 +00005601 ConstantExpr::getLShr(CI, ShAmt));
Chris Lattner18d19ca2004-09-28 18:22:15 +00005602 }
5603 }
Chris Lattner18d19ca2004-09-28 18:22:15 +00005604 }
5605 break;
5606
Reid Spencere4d87aa2006-12-23 06:05:41 +00005607 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Reid Spencer3822ff52006-11-08 06:47:33 +00005608 case Instruction::AShr:
Reid Spencerb83eb642006-10-20 07:07:24 +00005609 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Chris Lattner65b72ba2006-09-18 04:22:48 +00005610 if (I.isEquality()) {
Chris Lattnere17a1282005-06-15 20:53:31 +00005611 // Check that the shift amount is in range. If not, don't perform
5612 // undefined shifts. When the shift is visited it will be
5613 // simplified.
Chris Lattneraa457ac2005-06-16 01:52:07 +00005614 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencerb83eb642006-10-20 07:07:24 +00005615 if (ShAmt->getZExtValue() >= TypeBits)
Chris Lattnere17a1282005-06-15 20:53:31 +00005616 break;
5617
Chris Lattnerf63f6472004-09-27 16:18:50 +00005618 // If we are comparing against bits always shifted out, the
5619 // comparison cannot succeed.
Reid Spencer3822ff52006-11-08 06:47:33 +00005620 Constant *Comp;
Reid Spencerc5b206b2006-12-31 05:48:39 +00005621 if (LHSI->getOpcode() == Instruction::LShr)
Reid Spencer3822ff52006-11-08 06:47:33 +00005622 Comp = ConstantExpr::getLShr(ConstantExpr::getShl(CI, ShAmt),
5623 ShAmt);
5624 else
5625 Comp = ConstantExpr::getAShr(ConstantExpr::getShl(CI, ShAmt),
5626 ShAmt);
Misha Brukmanfd939082005-04-21 23:48:37 +00005627
Chris Lattnerf63f6472004-09-27 16:18:50 +00005628 if (Comp != CI) {// Comparing against a bit that we know is zero.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005629 bool IsICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
Reid Spencer579dca12007-01-12 04:24:46 +00005630 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
Chris Lattnerf63f6472004-09-27 16:18:50 +00005631 return ReplaceInstUsesWith(I, Cst);
5632 }
Misha Brukmanfd939082005-04-21 23:48:37 +00005633
Chris Lattnerf63f6472004-09-27 16:18:50 +00005634 if (LHSI->hasOneUse() || CI->isNullValue()) {
Reid Spencerb83eb642006-10-20 07:07:24 +00005635 unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
Chris Lattner18d19ca2004-09-28 18:22:15 +00005636
Chris Lattnerf63f6472004-09-27 16:18:50 +00005637 // Otherwise strength reduce the shift into an and.
5638 uint64_t Val = ~0ULL; // All ones.
5639 Val <<= ShAmtVal; // Shift over to the right spot.
Reid Spencerc5b206b2006-12-31 05:48:39 +00005640 Val &= ~0ULL >> (64-TypeBits);
5641 Constant *Mask = ConstantInt::get(CI->getType(), Val);
Misha Brukmanfd939082005-04-21 23:48:37 +00005642
Chris Lattnerf63f6472004-09-27 16:18:50 +00005643 Instruction *AndI =
5644 BinaryOperator::createAnd(LHSI->getOperand(0),
5645 Mask, LHSI->getName()+".mask");
5646 Value *And = InsertNewInstBefore(AndI, I);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005647 return new ICmpInst(I.getPredicate(), And,
Chris Lattnerf63f6472004-09-27 16:18:50 +00005648 ConstantExpr::getShl(CI, ShAmt));
5649 }
Chris Lattnerf63f6472004-09-27 16:18:50 +00005650 }
5651 }
5652 break;
Chris Lattner0c967662004-09-24 15:21:34 +00005653
Reid Spencer1628cec2006-10-26 06:15:43 +00005654 case Instruction::SDiv:
5655 case Instruction::UDiv:
Reid Spencere4d87aa2006-12-23 06:05:41 +00005656 // Fold: icmp pred ([us]div X, C1), C2 -> range test
Reid Spencer1628cec2006-10-26 06:15:43 +00005657 // Fold this div into the comparison, producing a range check.
5658 // Determine, based on the divide type, what the range is being
5659 // checked. If there is an overflow on the low or high side, remember
5660 // it, otherwise compute the range [low, hi) bounding the new value.
5661 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattnera96879a2004-09-29 17:40:11 +00005662 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00005663 // FIXME: If the operand types don't match the type of the divide
5664 // then don't attempt this transform. The code below doesn't have the
5665 // logic to deal with a signed divide and an unsigned compare (and
5666 // vice versa). This is because (x /s C1) <s C2 produces different
5667 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
5668 // (x /u C1) <u C2. Simply casting the operands and result won't
5669 // work. :( The if statement below tests that condition and bails
5670 // if it finds it.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005671 bool DivIsSigned = LHSI->getOpcode() == Instruction::SDiv;
5672 if (!I.isEquality() && DivIsSigned != I.isSignedPredicate())
Reid Spencer1628cec2006-10-26 06:15:43 +00005673 break;
5674
5675 // Initialize the variables that will indicate the nature of the
5676 // range check.
5677 bool LoOverflow = false, HiOverflow = false;
Chris Lattnera96879a2004-09-29 17:40:11 +00005678 ConstantInt *LoBound = 0, *HiBound = 0;
5679
Reid Spencer1628cec2006-10-26 06:15:43 +00005680 // Compute Prod = CI * DivRHS. We are essentially solving an equation
5681 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
5682 // C2 (CI). By solving for X we can turn this into a range check
5683 // instead of computing a divide.
5684 ConstantInt *Prod =
5685 cast<ConstantInt>(ConstantExpr::getMul(CI, DivRHS));
Chris Lattnera96879a2004-09-29 17:40:11 +00005686
Reid Spencer1628cec2006-10-26 06:15:43 +00005687 // Determine if the product overflows by seeing if the product is
5688 // not equal to the divide. Make sure we do the same kind of divide
5689 // as in the LHS instruction that we're folding.
5690 bool ProdOV = !DivRHS->isNullValue() &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00005691 (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
Reid Spencer1628cec2006-10-26 06:15:43 +00005692 ConstantExpr::getUDiv(Prod, DivRHS)) != CI;
5693
Reid Spencere4d87aa2006-12-23 06:05:41 +00005694 // Get the ICmp opcode
5695 ICmpInst::Predicate predicate = I.getPredicate();
Chris Lattner6a9fdfa2004-10-11 19:40:04 +00005696
Reid Spencer1628cec2006-10-26 06:15:43 +00005697 if (DivRHS->isNullValue()) {
5698 // Don't hack on divide by zeros!
Reid Spencere4d87aa2006-12-23 06:05:41 +00005699 } else if (!DivIsSigned) { // udiv
Chris Lattnera96879a2004-09-29 17:40:11 +00005700 LoBound = Prod;
5701 LoOverflow = ProdOV;
5702 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
Reid Spencer5a1e3e12007-03-19 20:58:18 +00005703 } else if (DivRHS->getValue().isPositive()) { // Divisor is > 0.
Chris Lattnera96879a2004-09-29 17:40:11 +00005704 if (CI->isNullValue()) { // (X / pos) op 0
5705 // Can't overflow.
5706 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
5707 HiBound = DivRHS;
Reid Spencer5a1e3e12007-03-19 20:58:18 +00005708 } else if (CI->getValue().isPositive()) { // (X / pos) op pos
Chris Lattnera96879a2004-09-29 17:40:11 +00005709 LoBound = Prod;
5710 LoOverflow = ProdOV;
5711 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
5712 } else { // (X / pos) op neg
5713 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
5714 LoOverflow = AddWithOverflow(LoBound, Prod,
5715 cast<ConstantInt>(DivRHSH));
5716 HiBound = Prod;
5717 HiOverflow = ProdOV;
5718 }
Reid Spencer1628cec2006-10-26 06:15:43 +00005719 } else { // Divisor is < 0.
Chris Lattnera96879a2004-09-29 17:40:11 +00005720 if (CI->isNullValue()) { // (X / neg) op 0
5721 LoBound = AddOne(DivRHS);
5722 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner56625032005-06-17 02:05:55 +00005723 if (HiBound == DivRHS)
Reid Spencer1628cec2006-10-26 06:15:43 +00005724 LoBound = 0; // - INTMIN = INTMIN
Reid Spencer5a1e3e12007-03-19 20:58:18 +00005725 } else if (CI->getValue().isPositive()) { // (X / neg) op pos
Chris Lattnera96879a2004-09-29 17:40:11 +00005726 HiOverflow = LoOverflow = ProdOV;
5727 if (!LoOverflow)
5728 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
5729 HiBound = AddOne(Prod);
5730 } else { // (X / neg) op neg
5731 LoBound = Prod;
5732 LoOverflow = HiOverflow = ProdOV;
5733 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
5734 }
Chris Lattner340a05f2004-10-08 19:15:44 +00005735
Chris Lattner6a9fdfa2004-10-11 19:40:04 +00005736 // Dividing by a negate swaps the condition.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005737 predicate = ICmpInst::getSwappedPredicate(predicate);
Chris Lattnera96879a2004-09-29 17:40:11 +00005738 }
5739
5740 if (LoBound) {
5741 Value *X = LHSI->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005742 switch (predicate) {
5743 default: assert(0 && "Unhandled icmp opcode!");
5744 case ICmpInst::ICMP_EQ:
Chris Lattnera96879a2004-09-29 17:40:11 +00005745 if (LoOverflow && HiOverflow)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005746 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattnera96879a2004-09-29 17:40:11 +00005747 else if (HiOverflow)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005748 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
5749 ICmpInst::ICMP_UGE, X, LoBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00005750 else if (LoOverflow)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005751 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
5752 ICmpInst::ICMP_ULT, X, HiBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00005753 else
Reid Spencere4d87aa2006-12-23 06:05:41 +00005754 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned,
5755 true, I);
5756 case ICmpInst::ICMP_NE:
Chris Lattnera96879a2004-09-29 17:40:11 +00005757 if (LoOverflow && HiOverflow)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005758 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnera96879a2004-09-29 17:40:11 +00005759 else if (HiOverflow)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005760 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
5761 ICmpInst::ICMP_ULT, X, LoBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00005762 else if (LoOverflow)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005763 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
5764 ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00005765 else
Reid Spencere4d87aa2006-12-23 06:05:41 +00005766 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned,
5767 false, I);
5768 case ICmpInst::ICMP_ULT:
5769 case ICmpInst::ICMP_SLT:
Chris Lattnera96879a2004-09-29 17:40:11 +00005770 if (LoOverflow)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005771 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005772 return new ICmpInst(predicate, X, LoBound);
5773 case ICmpInst::ICMP_UGT:
5774 case ICmpInst::ICMP_SGT:
Chris Lattnera96879a2004-09-29 17:40:11 +00005775 if (HiOverflow)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005776 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005777 if (predicate == ICmpInst::ICMP_UGT)
5778 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
5779 else
5780 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00005781 }
5782 }
5783 }
5784 break;
Chris Lattner648e3bc2004-09-23 21:52:49 +00005785 }
Misha Brukmanfd939082005-04-21 23:48:37 +00005786
Reid Spencere4d87aa2006-12-23 06:05:41 +00005787 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
Chris Lattner65b72ba2006-09-18 04:22:48 +00005788 if (I.isEquality()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005789 bool isICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
Chris Lattnerbc5d4142003-07-23 17:02:11 +00005790
Reid Spencerb83eb642006-10-20 07:07:24 +00005791 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
5792 // the second operand is a constant, simplify a bit.
Chris Lattner934754b2003-08-13 05:33:12 +00005793 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
5794 switch (BO->getOpcode()) {
Reid Spencerb83eb642006-10-20 07:07:24 +00005795 case Instruction::SRem:
5796 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
5797 if (CI->isNullValue() && isa<ConstantInt>(BO->getOperand(1)) &&
5798 BO->hasOneUse()) {
5799 int64_t V = cast<ConstantInt>(BO->getOperand(1))->getSExtValue();
5800 if (V > 1 && isPowerOf2_64(V)) {
Reid Spencer0a783f72006-11-02 01:53:59 +00005801 Value *NewRem = InsertNewInstBefore(BinaryOperator::createURem(
5802 BO->getOperand(0), BO->getOperand(1), BO->getName()), I);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005803 return new ICmpInst(I.getPredicate(), NewRem,
5804 Constant::getNullValue(BO->getType()));
Chris Lattner3571b722004-07-06 07:38:18 +00005805 }
Chris Lattnerbcd7db52005-08-02 19:16:58 +00005806 }
Misha Brukmanfd939082005-04-21 23:48:37 +00005807 break;
Chris Lattner934754b2003-08-13 05:33:12 +00005808 case Instruction::Add:
Chris Lattner15d58b62004-06-27 22:51:36 +00005809 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
5810 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattner3d834bf2004-09-21 21:35:23 +00005811 if (BO->hasOneUse())
Reid Spencere4d87aa2006-12-23 06:05:41 +00005812 return new ICmpInst(I.getPredicate(), BO->getOperand(0),
5813 ConstantExpr::getSub(CI, BOp1C));
Chris Lattner15d58b62004-06-27 22:51:36 +00005814 } else if (CI->isNullValue()) {
Chris Lattner934754b2003-08-13 05:33:12 +00005815 // Replace ((add A, B) != 0) with (A != -B) if A or B is
5816 // efficiently invertible, or if the add has just this one use.
5817 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Misha Brukmanfd939082005-04-21 23:48:37 +00005818
Chris Lattner934754b2003-08-13 05:33:12 +00005819 if (Value *NegVal = dyn_castNegVal(BOp1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005820 return new ICmpInst(I.getPredicate(), BOp0, NegVal);
Chris Lattner934754b2003-08-13 05:33:12 +00005821 else if (Value *NegVal = dyn_castNegVal(BOp0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005822 return new ICmpInst(I.getPredicate(), NegVal, BOp1);
Chris Lattnerfd059242003-10-15 16:48:29 +00005823 else if (BO->hasOneUse()) {
Chris Lattner6934a042007-02-11 01:23:03 +00005824 Instruction *Neg = BinaryOperator::createNeg(BOp1);
Chris Lattner934754b2003-08-13 05:33:12 +00005825 InsertNewInstBefore(Neg, I);
Chris Lattner6934a042007-02-11 01:23:03 +00005826 Neg->takeName(BO);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005827 return new ICmpInst(I.getPredicate(), BOp0, Neg);
Chris Lattner934754b2003-08-13 05:33:12 +00005828 }
5829 }
5830 break;
5831 case Instruction::Xor:
5832 // For the xor case, we can xor two constants together, eliminating
5833 // the explicit xor.
5834 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005835 return new ICmpInst(I.getPredicate(), BO->getOperand(0),
5836 ConstantExpr::getXor(CI, BOC));
Chris Lattner934754b2003-08-13 05:33:12 +00005837
5838 // FALLTHROUGH
5839 case Instruction::Sub:
5840 // Replace (([sub|xor] A, B) != 0) with (A != B)
5841 if (CI->isNullValue())
Reid Spencere4d87aa2006-12-23 06:05:41 +00005842 return new ICmpInst(I.getPredicate(), BO->getOperand(0),
5843 BO->getOperand(1));
Chris Lattner934754b2003-08-13 05:33:12 +00005844 break;
5845
5846 case Instruction::Or:
5847 // If bits are being or'd in that are not present in the constant we
5848 // are comparing against, then the comparison could never succeed!
Chris Lattner7c4049c2004-01-12 19:35:11 +00005849 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattner448c3232004-06-10 02:12:35 +00005850 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattner48595f12004-06-10 02:07:29 +00005851 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Reid Spencer579dca12007-01-12 04:24:46 +00005852 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5853 isICMP_NE));
Chris Lattner7c4049c2004-01-12 19:35:11 +00005854 }
Chris Lattner934754b2003-08-13 05:33:12 +00005855 break;
5856
5857 case Instruction::And:
5858 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerbc5d4142003-07-23 17:02:11 +00005859 // If bits are being compared against that are and'd out, then the
5860 // comparison can never succeed!
Chris Lattner448c3232004-06-10 02:12:35 +00005861 if (!ConstantExpr::getAnd(CI,
5862 ConstantExpr::getNot(BOC))->isNullValue())
Reid Spencer579dca12007-01-12 04:24:46 +00005863 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5864 isICMP_NE));
Chris Lattner934754b2003-08-13 05:33:12 +00005865
Chris Lattner457dd822004-06-09 07:59:58 +00005866 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattner3285a6f2004-06-10 02:33:20 +00005867 if (CI == BOC && isOneBitSet(CI))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005868 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
5869 ICmpInst::ICMP_NE, Op0,
5870 Constant::getNullValue(CI->getType()));
Chris Lattner457dd822004-06-09 07:59:58 +00005871
Reid Spencere4d87aa2006-12-23 06:05:41 +00005872 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattner934754b2003-08-13 05:33:12 +00005873 if (isSignBit(BOC)) {
5874 Value *X = BO->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005875 Constant *Zero = Constant::getNullValue(X->getType());
5876 ICmpInst::Predicate pred = isICMP_NE ?
5877 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
5878 return new ICmpInst(pred, X, Zero);
Chris Lattner934754b2003-08-13 05:33:12 +00005879 }
Misha Brukmanfd939082005-04-21 23:48:37 +00005880
Chris Lattner83c4ec02004-09-27 19:29:18 +00005881 // ((X & ~7) == 0) --> X < 8
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00005882 if (CI->isNullValue() && isHighOnes(BOC)) {
5883 Value *X = BO->getOperand(0);
Chris Lattner83c4ec02004-09-27 19:29:18 +00005884 Constant *NegX = ConstantExpr::getNeg(BOC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005885 ICmpInst::Predicate pred = isICMP_NE ?
5886 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
5887 return new ICmpInst(pred, X, NegX);
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00005888 }
5889
Chris Lattnerbc5d4142003-07-23 17:02:11 +00005890 }
Chris Lattner934754b2003-08-13 05:33:12 +00005891 default: break;
5892 }
Chris Lattner458cf462006-11-29 05:02:16 +00005893 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op0)) {
5894 // Handle set{eq|ne} <intrinsic>, intcst.
5895 switch (II->getIntrinsicID()) {
5896 default: break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005897 case Intrinsic::bswap_i16:
5898 // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
Chris Lattnerdbab3862007-03-02 21:28:56 +00005899 AddToWorkList(II); // Dead?
Chris Lattner458cf462006-11-29 05:02:16 +00005900 I.setOperand(0, II->getOperand(1));
Reid Spencerc5b206b2006-12-31 05:48:39 +00005901 I.setOperand(1, ConstantInt::get(Type::Int16Ty,
Chris Lattner458cf462006-11-29 05:02:16 +00005902 ByteSwap_16(CI->getZExtValue())));
5903 return &I;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005904 case Intrinsic::bswap_i32:
5905 // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
Chris Lattnerdbab3862007-03-02 21:28:56 +00005906 AddToWorkList(II); // Dead?
Chris Lattner458cf462006-11-29 05:02:16 +00005907 I.setOperand(0, II->getOperand(1));
Reid Spencerc5b206b2006-12-31 05:48:39 +00005908 I.setOperand(1, ConstantInt::get(Type::Int32Ty,
Chris Lattner458cf462006-11-29 05:02:16 +00005909 ByteSwap_32(CI->getZExtValue())));
5910 return &I;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005911 case Intrinsic::bswap_i64:
5912 // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
Chris Lattnerdbab3862007-03-02 21:28:56 +00005913 AddToWorkList(II); // Dead?
Chris Lattner458cf462006-11-29 05:02:16 +00005914 I.setOperand(0, II->getOperand(1));
Reid Spencerc5b206b2006-12-31 05:48:39 +00005915 I.setOperand(1, ConstantInt::get(Type::Int64Ty,
Chris Lattner458cf462006-11-29 05:02:16 +00005916 ByteSwap_64(CI->getZExtValue())));
5917 return &I;
5918 }
Chris Lattner934754b2003-08-13 05:33:12 +00005919 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00005920 } else { // Not a ICMP_EQ/ICMP_NE
5921 // If the LHS is a cast from an integral value of the same size, then
5922 // since we know the RHS is a constant, try to simlify.
Chris Lattnerc5943fb2004-02-23 07:16:20 +00005923 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
5924 Value *CastOp = Cast->getOperand(0);
5925 const Type *SrcTy = CastOp->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00005926 unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
Chris Lattner42a75512007-01-15 02:27:26 +00005927 if (SrcTy->isInteger() &&
Chris Lattner484d3cf2005-04-24 06:59:08 +00005928 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005929 // If this is an unsigned comparison, try to make the comparison use
5930 // smaller constant values.
5931 switch (I.getPredicate()) {
5932 default: break;
5933 case ICmpInst::ICMP_ULT: { // X u< 128 => X s> -1
5934 ConstantInt *CUI = cast<ConstantInt>(CI);
5935 if (CUI->getZExtValue() == 1ULL << (SrcTySize-1))
5936 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp,
Reid Spencer62aa9052007-03-01 19:33:52 +00005937 ConstantInt::get(SrcTy, -1ULL));
Reid Spencere4d87aa2006-12-23 06:05:41 +00005938 break;
5939 }
5940 case ICmpInst::ICMP_UGT: { // X u> 127 => X s< 0
5941 ConstantInt *CUI = cast<ConstantInt>(CI);
5942 if (CUI->getZExtValue() == (1ULL << (SrcTySize-1))-1)
5943 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp,
5944 Constant::getNullValue(SrcTy));
5945 break;
5946 }
Chris Lattnerc5943fb2004-02-23 07:16:20 +00005947 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00005948
Chris Lattnerc5943fb2004-02-23 07:16:20 +00005949 }
5950 }
Chris Lattner40f5d702003-06-04 05:10:11 +00005951 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00005952 }
5953
Reid Spencere4d87aa2006-12-23 06:05:41 +00005954 // Handle icmp with constant RHS
Chris Lattner6970b662005-04-23 15:31:55 +00005955 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5956 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5957 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00005958 case Instruction::GetElementPtr:
5959 if (RHSC->isNullValue()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005960 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattner9fb25db2005-05-01 04:42:15 +00005961 bool isAllZeros = true;
5962 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5963 if (!isa<Constant>(LHSI->getOperand(i)) ||
5964 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5965 isAllZeros = false;
5966 break;
5967 }
5968 if (isAllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005969 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Chris Lattner9fb25db2005-05-01 04:42:15 +00005970 Constant::getNullValue(LHSI->getOperand(0)->getType()));
5971 }
5972 break;
5973
Chris Lattner6970b662005-04-23 15:31:55 +00005974 case Instruction::PHI:
5975 if (Instruction *NV = FoldOpIntoPhi(I))
5976 return NV;
5977 break;
5978 case Instruction::Select:
5979 // If either operand of the select is a constant, we can fold the
5980 // comparison into the select arms, which will cause one to be
5981 // constant folded and the select turned into a bitwise or.
5982 Value *Op1 = 0, *Op2 = 0;
5983 if (LHSI->hasOneUse()) {
5984 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5985 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005986 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5987 // Insert a new ICmp of the other select operand.
5988 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5989 LHSI->getOperand(2), RHSC,
5990 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00005991 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5992 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005993 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5994 // Insert a new ICmp of the other select operand.
5995 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5996 LHSI->getOperand(1), RHSC,
5997 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00005998 }
5999 }
Jeff Cohen9d809302005-04-23 21:38:35 +00006000
Chris Lattner6970b662005-04-23 15:31:55 +00006001 if (Op1)
6002 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
6003 break;
6004 }
6005 }
6006
Reid Spencere4d87aa2006-12-23 06:05:41 +00006007 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Chris Lattner574da9b2005-01-13 20:14:25 +00006008 if (User *GEP = dyn_castGetElementPtr(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006009 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006010 return NI;
6011 if (User *GEP = dyn_castGetElementPtr(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006012 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6013 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006014 return NI;
6015
Reid Spencere4d87aa2006-12-23 06:05:41 +00006016 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner57d86372007-01-06 01:45:59 +00006017 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
6018 // now.
6019 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6020 if (isa<PointerType>(Op0->getType()) &&
6021 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006022 // We keep moving the cast from the left operand over to the right
6023 // operand, where it can often be eliminated completely.
Chris Lattner57d86372007-01-06 01:45:59 +00006024 Op0 = CI->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006025
Chris Lattner57d86372007-01-06 01:45:59 +00006026 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6027 // so eliminate it as well.
6028 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6029 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006030
Chris Lattnerde90b762003-11-03 04:25:02 +00006031 // If Op1 is a constant, we can fold the cast into the constant.
Chris Lattner57d86372007-01-06 01:45:59 +00006032 if (Op0->getType() != Op1->getType())
Chris Lattnerde90b762003-11-03 04:25:02 +00006033 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Reid Spencerd977d862006-12-12 23:36:14 +00006034 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00006035 } else {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006036 // Otherwise, cast the RHS right before the icmp
Reid Spencer17212df2006-12-12 09:18:51 +00006037 Op1 = InsertCastBefore(Instruction::BitCast, Op1, Op0->getType(), I);
Chris Lattnerde90b762003-11-03 04:25:02 +00006038 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00006039 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattnerde90b762003-11-03 04:25:02 +00006040 }
Chris Lattner57d86372007-01-06 01:45:59 +00006041 }
6042
6043 if (isa<CastInst>(Op0)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006044 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner68708052003-11-03 05:17:03 +00006045 // This comes up when you have code like
6046 // int X = A < B;
6047 // if (X) ...
6048 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00006049 // with a constant or another cast from the same type.
6050 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006051 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattner484d3cf2005-04-24 06:59:08 +00006052 return R;
Chris Lattner68708052003-11-03 05:17:03 +00006053 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006054
Chris Lattner65b72ba2006-09-18 04:22:48 +00006055 if (I.isEquality()) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006056 Value *A, *B, *C, *D;
6057 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
6058 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6059 Value *OtherVal = A == Op1 ? B : A;
6060 return new ICmpInst(I.getPredicate(), OtherVal,
6061 Constant::getNullValue(A->getType()));
6062 }
6063
6064 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
6065 // A^c1 == C^c2 --> A == C^(c1^c2)
6066 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
6067 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
6068 if (Op1->hasOneUse()) {
6069 Constant *NC = ConstantExpr::getXor(C1, C2);
6070 Instruction *Xor = BinaryOperator::createXor(C, NC, "tmp");
6071 return new ICmpInst(I.getPredicate(), A,
6072 InsertNewInstBefore(Xor, I));
6073 }
6074
6075 // A^B == A^D -> B == D
6076 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6077 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6078 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6079 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
6080 }
6081 }
6082
6083 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
6084 (A == Op0 || B == Op0)) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00006085 // A == (A^B) -> B == 0
6086 Value *OtherVal = A == Op0 ? B : A;
Reid Spencere4d87aa2006-12-23 06:05:41 +00006087 return new ICmpInst(I.getPredicate(), OtherVal,
6088 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006089 }
6090 if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00006091 // (A-B) == A -> B == 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00006092 return new ICmpInst(I.getPredicate(), B,
6093 Constant::getNullValue(B->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006094 }
6095 if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00006096 // A == (A-B) -> B == 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00006097 return new ICmpInst(I.getPredicate(), B,
6098 Constant::getNullValue(B->getType()));
Chris Lattner26ab9a92006-02-27 01:44:11 +00006099 }
Chris Lattner9c2328e2006-11-14 06:06:06 +00006100
Chris Lattner9c2328e2006-11-14 06:06:06 +00006101 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6102 if (Op0->hasOneUse() && Op1->hasOneUse() &&
6103 match(Op0, m_And(m_Value(A), m_Value(B))) &&
6104 match(Op1, m_And(m_Value(C), m_Value(D)))) {
6105 Value *X = 0, *Y = 0, *Z = 0;
6106
6107 if (A == C) {
6108 X = B; Y = D; Z = A;
6109 } else if (A == D) {
6110 X = B; Y = C; Z = A;
6111 } else if (B == C) {
6112 X = A; Y = D; Z = B;
6113 } else if (B == D) {
6114 X = A; Y = C; Z = B;
6115 }
6116
6117 if (X) { // Build (X^Y) & Z
6118 Op1 = InsertNewInstBefore(BinaryOperator::createXor(X, Y, "tmp"), I);
6119 Op1 = InsertNewInstBefore(BinaryOperator::createAnd(Op1, Z, "tmp"), I);
6120 I.setOperand(0, Op1);
6121 I.setOperand(1, Constant::getNullValue(Op1->getType()));
6122 return &I;
6123 }
6124 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006125 }
Chris Lattner7e708292002-06-25 16:13:24 +00006126 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006127}
6128
Reid Spencere4d87aa2006-12-23 06:05:41 +00006129// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
Chris Lattner484d3cf2005-04-24 06:59:08 +00006130// We only handle extending casts so far.
6131//
Reid Spencere4d87aa2006-12-23 06:05:41 +00006132Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
6133 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +00006134 Value *LHSCIOp = LHSCI->getOperand(0);
6135 const Type *SrcTy = LHSCIOp->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00006136 const Type *DestTy = LHSCI->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00006137 Value *RHSCIOp;
6138
Reid Spencere4d87aa2006-12-23 06:05:41 +00006139 // We only handle extension cast instructions, so far. Enforce this.
6140 if (LHSCI->getOpcode() != Instruction::ZExt &&
6141 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattnerb352fa52005-01-17 03:20:02 +00006142 return 0;
6143
Reid Spencere4d87aa2006-12-23 06:05:41 +00006144 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
6145 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattner484d3cf2005-04-24 06:59:08 +00006146
Reid Spencere4d87aa2006-12-23 06:05:41 +00006147 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00006148 // Not an extension from the same type?
6149 RHSCIOp = CI->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006150 if (RHSCIOp->getType() != LHSCIOp->getType())
6151 return 0;
Chris Lattnera5c5e772007-01-13 23:11:38 +00006152
6153 // If the signedness of the two compares doesn't agree (i.e. one is a sext
6154 // and the other is a zext), then we can't handle this.
6155 if (CI->getOpcode() != LHSCI->getOpcode())
6156 return 0;
6157
6158 // Likewise, if the signedness of the [sz]exts and the compare don't match,
6159 // then we can't handle this.
6160 if (isSignedExt != isSignedCmp && !ICI.isEquality())
6161 return 0;
6162
6163 // Okay, just insert a compare of the reduced operands now!
6164 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer6731d5c2004-11-28 21:31:15 +00006165 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00006166
Reid Spencere4d87aa2006-12-23 06:05:41 +00006167 // If we aren't dealing with a constant on the RHS, exit early
6168 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
6169 if (!CI)
6170 return 0;
6171
6172 // Compute the constant that would happen if we truncated to SrcTy then
6173 // reextended to DestTy.
6174 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
6175 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
6176
6177 // If the re-extended constant didn't change...
6178 if (Res2 == CI) {
6179 // Make sure that sign of the Cmp and the sign of the Cast are the same.
6180 // For example, we might have:
6181 // %A = sext short %X to uint
6182 // %B = icmp ugt uint %A, 1330
6183 // It is incorrect to transform this into
6184 // %B = icmp ugt short %X, 1330
6185 // because %A may have negative value.
6186 //
6187 // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
6188 // OR operation is EQ/NE.
Reid Spencer4fe16d62007-01-11 18:21:29 +00006189 if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
Reid Spencere4d87aa2006-12-23 06:05:41 +00006190 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
6191 else
6192 return 0;
6193 }
6194
6195 // The re-extended constant changed so the constant cannot be represented
6196 // in the shorter type. Consequently, we cannot emit a simple comparison.
6197
6198 // First, handle some easy cases. We know the result cannot be equal at this
6199 // point so handle the ICI.isEquality() cases
6200 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006201 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006202 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006203 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006204
6205 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
6206 // should have been folded away previously and not enter in here.
6207 Value *Result;
6208 if (isSignedCmp) {
6209 // We're performing a signed comparison.
6210 if (cast<ConstantInt>(CI)->getSExtValue() < 0)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006211 Result = ConstantInt::getFalse(); // X < (small) --> false
Reid Spencere4d87aa2006-12-23 06:05:41 +00006212 else
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006213 Result = ConstantInt::getTrue(); // X < (large) --> true
Reid Spencere4d87aa2006-12-23 06:05:41 +00006214 } else {
6215 // We're performing an unsigned comparison.
6216 if (isSignedExt) {
6217 // We're performing an unsigned comp with a sign extended value.
6218 // This is true if the input is >= 0. [aka >s -1]
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006219 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006220 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
6221 NegOne, ICI.getName()), ICI);
6222 } else {
6223 // Unsigned extend & unsigned compare -> always true.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006224 Result = ConstantInt::getTrue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00006225 }
6226 }
6227
6228 // Finally, return the value computed.
6229 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
6230 ICI.getPredicate() == ICmpInst::ICMP_SLT) {
6231 return ReplaceInstUsesWith(ICI, Result);
6232 } else {
6233 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
6234 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
6235 "ICmp should be folded!");
6236 if (Constant *CI = dyn_cast<Constant>(Result))
6237 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
6238 else
6239 return BinaryOperator::createNot(Result);
6240 }
Chris Lattner484d3cf2005-04-24 06:59:08 +00006241}
Chris Lattner3f5b8772002-05-06 16:14:14 +00006242
Reid Spencer832254e2007-02-02 02:16:23 +00006243Instruction *InstCombiner::visitShl(BinaryOperator &I) {
6244 return commonShiftTransforms(I);
6245}
6246
6247Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
6248 return commonShiftTransforms(I);
6249}
6250
6251Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
6252 return commonShiftTransforms(I);
6253}
6254
6255Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
6256 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00006257 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00006258
6259 // shl X, 0 == X and shr X, 0 == X
6260 // shl 0, X == 0 and shr 0, X == 0
Reid Spencer832254e2007-02-02 02:16:23 +00006261 if (Op1 == Constant::getNullValue(Op1->getType()) ||
Chris Lattner233f7dc2002-08-12 21:17:25 +00006262 Op0 == Constant::getNullValue(Op0->getType()))
6263 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006264
Reid Spencere4d87aa2006-12-23 06:05:41 +00006265 if (isa<UndefValue>(Op0)) {
6266 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00006267 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006268 else // undef << X -> 0, undef >>u X -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00006269 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6270 }
6271 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006272 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
6273 return ReplaceInstUsesWith(I, Op0);
6274 else // X << undef, X >>u undef -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00006275 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00006276 }
6277
Chris Lattnerde2b6602006-11-10 23:38:52 +00006278 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
6279 if (I.getOpcode() == Instruction::AShr)
Reid Spencerb83eb642006-10-20 07:07:24 +00006280 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Chris Lattnerde2b6602006-11-10 23:38:52 +00006281 if (CSI->isAllOnesValue())
Chris Lattnerdf17af12003-08-12 21:53:41 +00006282 return ReplaceInstUsesWith(I, CSI);
6283
Chris Lattner2eefe512004-04-09 19:05:30 +00006284 // Try to fold constant and into select arguments.
6285 if (isa<Constant>(Op0))
6286 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00006287 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00006288 return R;
6289
Chris Lattner120347e2005-05-08 17:34:56 +00006290 // See if we can turn a signed shr into an unsigned shr.
Chris Lattner65b72ba2006-09-18 04:22:48 +00006291 if (I.isArithmeticShift()) {
Chris Lattner3bedbd92006-02-07 07:27:52 +00006292 if (MaskedValueIsZero(Op0,
6293 1ULL << (I.getType()->getPrimitiveSizeInBits()-1))) {
Reid Spencercc46cdb2007-02-02 14:08:20 +00006294 return BinaryOperator::createLShr(Op0, Op1, I.getName());
Chris Lattner120347e2005-05-08 17:34:56 +00006295 }
6296 }
Jeff Cohen00b168892005-07-27 06:12:32 +00006297
Reid Spencerb83eb642006-10-20 07:07:24 +00006298 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00006299 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
6300 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006301 return 0;
6302}
6303
Reid Spencerb83eb642006-10-20 07:07:24 +00006304Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00006305 BinaryOperator &I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006306 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006307
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006308 // See if we can simplify any instructions used by the instruction whose sole
6309 // purpose is to compute bits we don't care about.
6310 uint64_t KnownZero, KnownOne;
Reid Spencerc1030572007-01-19 21:13:56 +00006311 if (SimplifyDemandedBits(&I, cast<IntegerType>(I.getType())->getBitMask(),
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006312 KnownZero, KnownOne))
6313 return &I;
6314
Chris Lattner4d5542c2006-01-06 07:12:35 +00006315 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
6316 // of a signed value.
6317 //
6318 unsigned TypeBits = Op0->getType()->getPrimitiveSizeInBits();
Reid Spencerb83eb642006-10-20 07:07:24 +00006319 if (Op1->getZExtValue() >= TypeBits) {
Chris Lattner0737c242007-02-02 05:29:55 +00006320 if (I.getOpcode() != Instruction::AShr)
Chris Lattner4d5542c2006-01-06 07:12:35 +00006321 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
6322 else {
Chris Lattner0737c242007-02-02 05:29:55 +00006323 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00006324 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00006325 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006326 }
6327
6328 // ((X*C1) << C2) == (X * (C1 << C2))
6329 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
6330 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
6331 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
6332 return BinaryOperator::createMul(BO->getOperand(0),
6333 ConstantExpr::getShl(BOOp, Op1));
6334
6335 // Try to fold constant and into select arguments.
6336 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
6337 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6338 return R;
6339 if (isa<PHINode>(Op0))
6340 if (Instruction *NV = FoldOpIntoPhi(I))
6341 return NV;
6342
6343 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00006344 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
6345 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
6346 Value *V1, *V2;
6347 ConstantInt *CC;
6348 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00006349 default: break;
6350 case Instruction::Add:
6351 case Instruction::And:
6352 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00006353 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00006354 // These operators commute.
6355 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00006356 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
6357 match(Op0BO->getOperand(1),
Chris Lattner4d5542c2006-01-06 07:12:35 +00006358 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Reid Spencercc46cdb2007-02-02 14:08:20 +00006359 Instruction *YS = BinaryOperator::createShl(
Chris Lattner4d5542c2006-01-06 07:12:35 +00006360 Op0BO->getOperand(0), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00006361 Op0BO->getName());
6362 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006363 Instruction *X =
6364 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
6365 Op0BO->getOperand(1)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006366 InsertNewInstBefore(X, I); // (X + (Y << C))
6367 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner4d5542c2006-01-06 07:12:35 +00006368 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner150f12a2005-09-18 06:30:59 +00006369 return BinaryOperator::createAnd(X, C2);
6370 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006371
Chris Lattner150f12a2005-09-18 06:30:59 +00006372 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00006373 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00006374 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00006375 match(Op0BOOp1,
6376 m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
Chris Lattner3c698492007-03-05 00:11:19 +00006377 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
6378 V2 == Op1) {
Reid Spencercc46cdb2007-02-02 14:08:20 +00006379 Instruction *YS = BinaryOperator::createShl(
Reid Spencer832254e2007-02-02 02:16:23 +00006380 Op0BO->getOperand(0), Op1,
6381 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006382 InsertNewInstBefore(YS, I); // (Y << C)
6383 Instruction *XM =
Chris Lattner4d5542c2006-01-06 07:12:35 +00006384 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00006385 V1->getName()+".mask");
6386 InsertNewInstBefore(XM, I); // X & (CC << C)
6387
6388 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
6389 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00006390 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006391
Reid Spencera07cb7d2007-02-02 14:41:37 +00006392 // FALL THROUGH.
6393 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00006394 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00006395 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6396 match(Op0BO->getOperand(0),
Chris Lattner4d5542c2006-01-06 07:12:35 +00006397 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Reid Spencercc46cdb2007-02-02 14:08:20 +00006398 Instruction *YS = BinaryOperator::createShl(
Reid Spencer832254e2007-02-02 02:16:23 +00006399 Op0BO->getOperand(1), Op1,
6400 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006401 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006402 Instruction *X =
Chris Lattner13d4ab42006-05-31 21:14:00 +00006403 BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006404 Op0BO->getOperand(0)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006405 InsertNewInstBefore(X, I); // (X + (Y << C))
6406 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner4d5542c2006-01-06 07:12:35 +00006407 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner150f12a2005-09-18 06:30:59 +00006408 return BinaryOperator::createAnd(X, C2);
6409 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006410
Chris Lattner13d4ab42006-05-31 21:14:00 +00006411 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00006412 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6413 match(Op0BO->getOperand(0),
6414 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner4d5542c2006-01-06 07:12:35 +00006415 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006416 cast<BinaryOperator>(Op0BO->getOperand(0))
6417 ->getOperand(0)->hasOneUse()) {
Reid Spencercc46cdb2007-02-02 14:08:20 +00006418 Instruction *YS = BinaryOperator::createShl(
Reid Spencer832254e2007-02-02 02:16:23 +00006419 Op0BO->getOperand(1), Op1,
6420 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006421 InsertNewInstBefore(YS, I); // (Y << C)
6422 Instruction *XM =
Chris Lattner4d5542c2006-01-06 07:12:35 +00006423 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00006424 V1->getName()+".mask");
6425 InsertNewInstBefore(XM, I); // X & (CC << C)
6426
Chris Lattner13d4ab42006-05-31 21:14:00 +00006427 return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00006428 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006429
Chris Lattner11021cb2005-09-18 05:12:10 +00006430 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00006431 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006432 }
6433
6434
6435 // If the operand is an bitwise operator with a constant RHS, and the
6436 // shift is the only use, we can pull it out of the shift.
6437 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
6438 bool isValid = true; // Valid only for And, Or, Xor
6439 bool highBitSet = false; // Transform if high bit of constant set?
6440
6441 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00006442 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00006443 case Instruction::Add:
6444 isValid = isLeftShift;
6445 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00006446 case Instruction::Or:
6447 case Instruction::Xor:
6448 highBitSet = false;
6449 break;
6450 case Instruction::And:
6451 highBitSet = true;
6452 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006453 }
6454
6455 // If this is a signed shift right, and the high bit is modified
6456 // by the logical operation, do not perform the transformation.
6457 // The highBitSet boolean indicates the value of the high bit of
6458 // the constant which would cause it to be modified for this
6459 // operation.
6460 //
Chris Lattnerb87056f2007-02-05 00:57:54 +00006461 if (isValid && !isLeftShift && I.getOpcode() == Instruction::AShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00006462 uint64_t Val = Op0C->getZExtValue();
Chris Lattner4d5542c2006-01-06 07:12:35 +00006463 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
6464 }
6465
6466 if (isValid) {
6467 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
6468
6469 Instruction *NewShift =
Chris Lattner6934a042007-02-11 01:23:03 +00006470 BinaryOperator::create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00006471 InsertNewInstBefore(NewShift, I);
Chris Lattner6934a042007-02-11 01:23:03 +00006472 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00006473
6474 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
6475 NewRHS);
6476 }
6477 }
6478 }
6479 }
6480
Chris Lattnerad0124c2006-01-06 07:52:12 +00006481 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00006482 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
6483 if (ShiftOp && !ShiftOp->isShift())
6484 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00006485
Reid Spencerb83eb642006-10-20 07:07:24 +00006486 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00006487 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Reid Spencerb83eb642006-10-20 07:07:24 +00006488 unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getZExtValue();
6489 unsigned ShiftAmt2 = (unsigned)Op1->getZExtValue();
Chris Lattnerb87056f2007-02-05 00:57:54 +00006490 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
6491 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
6492 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00006493
Chris Lattnerb87056f2007-02-05 00:57:54 +00006494 unsigned AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
6495 if (AmtSum > I.getType()->getPrimitiveSizeInBits())
6496 AmtSum = I.getType()->getPrimitiveSizeInBits();
6497
6498 const IntegerType *Ty = cast<IntegerType>(I.getType());
6499
6500 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00006501 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattnerb87056f2007-02-05 00:57:54 +00006502 return BinaryOperator::create(I.getOpcode(), X,
6503 ConstantInt::get(Ty, AmtSum));
6504 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
6505 I.getOpcode() == Instruction::AShr) {
6506 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
6507 return BinaryOperator::createLShr(X, ConstantInt::get(Ty, AmtSum));
6508 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
6509 I.getOpcode() == Instruction::LShr) {
6510 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
6511 Instruction *Shift =
6512 BinaryOperator::createAShr(X, ConstantInt::get(Ty, AmtSum));
6513 InsertNewInstBefore(Shift, I);
6514
6515 uint64_t Mask = Ty->getBitMask() >> ShiftAmt2;
6516 return BinaryOperator::createAnd(Shift, ConstantInt::get(Ty, Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00006517 }
6518
Chris Lattnerb87056f2007-02-05 00:57:54 +00006519 // Okay, if we get here, one shift must be left, and the other shift must be
6520 // right. See if the amounts are equal.
6521 if (ShiftAmt1 == ShiftAmt2) {
6522 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
6523 if (I.getOpcode() == Instruction::Shl) {
Chris Lattner4f3ebab2007-02-05 04:09:35 +00006524 uint64_t Mask = Ty->getBitMask() << ShiftAmt1;
Chris Lattnerb87056f2007-02-05 00:57:54 +00006525 return BinaryOperator::createAnd(X, ConstantInt::get(Ty, Mask));
6526 }
6527 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
6528 if (I.getOpcode() == Instruction::LShr) {
Chris Lattner4f3ebab2007-02-05 04:09:35 +00006529 uint64_t Mask = Ty->getBitMask() >> ShiftAmt1;
Chris Lattnerb87056f2007-02-05 00:57:54 +00006530 return BinaryOperator::createAnd(X, ConstantInt::get(Ty, Mask));
6531 }
6532 // We can simplify ((X << C) >>s C) into a trunc + sext.
6533 // NOTE: we could do this for any C, but that would make 'unusual' integer
6534 // types. For now, just stick to ones well-supported by the code
6535 // generators.
6536 const Type *SExtType = 0;
6537 switch (Ty->getBitWidth() - ShiftAmt1) {
6538 case 8 : SExtType = Type::Int8Ty; break;
6539 case 16: SExtType = Type::Int16Ty; break;
6540 case 32: SExtType = Type::Int32Ty; break;
6541 default: break;
6542 }
6543 if (SExtType) {
6544 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
6545 InsertNewInstBefore(NewTrunc, I);
6546 return new SExtInst(NewTrunc, Ty);
6547 }
6548 // Otherwise, we can't handle it yet.
6549 } else if (ShiftAmt1 < ShiftAmt2) {
6550 unsigned ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00006551
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006552 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006553 if (I.getOpcode() == Instruction::Shl) {
6554 assert(ShiftOp->getOpcode() == Instruction::LShr ||
6555 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnere8d56c52006-01-07 01:32:28 +00006556 Instruction *Shift =
Chris Lattnerb87056f2007-02-05 00:57:54 +00006557 BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00006558 InsertNewInstBefore(Shift, I);
6559
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006560 uint64_t Mask = Ty->getBitMask() << ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00006561 return BinaryOperator::createAnd(Shift, ConstantInt::get(Ty, Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00006562 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00006563
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006564 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006565 if (I.getOpcode() == Instruction::LShr) {
6566 assert(ShiftOp->getOpcode() == Instruction::Shl);
6567 Instruction *Shift =
6568 BinaryOperator::createLShr(X, ConstantInt::get(Ty, ShiftDiff));
6569 InsertNewInstBefore(Shift, I);
Chris Lattnerad0124c2006-01-06 07:52:12 +00006570
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006571 uint64_t Mask = Ty->getBitMask() >> ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00006572 return BinaryOperator::createAnd(Shift, ConstantInt::get(Ty, Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00006573 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00006574
6575 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
6576 } else {
6577 assert(ShiftAmt2 < ShiftAmt1);
6578 unsigned ShiftDiff = ShiftAmt1-ShiftAmt2;
6579
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006580 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006581 if (I.getOpcode() == Instruction::Shl) {
6582 assert(ShiftOp->getOpcode() == Instruction::LShr ||
6583 ShiftOp->getOpcode() == Instruction::AShr);
6584 Instruction *Shift =
6585 BinaryOperator::create(ShiftOp->getOpcode(), X,
6586 ConstantInt::get(Ty, ShiftDiff));
6587 InsertNewInstBefore(Shift, I);
6588
6589 uint64_t Mask = Ty->getBitMask() << ShiftAmt2;
6590 return BinaryOperator::createAnd(Shift, ConstantInt::get(Ty, Mask));
6591 }
6592
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006593 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006594 if (I.getOpcode() == Instruction::LShr) {
6595 assert(ShiftOp->getOpcode() == Instruction::Shl);
6596 Instruction *Shift =
6597 BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
6598 InsertNewInstBefore(Shift, I);
6599
6600 uint64_t Mask = Ty->getBitMask() >> ShiftAmt2;
6601 return BinaryOperator::createAnd(Shift, ConstantInt::get(Ty, Mask));
6602 }
6603
6604 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00006605 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00006606 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00006607 return 0;
6608}
6609
Chris Lattnera1be5662002-05-02 17:06:02 +00006610
Chris Lattnercfd65102005-10-29 04:36:15 +00006611/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
6612/// expression. If so, decompose it, returning some value X, such that Val is
6613/// X*Scale+Offset.
6614///
6615static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
6616 unsigned &Offset) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00006617 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00006618 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00006619 Offset = CI->getZExtValue();
6620 Scale = 1;
6621 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattnercfd65102005-10-29 04:36:15 +00006622 } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
6623 if (I->getNumOperands() == 2) {
Reid Spencerb83eb642006-10-20 07:07:24 +00006624 if (ConstantInt *CUI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00006625 if (I->getOpcode() == Instruction::Shl) {
6626 // This is a value scaled by '1 << the shift amt'.
6627 Scale = 1U << CUI->getZExtValue();
6628 Offset = 0;
6629 return I->getOperand(0);
6630 } else if (I->getOpcode() == Instruction::Mul) {
6631 // This value is scaled by 'CUI'.
6632 Scale = CUI->getZExtValue();
6633 Offset = 0;
6634 return I->getOperand(0);
6635 } else if (I->getOpcode() == Instruction::Add) {
6636 // We have X+C. Check to see if we really have (X*C2)+C1,
6637 // where C1 is divisible by C2.
6638 unsigned SubScale;
6639 Value *SubVal =
6640 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
6641 Offset += CUI->getZExtValue();
6642 if (SubScale > 1 && (Offset % SubScale == 0)) {
6643 Scale = SubScale;
6644 return SubVal;
Chris Lattnercfd65102005-10-29 04:36:15 +00006645 }
6646 }
6647 }
6648 }
6649 }
6650
6651 // Otherwise, we can't look past this.
6652 Scale = 1;
6653 Offset = 0;
6654 return Val;
6655}
6656
6657
Chris Lattnerb3f83972005-10-24 06:03:58 +00006658/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
6659/// try to eliminate the cast by moving the type information into the alloc.
6660Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
6661 AllocationInst &AI) {
6662 const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
Chris Lattner0ddac2a2005-10-27 05:53:56 +00006663 if (!PTy) return 0; // Not casting the allocation to a pointer type.
Chris Lattnerb3f83972005-10-24 06:03:58 +00006664
Chris Lattnerb53c2382005-10-24 06:22:12 +00006665 // Remove any uses of AI that are dead.
6666 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner535014f2007-02-15 22:52:10 +00006667
Chris Lattnerb53c2382005-10-24 06:22:12 +00006668 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
6669 Instruction *User = cast<Instruction>(*UI++);
6670 if (isInstructionTriviallyDead(User)) {
6671 while (UI != E && *UI == User)
6672 ++UI; // If this instruction uses AI more than once, don't break UI.
6673
Chris Lattnerb53c2382005-10-24 06:22:12 +00006674 ++NumDeadInst;
Bill Wendlingb7427032006-11-26 09:46:52 +00006675 DOUT << "IC: DCE: " << *User;
Chris Lattnerf22a5c62007-03-02 19:59:19 +00006676 EraseInstFromFunction(*User);
Chris Lattnerb53c2382005-10-24 06:22:12 +00006677 }
6678 }
6679
Chris Lattnerb3f83972005-10-24 06:03:58 +00006680 // Get the type really allocated and the type casted to.
6681 const Type *AllocElTy = AI.getAllocatedType();
6682 const Type *CastElTy = PTy->getElementType();
6683 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00006684
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00006685 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
6686 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00006687 if (CastElTyAlign < AllocElTyAlign) return 0;
6688
Chris Lattner39387a52005-10-24 06:35:18 +00006689 // If the allocation has multiple uses, only promote it if we are strictly
6690 // increasing the alignment of the resultant allocation. If we keep it the
6691 // same, we open the door to infinite loops of various kinds.
6692 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
6693
Chris Lattnerb3f83972005-10-24 06:03:58 +00006694 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
6695 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00006696 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00006697
Chris Lattner455fcc82005-10-29 03:19:53 +00006698 // See if we can satisfy the modulus by pulling a scale out of the array
6699 // size argument.
Chris Lattnercfd65102005-10-29 04:36:15 +00006700 unsigned ArraySizeScale, ArrayOffset;
6701 Value *NumElements = // See if the array size is a decomposable linear expr.
6702 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
6703
Chris Lattner455fcc82005-10-29 03:19:53 +00006704 // If we can now satisfy the modulus, by using a non-1 scale, we really can
6705 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00006706 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
6707 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00006708
Chris Lattner455fcc82005-10-29 03:19:53 +00006709 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
6710 Value *Amt = 0;
6711 if (Scale == 1) {
6712 Amt = NumElements;
6713 } else {
Reid Spencerb83eb642006-10-20 07:07:24 +00006714 // If the allocation size is constant, form a constant mul expression
Reid Spencerc5b206b2006-12-31 05:48:39 +00006715 Amt = ConstantInt::get(Type::Int32Ty, Scale);
6716 if (isa<ConstantInt>(NumElements))
Reid Spencerb83eb642006-10-20 07:07:24 +00006717 Amt = ConstantExpr::getMul(
6718 cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
6719 // otherwise multiply the amount and the number of elements
Chris Lattner455fcc82005-10-29 03:19:53 +00006720 else if (Scale != 1) {
6721 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
6722 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattner8142b0a2005-10-27 06:12:00 +00006723 }
Chris Lattner0ddac2a2005-10-27 05:53:56 +00006724 }
6725
Chris Lattnercfd65102005-10-29 04:36:15 +00006726 if (unsigned Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00006727 Value *Off = ConstantInt::get(Type::Int32Ty, Offset);
Chris Lattnercfd65102005-10-29 04:36:15 +00006728 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
6729 Amt = InsertNewInstBefore(Tmp, AI);
6730 }
6731
Chris Lattnerb3f83972005-10-24 06:03:58 +00006732 AllocationInst *New;
6733 if (isa<MallocInst>(AI))
Chris Lattner6934a042007-02-11 01:23:03 +00006734 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00006735 else
Chris Lattner6934a042007-02-11 01:23:03 +00006736 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00006737 InsertNewInstBefore(New, AI);
Chris Lattner6934a042007-02-11 01:23:03 +00006738 New->takeName(&AI);
Chris Lattner39387a52005-10-24 06:35:18 +00006739
6740 // If the allocation has multiple uses, insert a cast and change all things
6741 // that used it to use the new cast. This will also hack on CI, but it will
6742 // die soon.
6743 if (!AI.hasOneUse()) {
6744 AddUsesToWorkList(AI);
Reid Spencer3da59db2006-11-27 01:05:10 +00006745 // New is the allocation instruction, pointer typed. AI is the original
6746 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
6747 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner39387a52005-10-24 06:35:18 +00006748 InsertNewInstBefore(NewCast, AI);
6749 AI.replaceAllUsesWith(NewCast);
6750 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00006751 return ReplaceInstUsesWith(CI, New);
6752}
6753
Chris Lattner70074e02006-05-13 02:06:03 +00006754/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerc739cd62007-03-03 05:27:34 +00006755/// and return it as type Ty without inserting any new casts and without
6756/// changing the computed value. This is used by code that tries to decide
6757/// whether promoting or shrinking integer operations to wider or smaller types
6758/// will allow us to eliminate a truncate or extend.
6759///
6760/// This is a truncation operation if Ty is smaller than V->getType(), or an
6761/// extension operation if Ty is larger.
6762static bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
Chris Lattner70074e02006-05-13 02:06:03 +00006763 int &NumCastsRemoved) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00006764 // We can always evaluate constants in another type.
6765 if (isa<ConstantInt>(V))
6766 return true;
Chris Lattner70074e02006-05-13 02:06:03 +00006767
6768 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006769 if (!I) return false;
6770
6771 const IntegerType *OrigTy = cast<IntegerType>(V->getType());
Chris Lattner70074e02006-05-13 02:06:03 +00006772
6773 switch (I->getOpcode()) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00006774 case Instruction::Add:
6775 case Instruction::Sub:
Chris Lattner70074e02006-05-13 02:06:03 +00006776 case Instruction::And:
6777 case Instruction::Or:
6778 case Instruction::Xor:
Chris Lattnerc739cd62007-03-03 05:27:34 +00006779 if (!I->hasOneUse()) return false;
Chris Lattner70074e02006-05-13 02:06:03 +00006780 // These operators can all arbitrarily be extended or truncated.
6781 return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved) &&
6782 CanEvaluateInDifferentType(I->getOperand(1), Ty, NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006783
Chris Lattner46b96052006-11-29 07:18:39 +00006784 case Instruction::Shl:
Chris Lattnerc739cd62007-03-03 05:27:34 +00006785 if (!I->hasOneUse()) return false;
6786 // If we are truncating the result of this SHL, and if it's a shift of a
6787 // constant amount, we can always perform a SHL in a smaller type.
6788 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
6789 if (Ty->getBitWidth() < OrigTy->getBitWidth() &&
6790 CI->getZExtValue() < Ty->getBitWidth())
6791 return CanEvaluateInDifferentType(I->getOperand(0), Ty,NumCastsRemoved);
6792 }
6793 break;
6794 case Instruction::LShr:
6795 if (!I->hasOneUse()) return false;
6796 // If this is a truncate of a logical shr, we can truncate it to a smaller
6797 // lshr iff we know that the bits we would otherwise be shifting in are
6798 // already zeros.
6799 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
6800 if (Ty->getBitWidth() < OrigTy->getBitWidth() &&
6801 MaskedValueIsZero(I->getOperand(0),
6802 OrigTy->getBitMask() & ~Ty->getBitMask()) &&
6803 CI->getZExtValue() < Ty->getBitWidth()) {
6804 return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved);
6805 }
6806 }
Chris Lattner46b96052006-11-29 07:18:39 +00006807 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00006808 case Instruction::Trunc:
6809 case Instruction::ZExt:
6810 case Instruction::SExt:
Chris Lattner70074e02006-05-13 02:06:03 +00006811 // If this is a cast from the destination type, we can trivially eliminate
6812 // it, and this will remove a cast overall.
6813 if (I->getOperand(0)->getType() == Ty) {
Chris Lattnerd2280182006-06-28 17:34:50 +00006814 // If the first operand is itself a cast, and is eliminable, do not count
6815 // this as an eliminable cast. We would prefer to eliminate those two
6816 // casts first.
Reid Spencer3ed469c2006-11-02 20:25:50 +00006817 if (isa<CastInst>(I->getOperand(0)))
Chris Lattnerd2280182006-06-28 17:34:50 +00006818 return true;
6819
Chris Lattner70074e02006-05-13 02:06:03 +00006820 ++NumCastsRemoved;
6821 return true;
6822 }
Reid Spencer3da59db2006-11-27 01:05:10 +00006823 break;
6824 default:
Chris Lattner70074e02006-05-13 02:06:03 +00006825 // TODO: Can handle more cases here.
6826 break;
6827 }
6828
6829 return false;
6830}
6831
6832/// EvaluateInDifferentType - Given an expression that
6833/// CanEvaluateInDifferentType returns true for, actually insert the code to
6834/// evaluate the expression.
Reid Spencerc55b2432006-12-13 18:21:21 +00006835Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerc739cd62007-03-03 05:27:34 +00006836 bool isSigned) {
Chris Lattner70074e02006-05-13 02:06:03 +00006837 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencerc55b2432006-12-13 18:21:21 +00006838 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Chris Lattner70074e02006-05-13 02:06:03 +00006839
6840 // Otherwise, it must be an instruction.
6841 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00006842 Instruction *Res = 0;
Chris Lattner70074e02006-05-13 02:06:03 +00006843 switch (I->getOpcode()) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00006844 case Instruction::Add:
6845 case Instruction::Sub:
Chris Lattner70074e02006-05-13 02:06:03 +00006846 case Instruction::And:
6847 case Instruction::Or:
Chris Lattnerc739cd62007-03-03 05:27:34 +00006848 case Instruction::Xor:
Chris Lattner46b96052006-11-29 07:18:39 +00006849 case Instruction::AShr:
6850 case Instruction::LShr:
6851 case Instruction::Shl: {
Reid Spencerc55b2432006-12-13 18:21:21 +00006852 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006853 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
6854 Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
6855 LHS, RHS, I->getName());
Chris Lattner46b96052006-11-29 07:18:39 +00006856 break;
6857 }
Reid Spencer3da59db2006-11-27 01:05:10 +00006858 case Instruction::Trunc:
6859 case Instruction::ZExt:
6860 case Instruction::SExt:
6861 case Instruction::BitCast:
6862 // If the source type of the cast is the type we're trying for then we can
6863 // just return the source. There's no need to insert it because its not new.
Chris Lattner70074e02006-05-13 02:06:03 +00006864 if (I->getOperand(0)->getType() == Ty)
6865 return I->getOperand(0);
6866
Reid Spencer3da59db2006-11-27 01:05:10 +00006867 // Some other kind of cast, which shouldn't happen, so just ..
6868 // FALL THROUGH
6869 default:
Chris Lattner70074e02006-05-13 02:06:03 +00006870 // TODO: Can handle more cases here.
6871 assert(0 && "Unreachable!");
6872 break;
6873 }
6874
6875 return InsertNewInstBefore(Res, *I);
6876}
6877
Reid Spencer3da59db2006-11-27 01:05:10 +00006878/// @brief Implement the transforms common to all CastInst visitors.
6879Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00006880 Value *Src = CI.getOperand(0);
6881
Reid Spencer3da59db2006-11-27 01:05:10 +00006882 // Casting undef to anything results in undef so might as just replace it and
6883 // get rid of the cast.
Chris Lattnere87597f2004-10-16 18:11:37 +00006884 if (isa<UndefValue>(Src)) // cast undef -> undef
6885 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
6886
Reid Spencer3da59db2006-11-27 01:05:10 +00006887 // Many cases of "cast of a cast" are eliminable. If its eliminable we just
6888 // eliminate it now.
Chris Lattner6e7ba452005-01-01 16:22:27 +00006889 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00006890 if (Instruction::CastOps opc =
6891 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
6892 // The first cast (CSrc) is eliminable so we need to fix up or replace
6893 // the second cast (CI). CSrc will then have a good chance of being dead.
6894 return CastInst::create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner8fd217c2002-08-02 20:00:25 +00006895 }
6896 }
Chris Lattnera710ddc2004-05-25 04:29:21 +00006897
Chris Lattner797249b2003-06-21 23:12:02 +00006898 // If casting the result of a getelementptr instruction with no offset, turn
6899 // this into a cast of the original pointer!
6900 //
Chris Lattner79d35b32003-06-23 21:59:52 +00006901 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner797249b2003-06-21 23:12:02 +00006902 bool AllZeroOperands = true;
6903 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
6904 if (!isa<Constant>(GEP->getOperand(i)) ||
6905 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
6906 AllZeroOperands = false;
6907 break;
6908 }
6909 if (AllZeroOperands) {
Reid Spencer3da59db2006-11-27 01:05:10 +00006910 // Changing the cast operand is usually not a good idea but it is safe
6911 // here because the pointer operand is being replaced with another
6912 // pointer operand so the opcode doesn't need to change.
Chris Lattner797249b2003-06-21 23:12:02 +00006913 CI.setOperand(0, GEP->getOperand(0));
6914 return &CI;
6915 }
6916 }
Chris Lattner13c654a2006-11-21 17:05:13 +00006917
Chris Lattnerbc61e662003-11-02 05:57:39 +00006918 // If we are casting a malloc or alloca to a pointer to a type of the same
6919 // size, rewrite the allocation instruction to allocate the "right" type.
Chris Lattnerbc61e662003-11-02 05:57:39 +00006920 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattnerb3f83972005-10-24 06:03:58 +00006921 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
6922 return V;
Chris Lattnerbc61e662003-11-02 05:57:39 +00006923
Reid Spencer3da59db2006-11-27 01:05:10 +00006924 // If we are casting a select then fold the cast into the select
Chris Lattner6e7ba452005-01-01 16:22:27 +00006925 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
6926 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
6927 return NV;
Reid Spencer3da59db2006-11-27 01:05:10 +00006928
6929 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner4e998b22004-09-29 05:07:12 +00006930 if (isa<PHINode>(Src))
6931 if (Instruction *NV = FoldOpIntoPhi(CI))
6932 return NV;
Chris Lattner9fb92132006-04-12 18:09:35 +00006933
Reid Spencer3da59db2006-11-27 01:05:10 +00006934 return 0;
6935}
6936
Chris Lattnerc739cd62007-03-03 05:27:34 +00006937/// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
6938/// integer types. This function implements the common transforms for all those
Reid Spencer3da59db2006-11-27 01:05:10 +00006939/// cases.
6940/// @brief Implement the transforms common to CastInst with integer operands
6941Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
6942 if (Instruction *Result = commonCastTransforms(CI))
6943 return Result;
6944
6945 Value *Src = CI.getOperand(0);
6946 const Type *SrcTy = Src->getType();
6947 const Type *DestTy = CI.getType();
6948 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
6949 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
6950
Reid Spencer3da59db2006-11-27 01:05:10 +00006951 // See if we can simplify any instructions used by the LHS whose sole
6952 // purpose is to compute bits we don't care about.
6953 uint64_t KnownZero = 0, KnownOne = 0;
Reid Spencerc1030572007-01-19 21:13:56 +00006954 if (SimplifyDemandedBits(&CI, cast<IntegerType>(DestTy)->getBitMask(),
Reid Spencer3da59db2006-11-27 01:05:10 +00006955 KnownZero, KnownOne))
6956 return &CI;
6957
6958 // If the source isn't an instruction or has more than one use then we
6959 // can't do anything more.
Reid Spencere4d87aa2006-12-23 06:05:41 +00006960 Instruction *SrcI = dyn_cast<Instruction>(Src);
6961 if (!SrcI || !Src->hasOneUse())
Reid Spencer3da59db2006-11-27 01:05:10 +00006962 return 0;
6963
Chris Lattnerc739cd62007-03-03 05:27:34 +00006964 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00006965 int NumCastsRemoved = 0;
Chris Lattnerc739cd62007-03-03 05:27:34 +00006966 if (!isa<BitCastInst>(CI) &&
6967 CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
6968 NumCastsRemoved)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00006969 // If this cast is a truncate, evaluting in a different type always
6970 // eliminates the cast, so it is always a win. If this is a noop-cast
6971 // this just removes a noop cast which isn't pointful, but simplifies
6972 // the code. If this is a zero-extension, we need to do an AND to
6973 // maintain the clear top-part of the computation, so we require that
6974 // the input have eliminated at least one cast. If this is a sign
6975 // extension, we insert two new casts (to do the extension) so we
6976 // require that two casts have been eliminated.
Chris Lattnerc739cd62007-03-03 05:27:34 +00006977 bool DoXForm;
6978 switch (CI.getOpcode()) {
6979 default:
6980 // All the others use floating point so we shouldn't actually
6981 // get here because of the check above.
6982 assert(0 && "Unknown cast type");
6983 case Instruction::Trunc:
6984 DoXForm = true;
6985 break;
6986 case Instruction::ZExt:
6987 DoXForm = NumCastsRemoved >= 1;
6988 break;
6989 case Instruction::SExt:
6990 DoXForm = NumCastsRemoved >= 2;
6991 break;
6992 case Instruction::BitCast:
6993 DoXForm = false;
6994 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00006995 }
6996
6997 if (DoXForm) {
Reid Spencerc55b2432006-12-13 18:21:21 +00006998 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
6999 CI.getOpcode() == Instruction::SExt);
Reid Spencer3da59db2006-11-27 01:05:10 +00007000 assert(Res->getType() == DestTy);
7001 switch (CI.getOpcode()) {
7002 default: assert(0 && "Unknown cast type!");
7003 case Instruction::Trunc:
7004 case Instruction::BitCast:
7005 // Just replace this cast with the result.
7006 return ReplaceInstUsesWith(CI, Res);
7007 case Instruction::ZExt: {
7008 // We need to emit an AND to clear the high bits.
7009 assert(SrcBitSize < DestBitSize && "Not a zext?");
7010 Constant *C =
Reid Spencerc5b206b2006-12-31 05:48:39 +00007011 ConstantInt::get(Type::Int64Ty, (1ULL << SrcBitSize)-1);
Reid Spencer3da59db2006-11-27 01:05:10 +00007012 if (DestBitSize < 64)
7013 C = ConstantExpr::getTrunc(C, DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00007014 return BinaryOperator::createAnd(Res, C);
7015 }
7016 case Instruction::SExt:
7017 // We need to emit a cast to truncate, then a cast to sext.
7018 return CastInst::create(Instruction::SExt,
Reid Spencer17212df2006-12-12 09:18:51 +00007019 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
7020 CI), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00007021 }
7022 }
7023 }
7024
7025 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
7026 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
7027
7028 switch (SrcI->getOpcode()) {
7029 case Instruction::Add:
7030 case Instruction::Mul:
7031 case Instruction::And:
7032 case Instruction::Or:
7033 case Instruction::Xor:
7034 // If we are discarding information, or just changing the sign,
7035 // rewrite.
7036 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
7037 // Don't insert two casts if they cannot be eliminated. We allow
7038 // two casts to be inserted if the sizes are the same. This could
7039 // only be converting signedness, which is a noop.
7040 if (DestBitSize == SrcBitSize ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00007041 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
7042 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer7eb76382006-12-13 17:19:09 +00007043 Instruction::CastOps opcode = CI.getOpcode();
Reid Spencer17212df2006-12-12 09:18:51 +00007044 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7045 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
7046 return BinaryOperator::create(
7047 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00007048 }
7049 }
7050
7051 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
7052 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
7053 SrcI->getOpcode() == Instruction::Xor &&
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007054 Op1 == ConstantInt::getTrue() &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00007055 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Reid Spencer17212df2006-12-12 09:18:51 +00007056 Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007057 return BinaryOperator::createXor(New, ConstantInt::get(CI.getType(), 1));
7058 }
7059 break;
7060 case Instruction::SDiv:
7061 case Instruction::UDiv:
7062 case Instruction::SRem:
7063 case Instruction::URem:
7064 // If we are just changing the sign, rewrite.
7065 if (DestBitSize == SrcBitSize) {
7066 // Don't insert two casts if they cannot be eliminated. We allow
7067 // two casts to be inserted if the sizes are the same. This could
7068 // only be converting signedness, which is a noop.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007069 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
7070 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer17212df2006-12-12 09:18:51 +00007071 Value *Op0c = InsertOperandCastBefore(Instruction::BitCast,
7072 Op0, DestTy, SrcI);
7073 Value *Op1c = InsertOperandCastBefore(Instruction::BitCast,
7074 Op1, DestTy, SrcI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007075 return BinaryOperator::create(
7076 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7077 }
7078 }
7079 break;
7080
7081 case Instruction::Shl:
7082 // Allow changing the sign of the source operand. Do not allow
7083 // changing the size of the shift, UNLESS the shift amount is a
7084 // constant. We must not change variable sized shifts to a smaller
7085 // size, because it is undefined to shift more bits out than exist
7086 // in the value.
7087 if (DestBitSize == SrcBitSize ||
7088 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
Reid Spencer17212df2006-12-12 09:18:51 +00007089 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
7090 Instruction::BitCast : Instruction::Trunc);
7091 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
Reid Spencer832254e2007-02-02 02:16:23 +00007092 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
Reid Spencercc46cdb2007-02-02 14:08:20 +00007093 return BinaryOperator::createShl(Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00007094 }
7095 break;
7096 case Instruction::AShr:
7097 // If this is a signed shr, and if all bits shifted in are about to be
7098 // truncated off, turn it into an unsigned shr to allow greater
7099 // simplifications.
7100 if (DestBitSize < SrcBitSize &&
7101 isa<ConstantInt>(Op1)) {
7102 unsigned ShiftAmt = cast<ConstantInt>(Op1)->getZExtValue();
7103 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
7104 // Insert the new logical shift right.
Reid Spencercc46cdb2007-02-02 14:08:20 +00007105 return BinaryOperator::createLShr(Op0, Op1);
Reid Spencer3da59db2006-11-27 01:05:10 +00007106 }
7107 }
7108 break;
7109
Reid Spencere4d87aa2006-12-23 06:05:41 +00007110 case Instruction::ICmp:
7111 // If we are just checking for a icmp eq of a single bit and casting it
7112 // to an integer, then shift the bit to the appropriate place and then
Reid Spencer3da59db2006-11-27 01:05:10 +00007113 // cast to integer to avoid the comparison.
7114 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
7115 uint64_t Op1CV = Op1C->getZExtValue();
7116 // cast (X == 0) to int --> X^1 iff X has only the low bit set.
7117 // cast (X == 0) to int --> (X>>1)^1 iff X has only the 2nd bit set.
7118 // cast (X == 1) to int --> X iff X has only the low bit set.
7119 // cast (X == 2) to int --> X>>1 iff X has only the 2nd bit set.
7120 // cast (X != 0) to int --> X iff X has only the low bit set.
7121 // cast (X != 0) to int --> X>>1 iff X has only the 2nd bit set.
7122 // cast (X != 1) to int --> X^1 iff X has only the low bit set.
7123 // cast (X != 2) to int --> (X>>1)^1 iff X has only the 2nd bit set.
7124 if (Op1CV == 0 || isPowerOf2_64(Op1CV)) {
7125 // If Op1C some other power of two, convert:
7126 uint64_t KnownZero, KnownOne;
Reid Spencerc1030572007-01-19 21:13:56 +00007127 uint64_t TypeMask = Op1C->getType()->getBitMask();
Reid Spencer3da59db2006-11-27 01:05:10 +00007128 ComputeMaskedBits(Op0, TypeMask, KnownZero, KnownOne);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007129
7130 // This only works for EQ and NE
7131 ICmpInst::Predicate pred = cast<ICmpInst>(SrcI)->getPredicate();
7132 if (pred != ICmpInst::ICMP_NE && pred != ICmpInst::ICMP_EQ)
7133 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007134
7135 if (isPowerOf2_64(KnownZero^TypeMask)) { // Exactly 1 possible 1?
Reid Spencere4d87aa2006-12-23 06:05:41 +00007136 bool isNE = pred == ICmpInst::ICMP_NE;
Reid Spencer3da59db2006-11-27 01:05:10 +00007137 if (Op1CV && (Op1CV != (KnownZero^TypeMask))) {
7138 // (X&4) == 2 --> false
7139 // (X&4) != 2 --> true
Reid Spencer579dca12007-01-12 04:24:46 +00007140 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
Reid Spencerd977d862006-12-12 23:36:14 +00007141 Res = ConstantExpr::getZExt(Res, CI.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00007142 return ReplaceInstUsesWith(CI, Res);
7143 }
7144
7145 unsigned ShiftAmt = Log2_64(KnownZero^TypeMask);
7146 Value *In = Op0;
7147 if (ShiftAmt) {
7148 // Perform a logical shr by shiftamt.
7149 // Insert the shift to put the result in the low bit.
7150 In = InsertNewInstBefore(
Reid Spencercc46cdb2007-02-02 14:08:20 +00007151 BinaryOperator::createLShr(In,
Reid Spencer832254e2007-02-02 02:16:23 +00007152 ConstantInt::get(In->getType(), ShiftAmt),
7153 In->getName()+".lobit"), CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007154 }
7155
Reid Spencere4d87aa2006-12-23 06:05:41 +00007156 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
Reid Spencer3da59db2006-11-27 01:05:10 +00007157 Constant *One = ConstantInt::get(In->getType(), 1);
7158 In = BinaryOperator::createXor(In, One, "tmp");
7159 InsertNewInstBefore(cast<Instruction>(In), CI);
7160 }
7161
7162 if (CI.getType() == In->getType())
7163 return ReplaceInstUsesWith(CI, In);
7164 else
Reid Spencerd977d862006-12-12 23:36:14 +00007165 return CastInst::createIntegerCast(In, CI.getType(), false/*ZExt*/);
Reid Spencer3da59db2006-11-27 01:05:10 +00007166 }
7167 }
7168 }
7169 break;
7170 }
7171 return 0;
7172}
7173
7174Instruction *InstCombiner::visitTrunc(CastInst &CI) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007175 if (Instruction *Result = commonIntCastTransforms(CI))
7176 return Result;
7177
7178 Value *Src = CI.getOperand(0);
7179 const Type *Ty = CI.getType();
7180 unsigned DestBitWidth = Ty->getPrimitiveSizeInBits();
7181
7182 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
7183 switch (SrcI->getOpcode()) {
7184 default: break;
7185 case Instruction::LShr:
7186 // We can shrink lshr to something smaller if we know the bits shifted in
7187 // are already zeros.
7188 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
7189 unsigned ShAmt = ShAmtV->getZExtValue();
7190
7191 // Get a mask for the bits shifting in.
7192 uint64_t Mask = (~0ULL >> (64-ShAmt)) << DestBitWidth;
Reid Spencer17212df2006-12-12 09:18:51 +00007193 Value* SrcIOp0 = SrcI->getOperand(0);
7194 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007195 if (ShAmt >= DestBitWidth) // All zeros.
7196 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
7197
7198 // Okay, we can shrink this. Truncate the input, then return a new
7199 // shift.
Reid Spencer832254e2007-02-02 02:16:23 +00007200 Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
7201 Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
7202 Ty, CI);
Reid Spencercc46cdb2007-02-02 14:08:20 +00007203 return BinaryOperator::createLShr(V1, V2);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007204 }
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007205 } else { // This is a variable shr.
7206
7207 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
7208 // more LLVM instructions, but allows '1 << Y' to be hoisted if
7209 // loop-invariant and CSE'd.
Reid Spencer4fe16d62007-01-11 18:21:29 +00007210 if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007211 Value *One = ConstantInt::get(SrcI->getType(), 1);
7212
Reid Spencer832254e2007-02-02 02:16:23 +00007213 Value *V = InsertNewInstBefore(
Reid Spencercc46cdb2007-02-02 14:08:20 +00007214 BinaryOperator::createShl(One, SrcI->getOperand(1),
Reid Spencer832254e2007-02-02 02:16:23 +00007215 "tmp"), CI);
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007216 V = InsertNewInstBefore(BinaryOperator::createAnd(V,
7217 SrcI->getOperand(0),
7218 "tmp"), CI);
7219 Value *Zero = Constant::getNullValue(V->getType());
Reid Spencere4d87aa2006-12-23 06:05:41 +00007220 return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007221 }
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007222 }
7223 break;
7224 }
7225 }
7226
7227 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007228}
7229
7230Instruction *InstCombiner::visitZExt(CastInst &CI) {
7231 // If one of the common conversion will work ..
7232 if (Instruction *Result = commonIntCastTransforms(CI))
7233 return Result;
7234
7235 Value *Src = CI.getOperand(0);
7236
7237 // If this is a cast of a cast
7238 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00007239 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
7240 // types and if the sizes are just right we can convert this into a logical
7241 // 'and' which will be much cheaper than the pair of casts.
7242 if (isa<TruncInst>(CSrc)) {
7243 // Get the sizes of the types involved
7244 Value *A = CSrc->getOperand(0);
7245 unsigned SrcSize = A->getType()->getPrimitiveSizeInBits();
7246 unsigned MidSize = CSrc->getType()->getPrimitiveSizeInBits();
7247 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
7248 // If we're actually extending zero bits and the trunc is a no-op
7249 if (MidSize < DstSize && SrcSize == DstSize) {
7250 // Replace both of the casts with an And of the type mask.
Reid Spencerc1030572007-01-19 21:13:56 +00007251 uint64_t AndValue = cast<IntegerType>(CSrc->getType())->getBitMask();
Reid Spencer3da59db2006-11-27 01:05:10 +00007252 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
7253 Instruction *And =
7254 BinaryOperator::createAnd(CSrc->getOperand(0), AndConst);
7255 // Unfortunately, if the type changed, we need to cast it back.
7256 if (And->getType() != CI.getType()) {
7257 And->setName(CSrc->getName()+".mask");
7258 InsertNewInstBefore(And, CI);
Reid Spencerd977d862006-12-12 23:36:14 +00007259 And = CastInst::createIntegerCast(And, CI.getType(), false/*ZExt*/);
Reid Spencer3da59db2006-11-27 01:05:10 +00007260 }
7261 return And;
7262 }
7263 }
7264 }
7265
7266 return 0;
7267}
7268
7269Instruction *InstCombiner::visitSExt(CastInst &CI) {
7270 return commonIntCastTransforms(CI);
7271}
7272
7273Instruction *InstCombiner::visitFPTrunc(CastInst &CI) {
7274 return commonCastTransforms(CI);
7275}
7276
7277Instruction *InstCombiner::visitFPExt(CastInst &CI) {
7278 return commonCastTransforms(CI);
7279}
7280
7281Instruction *InstCombiner::visitFPToUI(CastInst &CI) {
Reid Spencer44c030a2006-11-30 23:13:36 +00007282 return commonCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007283}
7284
7285Instruction *InstCombiner::visitFPToSI(CastInst &CI) {
Reid Spencer44c030a2006-11-30 23:13:36 +00007286 return commonCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007287}
7288
7289Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
7290 return commonCastTransforms(CI);
7291}
7292
7293Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
7294 return commonCastTransforms(CI);
7295}
7296
7297Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
Reid Spencer44c030a2006-11-30 23:13:36 +00007298 return commonCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007299}
7300
7301Instruction *InstCombiner::visitIntToPtr(CastInst &CI) {
7302 return commonCastTransforms(CI);
7303}
7304
7305Instruction *InstCombiner::visitBitCast(CastInst &CI) {
7306
7307 // If the operands are integer typed then apply the integer transforms,
7308 // otherwise just apply the common ones.
7309 Value *Src = CI.getOperand(0);
7310 const Type *SrcTy = Src->getType();
7311 const Type *DestTy = CI.getType();
7312
Chris Lattner42a75512007-01-15 02:27:26 +00007313 if (SrcTy->isInteger() && DestTy->isInteger()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007314 if (Instruction *Result = commonIntCastTransforms(CI))
7315 return Result;
7316 } else {
7317 if (Instruction *Result = commonCastTransforms(CI))
7318 return Result;
7319 }
7320
7321
7322 // Get rid of casts from one type to the same type. These are useless and can
7323 // be replaced by the operand.
7324 if (DestTy == Src->getType())
7325 return ReplaceInstUsesWith(CI, Src);
7326
Chris Lattner9fb92132006-04-12 18:09:35 +00007327 // If the source and destination are pointers, and this cast is equivalent to
7328 // a getelementptr X, 0, 0, 0... turn it into the appropriate getelementptr.
7329 // This can enhance SROA and other transforms that want type-safe pointers.
Reid Spencer3da59db2006-11-27 01:05:10 +00007330 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
7331 if (const PointerType *SrcPTy = dyn_cast<PointerType>(SrcTy)) {
7332 const Type *DstElTy = DstPTy->getElementType();
7333 const Type *SrcElTy = SrcPTy->getElementType();
Chris Lattner9fb92132006-04-12 18:09:35 +00007334
Reid Spencerc5b206b2006-12-31 05:48:39 +00007335 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
Chris Lattner9fb92132006-04-12 18:09:35 +00007336 unsigned NumZeros = 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007337 while (SrcElTy != DstElTy &&
7338 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
7339 SrcElTy->getNumContainedTypes() /* not "{}" */) {
7340 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
Chris Lattner9fb92132006-04-12 18:09:35 +00007341 ++NumZeros;
7342 }
Chris Lattner4e998b22004-09-29 05:07:12 +00007343
Chris Lattner9fb92132006-04-12 18:09:35 +00007344 // If we found a path from the src to dest, create the getelementptr now.
Reid Spencer3da59db2006-11-27 01:05:10 +00007345 if (SrcElTy == DstElTy) {
Chris Lattnerfbbe92f2007-01-31 20:08:52 +00007346 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
7347 return new GetElementPtrInst(Src, &Idxs[0], Idxs.size());
Chris Lattner9fb92132006-04-12 18:09:35 +00007348 }
7349 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007350 }
Chris Lattner24c8e382003-07-24 17:35:25 +00007351
Reid Spencer3da59db2006-11-27 01:05:10 +00007352 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
7353 if (SVI->hasOneUse()) {
7354 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
7355 // a bitconvert to a vector with the same # elts.
Reid Spencer9d6565a2007-02-15 02:26:10 +00007356 if (isa<VectorType>(DestTy) &&
7357 cast<VectorType>(DestTy)->getNumElements() ==
Reid Spencer3da59db2006-11-27 01:05:10 +00007358 SVI->getType()->getNumElements()) {
7359 CastInst *Tmp;
7360 // If either of the operands is a cast from CI.getType(), then
7361 // evaluating the shuffle in the casted destination's type will allow
7362 // us to eliminate at least one cast.
7363 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
7364 Tmp->getOperand(0)->getType() == DestTy) ||
7365 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
7366 Tmp->getOperand(0)->getType() == DestTy)) {
Reid Spencer17212df2006-12-12 09:18:51 +00007367 Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
7368 SVI->getOperand(0), DestTy, &CI);
7369 Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
7370 SVI->getOperand(1), DestTy, &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007371 // Return a new shuffle vector. Use the same element ID's, as we
7372 // know the vector types match #elts.
7373 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner01575b72006-05-25 23:24:33 +00007374 }
7375 }
7376 }
7377 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00007378 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00007379}
7380
Chris Lattnere576b912004-04-09 23:46:01 +00007381/// GetSelectFoldableOperands - We want to turn code that looks like this:
7382/// %C = or %A, %B
7383/// %D = select %cond, %C, %A
7384/// into:
7385/// %C = select %cond, %B, 0
7386/// %D = or %A, %C
7387///
7388/// Assuming that the specified instruction is an operand to the select, return
7389/// a bitmask indicating which operands of this instruction are foldable if they
7390/// equal the other incoming value of the select.
7391///
7392static unsigned GetSelectFoldableOperands(Instruction *I) {
7393 switch (I->getOpcode()) {
7394 case Instruction::Add:
7395 case Instruction::Mul:
7396 case Instruction::And:
7397 case Instruction::Or:
7398 case Instruction::Xor:
7399 return 3; // Can fold through either operand.
7400 case Instruction::Sub: // Can only fold on the amount subtracted.
7401 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencer3822ff52006-11-08 06:47:33 +00007402 case Instruction::LShr:
7403 case Instruction::AShr:
Misha Brukmanfd939082005-04-21 23:48:37 +00007404 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00007405 default:
7406 return 0; // Cannot fold
7407 }
7408}
7409
7410/// GetSelectFoldableConstant - For the same transformation as the previous
7411/// function, return the identity constant that goes into the select.
7412static Constant *GetSelectFoldableConstant(Instruction *I) {
7413 switch (I->getOpcode()) {
7414 default: assert(0 && "This cannot happen!"); abort();
7415 case Instruction::Add:
7416 case Instruction::Sub:
7417 case Instruction::Or:
7418 case Instruction::Xor:
Chris Lattnere576b912004-04-09 23:46:01 +00007419 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00007420 case Instruction::LShr:
7421 case Instruction::AShr:
Reid Spencer832254e2007-02-02 02:16:23 +00007422 return Constant::getNullValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00007423 case Instruction::And:
7424 return ConstantInt::getAllOnesValue(I->getType());
7425 case Instruction::Mul:
7426 return ConstantInt::get(I->getType(), 1);
7427 }
7428}
7429
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007430/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
7431/// have the same opcode and only one use each. Try to simplify this.
7432Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
7433 Instruction *FI) {
7434 if (TI->getNumOperands() == 1) {
7435 // If this is a non-volatile load or a cast from the same type,
7436 // merge.
Reid Spencer3da59db2006-11-27 01:05:10 +00007437 if (TI->isCast()) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007438 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
7439 return 0;
7440 } else {
7441 return 0; // unknown unary op.
7442 }
Misha Brukmanfd939082005-04-21 23:48:37 +00007443
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007444 // Fold this by inserting a select from the input values.
7445 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
7446 FI->getOperand(0), SI.getName()+".v");
7447 InsertNewInstBefore(NewSI, SI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007448 return CastInst::create(Instruction::CastOps(TI->getOpcode()), NewSI,
7449 TI->getType());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007450 }
7451
Reid Spencer832254e2007-02-02 02:16:23 +00007452 // Only handle binary operators here.
7453 if (!isa<BinaryOperator>(TI))
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007454 return 0;
7455
7456 // Figure out if the operations have any operands in common.
7457 Value *MatchOp, *OtherOpT, *OtherOpF;
7458 bool MatchIsOpZero;
7459 if (TI->getOperand(0) == FI->getOperand(0)) {
7460 MatchOp = TI->getOperand(0);
7461 OtherOpT = TI->getOperand(1);
7462 OtherOpF = FI->getOperand(1);
7463 MatchIsOpZero = true;
7464 } else if (TI->getOperand(1) == FI->getOperand(1)) {
7465 MatchOp = TI->getOperand(1);
7466 OtherOpT = TI->getOperand(0);
7467 OtherOpF = FI->getOperand(0);
7468 MatchIsOpZero = false;
7469 } else if (!TI->isCommutative()) {
7470 return 0;
7471 } else if (TI->getOperand(0) == FI->getOperand(1)) {
7472 MatchOp = TI->getOperand(0);
7473 OtherOpT = TI->getOperand(1);
7474 OtherOpF = FI->getOperand(0);
7475 MatchIsOpZero = true;
7476 } else if (TI->getOperand(1) == FI->getOperand(0)) {
7477 MatchOp = TI->getOperand(1);
7478 OtherOpT = TI->getOperand(0);
7479 OtherOpF = FI->getOperand(1);
7480 MatchIsOpZero = true;
7481 } else {
7482 return 0;
7483 }
7484
7485 // If we reach here, they do have operations in common.
7486 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
7487 OtherOpF, SI.getName()+".v");
7488 InsertNewInstBefore(NewSI, SI);
7489
7490 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
7491 if (MatchIsOpZero)
7492 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
7493 else
7494 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007495 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00007496 assert(0 && "Shouldn't get here");
7497 return 0;
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007498}
7499
Chris Lattner3d69f462004-03-12 05:52:32 +00007500Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00007501 Value *CondVal = SI.getCondition();
7502 Value *TrueVal = SI.getTrueValue();
7503 Value *FalseVal = SI.getFalseValue();
7504
7505 // select true, X, Y -> X
7506 // select false, X, Y -> Y
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007507 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencer579dca12007-01-12 04:24:46 +00007508 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00007509
7510 // select C, X, X -> X
7511 if (TrueVal == FalseVal)
7512 return ReplaceInstUsesWith(SI, TrueVal);
7513
Chris Lattnere87597f2004-10-16 18:11:37 +00007514 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
7515 return ReplaceInstUsesWith(SI, FalseVal);
7516 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
7517 return ReplaceInstUsesWith(SI, TrueVal);
7518 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
7519 if (isa<Constant>(TrueVal))
7520 return ReplaceInstUsesWith(SI, TrueVal);
7521 else
7522 return ReplaceInstUsesWith(SI, FalseVal);
7523 }
7524
Reid Spencer4fe16d62007-01-11 18:21:29 +00007525 if (SI.getType() == Type::Int1Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00007526 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00007527 if (C->getZExtValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00007528 // Change: A = select B, true, C --> A = or B, C
Chris Lattner48595f12004-06-10 02:07:29 +00007529 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00007530 } else {
7531 // Change: A = select B, false, C --> A = and !B, C
7532 Value *NotCond =
7533 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
7534 "not."+CondVal->getName()), SI);
Chris Lattner48595f12004-06-10 02:07:29 +00007535 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00007536 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00007537 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00007538 if (C->getZExtValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00007539 // Change: A = select B, C, false --> A = and B, C
Chris Lattner48595f12004-06-10 02:07:29 +00007540 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00007541 } else {
7542 // Change: A = select B, C, true --> A = or !B, C
7543 Value *NotCond =
7544 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
7545 "not."+CondVal->getName()), SI);
Chris Lattner48595f12004-06-10 02:07:29 +00007546 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00007547 }
7548 }
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007549 }
Chris Lattner0c199a72004-04-08 04:43:23 +00007550
Chris Lattner2eefe512004-04-09 19:05:30 +00007551 // Selecting between two integer constants?
7552 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
7553 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
7554 // select C, 1, 0 -> cast C to int
Reid Spencerb83eb642006-10-20 07:07:24 +00007555 if (FalseValC->isNullValue() && TrueValC->getZExtValue() == 1) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007556 return CastInst::create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencerb83eb642006-10-20 07:07:24 +00007557 } else if (TrueValC->isNullValue() && FalseValC->getZExtValue() == 1) {
Chris Lattner2eefe512004-04-09 19:05:30 +00007558 // select C, 0, 1 -> cast !C to int
7559 Value *NotCond =
7560 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00007561 "not."+CondVal->getName()), SI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007562 return CastInst::create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00007563 }
Chris Lattner457dd822004-06-09 07:59:58 +00007564
Reid Spencere4d87aa2006-12-23 06:05:41 +00007565 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattnerb8456462006-09-20 04:44:59 +00007566
Reid Spencere4d87aa2006-12-23 06:05:41 +00007567 // (x <s 0) ? -1 : 0 -> ashr x, 31
7568 // (x >u 2147483647) ? -1 : 0 -> ashr x, 31
Chris Lattnerb8456462006-09-20 04:44:59 +00007569 if (TrueValC->isAllOnesValue() && FalseValC->isNullValue())
7570 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
7571 bool CanXForm = false;
Reid Spencere4d87aa2006-12-23 06:05:41 +00007572 if (IC->isSignedPredicate())
Chris Lattnerb8456462006-09-20 04:44:59 +00007573 CanXForm = CmpCst->isNullValue() &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00007574 IC->getPredicate() == ICmpInst::ICMP_SLT;
Chris Lattnerb8456462006-09-20 04:44:59 +00007575 else {
7576 unsigned Bits = CmpCst->getType()->getPrimitiveSizeInBits();
Reid Spencerb83eb642006-10-20 07:07:24 +00007577 CanXForm = (CmpCst->getZExtValue() == ~0ULL >> (64-Bits+1)) &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00007578 IC->getPredicate() == ICmpInst::ICMP_UGT;
Chris Lattnerb8456462006-09-20 04:44:59 +00007579 }
7580
7581 if (CanXForm) {
7582 // The comparison constant and the result are not neccessarily the
Reid Spencer3da59db2006-11-27 01:05:10 +00007583 // same width. Make an all-ones value by inserting a AShr.
Chris Lattnerb8456462006-09-20 04:44:59 +00007584 Value *X = IC->getOperand(0);
Chris Lattnerb8456462006-09-20 04:44:59 +00007585 unsigned Bits = X->getType()->getPrimitiveSizeInBits();
Reid Spencer832254e2007-02-02 02:16:23 +00007586 Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
7587 Instruction *SRA = BinaryOperator::create(Instruction::AShr, X,
7588 ShAmt, "ones");
Chris Lattnerb8456462006-09-20 04:44:59 +00007589 InsertNewInstBefore(SRA, SI);
7590
Reid Spencer3da59db2006-11-27 01:05:10 +00007591 // Finally, convert to the type of the select RHS. We figure out
7592 // if this requires a SExt, Trunc or BitCast based on the sizes.
7593 Instruction::CastOps opc = Instruction::BitCast;
7594 unsigned SRASize = SRA->getType()->getPrimitiveSizeInBits();
7595 unsigned SISize = SI.getType()->getPrimitiveSizeInBits();
7596 if (SRASize < SISize)
7597 opc = Instruction::SExt;
7598 else if (SRASize > SISize)
7599 opc = Instruction::Trunc;
7600 return CastInst::create(opc, SRA, SI.getType());
Chris Lattnerb8456462006-09-20 04:44:59 +00007601 }
7602 }
7603
7604
7605 // If one of the constants is zero (we know they can't both be) and we
Reid Spencere4d87aa2006-12-23 06:05:41 +00007606 // have a fcmp instruction with zero, and we have an 'and' with the
Chris Lattnerb8456462006-09-20 04:44:59 +00007607 // non-constant value, eliminate this whole mess. This corresponds to
7608 // cases like this: ((X & 27) ? 27 : 0)
7609 if (TrueValC->isNullValue() || FalseValC->isNullValue())
Chris Lattner65b72ba2006-09-18 04:22:48 +00007610 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00007611 cast<Constant>(IC->getOperand(1))->isNullValue())
7612 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
7613 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00007614 isa<ConstantInt>(ICA->getOperand(1)) &&
7615 (ICA->getOperand(1) == TrueValC ||
7616 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00007617 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
7618 // Okay, now we know that everything is set up, we just don't
Reid Spencere4d87aa2006-12-23 06:05:41 +00007619 // know whether we have a icmp_ne or icmp_eq and whether the
7620 // true or false val is the zero.
Chris Lattner457dd822004-06-09 07:59:58 +00007621 bool ShouldNotVal = !TrueValC->isNullValue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00007622 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner457dd822004-06-09 07:59:58 +00007623 Value *V = ICA;
7624 if (ShouldNotVal)
7625 V = InsertNewInstBefore(BinaryOperator::create(
7626 Instruction::Xor, V, ICA->getOperand(1)), SI);
7627 return ReplaceInstUsesWith(SI, V);
7628 }
Chris Lattnerb8456462006-09-20 04:44:59 +00007629 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00007630 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00007631
7632 // See if we are selecting two values based on a comparison of the two values.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007633 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
7634 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattnerd76956d2004-04-10 22:21:27 +00007635 // Transform (X == Y) ? X : Y -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00007636 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ)
Chris Lattnerd76956d2004-04-10 22:21:27 +00007637 return ReplaceInstUsesWith(SI, FalseVal);
7638 // Transform (X != Y) ? X : Y -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00007639 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattnerd76956d2004-04-10 22:21:27 +00007640 return ReplaceInstUsesWith(SI, TrueVal);
7641 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7642
Reid Spencere4d87aa2006-12-23 06:05:41 +00007643 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattnerd76956d2004-04-10 22:21:27 +00007644 // Transform (X == Y) ? Y : X -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00007645 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ)
Chris Lattnerfbede522004-04-11 01:39:19 +00007646 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattnerd76956d2004-04-10 22:21:27 +00007647 // Transform (X != Y) ? Y : X -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00007648 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
7649 return ReplaceInstUsesWith(SI, TrueVal);
7650 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7651 }
7652 }
7653
7654 // See if we are selecting two values based on a comparison of the two values.
7655 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
7656 if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
7657 // Transform (X == Y) ? X : Y -> Y
7658 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
7659 return ReplaceInstUsesWith(SI, FalseVal);
7660 // Transform (X != Y) ? X : Y -> X
7661 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
7662 return ReplaceInstUsesWith(SI, TrueVal);
7663 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7664
7665 } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
7666 // Transform (X == Y) ? Y : X -> X
7667 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
7668 return ReplaceInstUsesWith(SI, FalseVal);
7669 // Transform (X != Y) ? Y : X -> Y
7670 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
Chris Lattnerfbede522004-04-11 01:39:19 +00007671 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerd76956d2004-04-10 22:21:27 +00007672 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7673 }
7674 }
Misha Brukmanfd939082005-04-21 23:48:37 +00007675
Chris Lattner87875da2005-01-13 22:52:24 +00007676 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
7677 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
7678 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattner87875da2005-01-13 22:52:24 +00007679 Instruction *AddOp = 0, *SubOp = 0;
7680
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007681 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
7682 if (TI->getOpcode() == FI->getOpcode())
7683 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
7684 return IV;
7685
7686 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
7687 // even legal for FP.
Chris Lattner87875da2005-01-13 22:52:24 +00007688 if (TI->getOpcode() == Instruction::Sub &&
7689 FI->getOpcode() == Instruction::Add) {
7690 AddOp = FI; SubOp = TI;
7691 } else if (FI->getOpcode() == Instruction::Sub &&
7692 TI->getOpcode() == Instruction::Add) {
7693 AddOp = TI; SubOp = FI;
7694 }
7695
7696 if (AddOp) {
7697 Value *OtherAddOp = 0;
7698 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
7699 OtherAddOp = AddOp->getOperand(1);
7700 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
7701 OtherAddOp = AddOp->getOperand(0);
7702 }
7703
7704 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00007705 // So at this point we know we have (Y -> OtherAddOp):
7706 // select C, (add X, Y), (sub X, Z)
7707 Value *NegVal; // Compute -Z
7708 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
7709 NegVal = ConstantExpr::getNeg(C);
7710 } else {
7711 NegVal = InsertNewInstBefore(
7712 BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00007713 }
Chris Lattner97f37a42006-02-24 18:05:58 +00007714
7715 Value *NewTrueOp = OtherAddOp;
7716 Value *NewFalseOp = NegVal;
7717 if (AddOp != TI)
7718 std::swap(NewTrueOp, NewFalseOp);
7719 Instruction *NewSel =
7720 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
7721
7722 NewSel = InsertNewInstBefore(NewSel, SI);
7723 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00007724 }
7725 }
7726 }
Misha Brukmanfd939082005-04-21 23:48:37 +00007727
Chris Lattnere576b912004-04-09 23:46:01 +00007728 // See if we can fold the select into one of our operands.
Chris Lattner42a75512007-01-15 02:27:26 +00007729 if (SI.getType()->isInteger()) {
Chris Lattnere576b912004-04-09 23:46:01 +00007730 // See the comment above GetSelectFoldableOperands for a description of the
7731 // transformation we are doing here.
7732 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
7733 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
7734 !isa<Constant>(FalseVal))
7735 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
7736 unsigned OpToFold = 0;
7737 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
7738 OpToFold = 1;
7739 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
7740 OpToFold = 2;
7741 }
7742
7743 if (OpToFold) {
7744 Constant *C = GetSelectFoldableConstant(TVI);
Chris Lattnere576b912004-04-09 23:46:01 +00007745 Instruction *NewSel =
Chris Lattner6934a042007-02-11 01:23:03 +00007746 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C);
Chris Lattnere576b912004-04-09 23:46:01 +00007747 InsertNewInstBefore(NewSel, SI);
Chris Lattner6934a042007-02-11 01:23:03 +00007748 NewSel->takeName(TVI);
Chris Lattnere576b912004-04-09 23:46:01 +00007749 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
7750 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
Chris Lattnere576b912004-04-09 23:46:01 +00007751 else {
7752 assert(0 && "Unknown instruction!!");
7753 }
7754 }
7755 }
Chris Lattnera96879a2004-09-29 17:40:11 +00007756
Chris Lattnere576b912004-04-09 23:46:01 +00007757 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
7758 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
7759 !isa<Constant>(TrueVal))
7760 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
7761 unsigned OpToFold = 0;
7762 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
7763 OpToFold = 1;
7764 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
7765 OpToFold = 2;
7766 }
7767
7768 if (OpToFold) {
7769 Constant *C = GetSelectFoldableConstant(FVI);
Chris Lattnere576b912004-04-09 23:46:01 +00007770 Instruction *NewSel =
Chris Lattner6934a042007-02-11 01:23:03 +00007771 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold));
Chris Lattnere576b912004-04-09 23:46:01 +00007772 InsertNewInstBefore(NewSel, SI);
Chris Lattner6934a042007-02-11 01:23:03 +00007773 NewSel->takeName(FVI);
Chris Lattnere576b912004-04-09 23:46:01 +00007774 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
7775 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
Reid Spencer832254e2007-02-02 02:16:23 +00007776 else
Chris Lattnere576b912004-04-09 23:46:01 +00007777 assert(0 && "Unknown instruction!!");
Chris Lattnere576b912004-04-09 23:46:01 +00007778 }
7779 }
7780 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00007781
7782 if (BinaryOperator::isNot(CondVal)) {
7783 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
7784 SI.setOperand(1, FalseVal);
7785 SI.setOperand(2, TrueVal);
7786 return &SI;
7787 }
7788
Chris Lattner3d69f462004-03-12 05:52:32 +00007789 return 0;
7790}
7791
Chris Lattner95a959d2006-03-06 20:18:44 +00007792/// GetKnownAlignment - If the specified pointer has an alignment that we can
7793/// determine, return it, otherwise return 0.
7794static unsigned GetKnownAlignment(Value *V, TargetData *TD) {
7795 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
7796 unsigned Align = GV->getAlignment();
7797 if (Align == 0 && TD)
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007798 Align = TD->getPrefTypeAlignment(GV->getType()->getElementType());
Chris Lattner95a959d2006-03-06 20:18:44 +00007799 return Align;
7800 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
7801 unsigned Align = AI->getAlignment();
7802 if (Align == 0 && TD) {
7803 if (isa<AllocaInst>(AI))
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007804 Align = TD->getPrefTypeAlignment(AI->getType()->getElementType());
Chris Lattner95a959d2006-03-06 20:18:44 +00007805 else if (isa<MallocInst>(AI)) {
7806 // Malloc returns maximally aligned memory.
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007807 Align = TD->getABITypeAlignment(AI->getType()->getElementType());
Chris Lattner58092e32007-01-20 22:35:55 +00007808 Align =
7809 std::max(Align,
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007810 (unsigned)TD->getABITypeAlignment(Type::DoubleTy));
Chris Lattner58092e32007-01-20 22:35:55 +00007811 Align =
7812 std::max(Align,
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007813 (unsigned)TD->getABITypeAlignment(Type::Int64Ty));
Chris Lattner95a959d2006-03-06 20:18:44 +00007814 }
7815 }
7816 return Align;
Reid Spencer3da59db2006-11-27 01:05:10 +00007817 } else if (isa<BitCastInst>(V) ||
Chris Lattner51c26e92006-03-07 01:28:57 +00007818 (isa<ConstantExpr>(V) &&
Reid Spencer3da59db2006-11-27 01:05:10 +00007819 cast<ConstantExpr>(V)->getOpcode() == Instruction::BitCast)) {
Chris Lattner51c26e92006-03-07 01:28:57 +00007820 User *CI = cast<User>(V);
Chris Lattner95a959d2006-03-06 20:18:44 +00007821 if (isa<PointerType>(CI->getOperand(0)->getType()))
7822 return GetKnownAlignment(CI->getOperand(0), TD);
7823 return 0;
Chris Lattner51c26e92006-03-07 01:28:57 +00007824 } else if (isa<GetElementPtrInst>(V) ||
7825 (isa<ConstantExpr>(V) &&
7826 cast<ConstantExpr>(V)->getOpcode()==Instruction::GetElementPtr)) {
7827 User *GEPI = cast<User>(V);
Chris Lattner95a959d2006-03-06 20:18:44 +00007828 unsigned BaseAlignment = GetKnownAlignment(GEPI->getOperand(0), TD);
7829 if (BaseAlignment == 0) return 0;
7830
7831 // If all indexes are zero, it is just the alignment of the base pointer.
7832 bool AllZeroOperands = true;
7833 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
7834 if (!isa<Constant>(GEPI->getOperand(i)) ||
7835 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
7836 AllZeroOperands = false;
7837 break;
7838 }
7839 if (AllZeroOperands)
7840 return BaseAlignment;
7841
7842 // Otherwise, if the base alignment is >= the alignment we expect for the
7843 // base pointer type, then we know that the resultant pointer is aligned at
7844 // least as much as its type requires.
7845 if (!TD) return 0;
7846
7847 const Type *BasePtrTy = GEPI->getOperand(0)->getType();
Chris Lattner58092e32007-01-20 22:35:55 +00007848 const PointerType *PtrTy = cast<PointerType>(BasePtrTy);
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007849 if (TD->getABITypeAlignment(PtrTy->getElementType())
Chris Lattner51c26e92006-03-07 01:28:57 +00007850 <= BaseAlignment) {
7851 const Type *GEPTy = GEPI->getType();
Chris Lattner58092e32007-01-20 22:35:55 +00007852 const PointerType *GEPPtrTy = cast<PointerType>(GEPTy);
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007853 return TD->getABITypeAlignment(GEPPtrTy->getElementType());
Chris Lattner51c26e92006-03-07 01:28:57 +00007854 }
Chris Lattner95a959d2006-03-06 20:18:44 +00007855 return 0;
7856 }
7857 return 0;
7858}
7859
Chris Lattner3d69f462004-03-12 05:52:32 +00007860
Chris Lattner8b0ea312006-01-13 20:11:04 +00007861/// visitCallInst - CallInst simplification. This mostly only handles folding
7862/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
7863/// the heavy lifting.
7864///
Chris Lattner9fe38862003-06-19 17:00:31 +00007865Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattner8b0ea312006-01-13 20:11:04 +00007866 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
7867 if (!II) return visitCallSite(&CI);
7868
Chris Lattner7bcc0e72004-02-28 05:22:00 +00007869 // Intrinsics cannot occur in an invoke, so handle them here instead of in
7870 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00007871 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00007872 bool Changed = false;
7873
7874 // memmove/cpy/set of zero bytes is a noop.
7875 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
7876 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
7877
Chris Lattner35b9e482004-10-12 04:52:52 +00007878 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +00007879 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +00007880 // Replace the instruction with just byte operations. We would
7881 // transform other cases to loads/stores, but we don't know if
7882 // alignment is sufficient.
7883 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00007884 }
7885
Chris Lattner35b9e482004-10-12 04:52:52 +00007886 // If we have a memmove and the source operation is a constant global,
7887 // then the source and dest pointers can't alias, so we can change this
7888 // into a call to memcpy.
Chris Lattner95a959d2006-03-06 20:18:44 +00007889 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00007890 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
7891 if (GVSrc->isConstant()) {
7892 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner21959392006-03-03 01:34:17 +00007893 const char *Name;
Andrew Lenharth8ed4c472006-11-03 22:45:50 +00007894 if (CI.getCalledFunction()->getFunctionType()->getParamType(2) ==
Reid Spencerc5b206b2006-12-31 05:48:39 +00007895 Type::Int32Ty)
Chris Lattner21959392006-03-03 01:34:17 +00007896 Name = "llvm.memcpy.i32";
7897 else
7898 Name = "llvm.memcpy.i64";
Chris Lattner92141962007-01-07 06:58:05 +00007899 Constant *MemCpy = M->getOrInsertFunction(Name,
Chris Lattner35b9e482004-10-12 04:52:52 +00007900 CI.getCalledFunction()->getFunctionType());
7901 CI.setOperand(0, MemCpy);
7902 Changed = true;
7903 }
Chris Lattner95a959d2006-03-06 20:18:44 +00007904 }
Chris Lattner35b9e482004-10-12 04:52:52 +00007905
Chris Lattner95a959d2006-03-06 20:18:44 +00007906 // If we can determine a pointer alignment that is bigger than currently
7907 // set, update the alignment.
7908 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
7909 unsigned Alignment1 = GetKnownAlignment(MI->getOperand(1), TD);
7910 unsigned Alignment2 = GetKnownAlignment(MI->getOperand(2), TD);
7911 unsigned Align = std::min(Alignment1, Alignment2);
Reid Spencerb83eb642006-10-20 07:07:24 +00007912 if (MI->getAlignment()->getZExtValue() < Align) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007913 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Align));
Chris Lattner95a959d2006-03-06 20:18:44 +00007914 Changed = true;
7915 }
7916 } else if (isa<MemSetInst>(MI)) {
7917 unsigned Alignment = GetKnownAlignment(MI->getDest(), TD);
Reid Spencerb83eb642006-10-20 07:07:24 +00007918 if (MI->getAlignment()->getZExtValue() < Alignment) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007919 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
Chris Lattner95a959d2006-03-06 20:18:44 +00007920 Changed = true;
7921 }
7922 }
7923
Chris Lattner8b0ea312006-01-13 20:11:04 +00007924 if (Changed) return II;
Chris Lattnera728ddc2006-01-13 21:28:09 +00007925 } else {
7926 switch (II->getIntrinsicID()) {
7927 default: break;
Chris Lattner82ed58f2006-04-02 05:30:25 +00007928 case Intrinsic::ppc_altivec_lvx:
7929 case Intrinsic::ppc_altivec_lvxl:
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00007930 case Intrinsic::x86_sse_loadu_ps:
7931 case Intrinsic::x86_sse2_loadu_pd:
7932 case Intrinsic::x86_sse2_loadu_dq:
7933 // Turn PPC lvx -> load if the pointer is known aligned.
7934 // Turn X86 loadups -> load if the pointer is known aligned.
Chris Lattner82ed58f2006-04-02 05:30:25 +00007935 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
Reid Spencer17212df2006-12-12 09:18:51 +00007936 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
Chris Lattnere2ed0572006-04-06 19:19:17 +00007937 PointerType::get(II->getType()), CI);
Chris Lattner82ed58f2006-04-02 05:30:25 +00007938 return new LoadInst(Ptr);
7939 }
7940 break;
7941 case Intrinsic::ppc_altivec_stvx:
7942 case Intrinsic::ppc_altivec_stvxl:
7943 // Turn stvx -> store if the pointer is known aligned.
7944 if (GetKnownAlignment(II->getOperand(2), TD) >= 16) {
Chris Lattnere2ed0572006-04-06 19:19:17 +00007945 const Type *OpPtrTy = PointerType::get(II->getOperand(1)->getType());
Reid Spencer17212df2006-12-12 09:18:51 +00007946 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(2),
7947 OpPtrTy, CI);
Chris Lattner82ed58f2006-04-02 05:30:25 +00007948 return new StoreInst(II->getOperand(1), Ptr);
7949 }
7950 break;
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00007951 case Intrinsic::x86_sse_storeu_ps:
7952 case Intrinsic::x86_sse2_storeu_pd:
7953 case Intrinsic::x86_sse2_storeu_dq:
7954 case Intrinsic::x86_sse2_storel_dq:
7955 // Turn X86 storeu -> store if the pointer is known aligned.
7956 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
7957 const Type *OpPtrTy = PointerType::get(II->getOperand(2)->getType());
Reid Spencer17212df2006-12-12 09:18:51 +00007958 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
7959 OpPtrTy, CI);
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00007960 return new StoreInst(II->getOperand(2), Ptr);
7961 }
7962 break;
Chris Lattner867b99f2006-10-05 06:55:50 +00007963
7964 case Intrinsic::x86_sse_cvttss2si: {
7965 // These intrinsics only demands the 0th element of its input vector. If
7966 // we can simplify the input based on that, do so now.
7967 uint64_t UndefElts;
7968 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
7969 UndefElts)) {
7970 II->setOperand(1, V);
7971 return II;
7972 }
7973 break;
7974 }
7975
Chris Lattnere2ed0572006-04-06 19:19:17 +00007976 case Intrinsic::ppc_altivec_vperm:
7977 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
Reid Spencer9d6565a2007-02-15 02:26:10 +00007978 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
Chris Lattnere2ed0572006-04-06 19:19:17 +00007979 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
7980
7981 // Check that all of the elements are integer constants or undefs.
7982 bool AllEltsOk = true;
7983 for (unsigned i = 0; i != 16; ++i) {
7984 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
7985 !isa<UndefValue>(Mask->getOperand(i))) {
7986 AllEltsOk = false;
7987 break;
7988 }
7989 }
7990
7991 if (AllEltsOk) {
7992 // Cast the input vectors to byte vectors.
Reid Spencer17212df2006-12-12 09:18:51 +00007993 Value *Op0 = InsertCastBefore(Instruction::BitCast,
7994 II->getOperand(1), Mask->getType(), CI);
7995 Value *Op1 = InsertCastBefore(Instruction::BitCast,
7996 II->getOperand(2), Mask->getType(), CI);
Chris Lattnere2ed0572006-04-06 19:19:17 +00007997 Value *Result = UndefValue::get(Op0->getType());
7998
7999 // Only extract each element once.
8000 Value *ExtractedElts[32];
8001 memset(ExtractedElts, 0, sizeof(ExtractedElts));
8002
8003 for (unsigned i = 0; i != 16; ++i) {
8004 if (isa<UndefValue>(Mask->getOperand(i)))
8005 continue;
Reid Spencerb83eb642006-10-20 07:07:24 +00008006 unsigned Idx =cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
Chris Lattnere2ed0572006-04-06 19:19:17 +00008007 Idx &= 31; // Match the hardware behavior.
8008
8009 if (ExtractedElts[Idx] == 0) {
8010 Instruction *Elt =
Chris Lattner867b99f2006-10-05 06:55:50 +00008011 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00008012 InsertNewInstBefore(Elt, CI);
8013 ExtractedElts[Idx] = Elt;
8014 }
8015
8016 // Insert this value into the result vector.
Chris Lattner867b99f2006-10-05 06:55:50 +00008017 Result = new InsertElementInst(Result, ExtractedElts[Idx], i,"tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00008018 InsertNewInstBefore(cast<Instruction>(Result), CI);
8019 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008020 return CastInst::create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00008021 }
8022 }
8023 break;
8024
Chris Lattnera728ddc2006-01-13 21:28:09 +00008025 case Intrinsic::stackrestore: {
8026 // If the save is right next to the restore, remove the restore. This can
8027 // happen when variable allocas are DCE'd.
8028 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
8029 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
8030 BasicBlock::iterator BI = SS;
8031 if (&*++BI == II)
8032 return EraseInstFromFunction(CI);
8033 }
8034 }
8035
8036 // If the stack restore is in a return/unwind block and if there are no
8037 // allocas or calls between the restore and the return, nuke the restore.
8038 TerminatorInst *TI = II->getParent()->getTerminator();
8039 if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
8040 BasicBlock::iterator BI = II;
8041 bool CannotRemove = false;
8042 for (++BI; &*BI != TI; ++BI) {
8043 if (isa<AllocaInst>(BI) ||
8044 (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
8045 CannotRemove = true;
8046 break;
8047 }
8048 }
8049 if (!CannotRemove)
8050 return EraseInstFromFunction(CI);
8051 }
8052 break;
8053 }
8054 }
Chris Lattner35b9e482004-10-12 04:52:52 +00008055 }
8056
Chris Lattner8b0ea312006-01-13 20:11:04 +00008057 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +00008058}
8059
8060// InvokeInst simplification
8061//
8062Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +00008063 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +00008064}
8065
Chris Lattnera44d8a22003-10-07 22:32:43 +00008066// visitCallSite - Improvements for call and invoke instructions.
8067//
8068Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +00008069 bool Changed = false;
8070
8071 // If the callee is a constexpr cast of a function, attempt to move the cast
8072 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +00008073 if (transformConstExprCastCall(CS)) return 0;
8074
Chris Lattner6c266db2003-10-07 22:54:13 +00008075 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +00008076
Chris Lattner08b22ec2005-05-13 07:09:09 +00008077 if (Function *CalleeF = dyn_cast<Function>(Callee))
8078 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
8079 Instruction *OldCall = CS.getInstruction();
8080 // If the call and callee calling conventions don't match, this call must
8081 // be unreachable, as the call is undefined.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008082 new StoreInst(ConstantInt::getTrue(),
Reid Spencer4fe16d62007-01-11 18:21:29 +00008083 UndefValue::get(PointerType::get(Type::Int1Ty)), OldCall);
Chris Lattner08b22ec2005-05-13 07:09:09 +00008084 if (!OldCall->use_empty())
8085 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
8086 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
8087 return EraseInstFromFunction(*OldCall);
8088 return 0;
8089 }
8090
Chris Lattner17be6352004-10-18 02:59:09 +00008091 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
8092 // This instruction is not reachable, just remove it. We insert a store to
8093 // undef so that we know that this code is not reachable, despite the fact
8094 // that we can't modify the CFG here.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008095 new StoreInst(ConstantInt::getTrue(),
Reid Spencer4fe16d62007-01-11 18:21:29 +00008096 UndefValue::get(PointerType::get(Type::Int1Ty)),
Chris Lattner17be6352004-10-18 02:59:09 +00008097 CS.getInstruction());
8098
8099 if (!CS.getInstruction()->use_empty())
8100 CS.getInstruction()->
8101 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
8102
8103 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
8104 // Don't break the CFG, insert a dummy cond branch.
8105 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008106 ConstantInt::getTrue(), II);
Chris Lattnere87597f2004-10-16 18:11:37 +00008107 }
Chris Lattner17be6352004-10-18 02:59:09 +00008108 return EraseInstFromFunction(*CS.getInstruction());
8109 }
Chris Lattnere87597f2004-10-16 18:11:37 +00008110
Chris Lattner6c266db2003-10-07 22:54:13 +00008111 const PointerType *PTy = cast<PointerType>(Callee->getType());
8112 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
8113 if (FTy->isVarArg()) {
8114 // See if we can optimize any arguments passed through the varargs area of
8115 // the call.
8116 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
8117 E = CS.arg_end(); I != E; ++I)
8118 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
8119 // If this cast does not effect the value passed through the varargs
8120 // area, we can eliminate the use of the cast.
8121 Value *Op = CI->getOperand(0);
Reid Spencer3da59db2006-11-27 01:05:10 +00008122 if (CI->isLosslessCast()) {
Chris Lattner6c266db2003-10-07 22:54:13 +00008123 *I = Op;
8124 Changed = true;
8125 }
8126 }
8127 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008128
Chris Lattner6c266db2003-10-07 22:54:13 +00008129 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +00008130}
8131
Chris Lattner9fe38862003-06-19 17:00:31 +00008132// transformConstExprCastCall - If the callee is a constexpr cast of a function,
8133// attempt to move the cast to the arguments of the call/invoke.
8134//
8135bool InstCombiner::transformConstExprCastCall(CallSite CS) {
8136 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
8137 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +00008138 if (CE->getOpcode() != Instruction::BitCast ||
8139 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +00008140 return false;
Reid Spencer8863f182004-07-18 00:38:32 +00008141 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +00008142 Instruction *Caller = CS.getInstruction();
8143
8144 // Okay, this is a cast from a function to a different type. Unless doing so
8145 // would cause a type conversion of one of our arguments, change this call to
8146 // be a direct call with arguments casted to the appropriate types.
8147 //
8148 const FunctionType *FT = Callee->getFunctionType();
8149 const Type *OldRetTy = Caller->getType();
8150
Chris Lattnerf78616b2004-01-14 06:06:08 +00008151 // Check to see if we are changing the return type...
8152 if (OldRetTy != FT->getReturnType()) {
Reid Spencer5cbf9852007-01-30 20:08:39 +00008153 if (Callee->isDeclaration() && !Caller->use_empty() &&
Chris Lattner46013f42007-01-06 19:53:32 +00008154 // Conversion is ok if changing from pointer to int of same size.
8155 !(isa<PointerType>(FT->getReturnType()) &&
8156 TD->getIntPtrType() == OldRetTy))
Chris Lattnerec479922007-01-06 02:09:32 +00008157 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +00008158
8159 // If the callsite is an invoke instruction, and the return value is used by
8160 // a PHI node in a successor, we cannot change the return type of the call
8161 // because there is no place to put the cast instruction (without breaking
8162 // the critical edge). Bail out in this case.
8163 if (!Caller->use_empty())
8164 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
8165 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
8166 UI != E; ++UI)
8167 if (PHINode *PN = dyn_cast<PHINode>(*UI))
8168 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00008169 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +00008170 return false;
8171 }
Chris Lattner9fe38862003-06-19 17:00:31 +00008172
8173 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
8174 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +00008175
Chris Lattner9fe38862003-06-19 17:00:31 +00008176 CallSite::arg_iterator AI = CS.arg_begin();
8177 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
8178 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +00008179 const Type *ActTy = (*AI)->getType();
Reid Spencer3da59db2006-11-27 01:05:10 +00008180 ConstantInt *c = dyn_cast<ConstantInt>(*AI);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +00008181 //Either we can cast directly, or we can upconvert the argument
Chris Lattnerec479922007-01-06 02:09:32 +00008182 bool isConvertible = ActTy == ParamTy ||
Chris Lattner46013f42007-01-06 19:53:32 +00008183 (isa<PointerType>(ParamTy) && isa<PointerType>(ActTy)) ||
Chris Lattner42a75512007-01-15 02:27:26 +00008184 (ParamTy->isInteger() && ActTy->isInteger() &&
Reid Spencerabaa8ca2007-01-08 16:32:00 +00008185 ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()) ||
8186 (c && ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()
8187 && c->getSExtValue() > 0);
Reid Spencer5cbf9852007-01-30 20:08:39 +00008188 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +00008189 }
8190
8191 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +00008192 Callee->isDeclaration())
Chris Lattner9fe38862003-06-19 17:00:31 +00008193 return false; // Do not delete arguments unless we have a function body...
8194
8195 // Okay, we decided that this is a safe thing to do: go ahead and start
8196 // inserting cast instructions as necessary...
8197 std::vector<Value*> Args;
8198 Args.reserve(NumActualArgs);
8199
8200 AI = CS.arg_begin();
8201 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
8202 const Type *ParamTy = FT->getParamType(i);
8203 if ((*AI)->getType() == ParamTy) {
8204 Args.push_back(*AI);
8205 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +00008206 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +00008207 false, ParamTy, false);
Reid Spencer8a903db2006-12-18 08:47:13 +00008208 CastInst *NewCast = CastInst::create(opcode, *AI, ParamTy, "tmp");
Reid Spencer3da59db2006-11-27 01:05:10 +00008209 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner9fe38862003-06-19 17:00:31 +00008210 }
8211 }
8212
8213 // If the function takes more arguments than the call was taking, add them
8214 // now...
8215 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
8216 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
8217
8218 // If we are removing arguments to the function, emit an obnoxious warning...
8219 if (FT->getNumParams() < NumActualArgs)
8220 if (!FT->isVarArg()) {
Bill Wendlinge8156192006-12-07 01:30:32 +00008221 cerr << "WARNING: While resolving call to function '"
8222 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +00008223 } else {
8224 // Add all of the arguments in their promoted form to the arg list...
8225 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
8226 const Type *PTy = getPromotedType((*AI)->getType());
8227 if (PTy != (*AI)->getType()) {
8228 // Must promote to pass through va_arg area!
Reid Spencerc5b206b2006-12-31 05:48:39 +00008229 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
8230 PTy, false);
Reid Spencer8a903db2006-12-18 08:47:13 +00008231 Instruction *Cast = CastInst::create(opcode, *AI, PTy, "tmp");
Chris Lattner9fe38862003-06-19 17:00:31 +00008232 InsertNewInstBefore(Cast, *Caller);
8233 Args.push_back(Cast);
8234 } else {
8235 Args.push_back(*AI);
8236 }
8237 }
8238 }
8239
8240 if (FT->getReturnType() == Type::VoidTy)
Chris Lattner6934a042007-02-11 01:23:03 +00008241 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +00008242
8243 Instruction *NC;
8244 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00008245 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattner93e985f2007-02-13 02:10:56 +00008246 &Args[0], Args.size(), Caller->getName(), Caller);
Chris Lattnere4370262005-05-14 12:25:32 +00008247 cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
Chris Lattner9fe38862003-06-19 17:00:31 +00008248 } else {
Chris Lattner93e985f2007-02-13 02:10:56 +00008249 NC = new CallInst(Callee, &Args[0], Args.size(), Caller->getName(), Caller);
Chris Lattnera9e92112005-05-06 06:48:21 +00008250 if (cast<CallInst>(Caller)->isTailCall())
8251 cast<CallInst>(NC)->setTailCall();
Chris Lattnere4370262005-05-14 12:25:32 +00008252 cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Chris Lattner9fe38862003-06-19 17:00:31 +00008253 }
8254
Chris Lattner6934a042007-02-11 01:23:03 +00008255 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +00008256 Value *NV = NC;
8257 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
8258 if (NV->getType() != Type::VoidTy) {
Reid Spencer8a903db2006-12-18 08:47:13 +00008259 const Type *CallerTy = Caller->getType();
Reid Spencerc5b206b2006-12-31 05:48:39 +00008260 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
8261 CallerTy, false);
Reid Spencer8a903db2006-12-18 08:47:13 +00008262 NV = NC = CastInst::create(opcode, NC, CallerTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +00008263
8264 // If this is an invoke instruction, we should insert it after the first
8265 // non-phi, instruction in the normal successor block.
8266 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
8267 BasicBlock::iterator I = II->getNormalDest()->begin();
8268 while (isa<PHINode>(I)) ++I;
8269 InsertNewInstBefore(NC, *I);
8270 } else {
8271 // Otherwise, it's a call, just insert cast right after the call instr
8272 InsertNewInstBefore(NC, *Caller);
8273 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00008274 AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00008275 } else {
Chris Lattnerc30bda72004-10-17 21:22:38 +00008276 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +00008277 }
8278 }
8279
8280 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
8281 Caller->replaceAllUsesWith(NV);
Chris Lattnerf22a5c62007-03-02 19:59:19 +00008282 Caller->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +00008283 RemoveFromWorkList(Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00008284 return true;
8285}
8286
Chris Lattner7da52b22006-11-01 04:51:18 +00008287/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
8288/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
8289/// and a single binop.
8290Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
8291 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Reid Spencer832254e2007-02-02 02:16:23 +00008292 assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
8293 isa<CmpInst>(FirstInst));
Chris Lattner7da52b22006-11-01 04:51:18 +00008294 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00008295 Value *LHSVal = FirstInst->getOperand(0);
8296 Value *RHSVal = FirstInst->getOperand(1);
8297
8298 const Type *LHSType = LHSVal->getType();
8299 const Type *RHSType = RHSVal->getType();
Chris Lattner7da52b22006-11-01 04:51:18 +00008300
8301 // Scan to see if all operands are the same opcode, all have one use, and all
8302 // kill their operands (i.e. the operands have one use).
Chris Lattnera90a24c2006-11-01 04:55:47 +00008303 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
Chris Lattner7da52b22006-11-01 04:51:18 +00008304 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnera90a24c2006-11-01 04:55:47 +00008305 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00008306 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattner9c080502006-11-01 07:43:41 +00008307 // types or GEP's with different index types.
8308 I->getOperand(0)->getType() != LHSType ||
8309 I->getOperand(1)->getType() != RHSType)
Chris Lattner7da52b22006-11-01 04:51:18 +00008310 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +00008311
8312 // If they are CmpInst instructions, check their predicates
8313 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
8314 if (cast<CmpInst>(I)->getPredicate() !=
8315 cast<CmpInst>(FirstInst)->getPredicate())
8316 return 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00008317
8318 // Keep track of which operand needs a phi node.
8319 if (I->getOperand(0) != LHSVal) LHSVal = 0;
8320 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattner7da52b22006-11-01 04:51:18 +00008321 }
8322
Chris Lattner53738a42006-11-08 19:42:28 +00008323 // Otherwise, this is safe to transform, determine if it is profitable.
8324
8325 // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
8326 // Indexes are often folded into load/store instructions, so we don't want to
8327 // hide them behind a phi.
8328 if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
8329 return 0;
8330
Chris Lattner7da52b22006-11-01 04:51:18 +00008331 Value *InLHS = FirstInst->getOperand(0);
Chris Lattner7da52b22006-11-01 04:51:18 +00008332 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner53738a42006-11-08 19:42:28 +00008333 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00008334 if (LHSVal == 0) {
8335 NewLHS = new PHINode(LHSType, FirstInst->getOperand(0)->getName()+".pn");
8336 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
8337 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +00008338 InsertNewInstBefore(NewLHS, PN);
8339 LHSVal = NewLHS;
8340 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00008341
8342 if (RHSVal == 0) {
8343 NewRHS = new PHINode(RHSType, FirstInst->getOperand(1)->getName()+".pn");
8344 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
8345 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +00008346 InsertNewInstBefore(NewRHS, PN);
8347 RHSVal = NewRHS;
8348 }
8349
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00008350 // Add all operands to the new PHIs.
8351 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
8352 if (NewLHS) {
8353 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
8354 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
8355 }
8356 if (NewRHS) {
8357 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
8358 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
8359 }
8360 }
8361
Chris Lattner7da52b22006-11-01 04:51:18 +00008362 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattner9c080502006-11-01 07:43:41 +00008363 return BinaryOperator::create(BinOp->getOpcode(), LHSVal, RHSVal);
Reid Spencere4d87aa2006-12-23 06:05:41 +00008364 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
8365 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
8366 RHSVal);
Chris Lattner9c080502006-11-01 07:43:41 +00008367 else {
8368 assert(isa<GetElementPtrInst>(FirstInst));
8369 return new GetElementPtrInst(LHSVal, RHSVal);
8370 }
Chris Lattner7da52b22006-11-01 04:51:18 +00008371}
8372
Chris Lattner76c73142006-11-01 07:13:54 +00008373/// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
8374/// of the block that defines it. This means that it must be obvious the value
8375/// of the load is not changed from the point of the load to the end of the
8376/// block it is in.
Chris Lattnerfd905ca2007-02-01 22:30:07 +00008377///
8378/// Finally, it is safe, but not profitable, to sink a load targetting a
8379/// non-address-taken alloca. Doing so will cause us to not promote the alloca
8380/// to a register.
Chris Lattner76c73142006-11-01 07:13:54 +00008381static bool isSafeToSinkLoad(LoadInst *L) {
8382 BasicBlock::iterator BBI = L, E = L->getParent()->end();
8383
8384 for (++BBI; BBI != E; ++BBI)
8385 if (BBI->mayWriteToMemory())
8386 return false;
Chris Lattnerfd905ca2007-02-01 22:30:07 +00008387
8388 // Check for non-address taken alloca. If not address-taken already, it isn't
8389 // profitable to do this xform.
8390 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
8391 bool isAddressTaken = false;
8392 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
8393 UI != E; ++UI) {
8394 if (isa<LoadInst>(UI)) continue;
8395 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
8396 // If storing TO the alloca, then the address isn't taken.
8397 if (SI->getOperand(1) == AI) continue;
8398 }
8399 isAddressTaken = true;
8400 break;
8401 }
8402
8403 if (!isAddressTaken)
8404 return false;
8405 }
8406
Chris Lattner76c73142006-11-01 07:13:54 +00008407 return true;
8408}
8409
Chris Lattner9fe38862003-06-19 17:00:31 +00008410
Chris Lattnerbac32862004-11-14 19:13:23 +00008411// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
8412// operator and they all are only used by the PHI, PHI together their
8413// inputs, and do the operation once, to the result of the PHI.
8414Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
8415 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
8416
8417 // Scan the instruction, looking for input operations that can be folded away.
8418 // If all input operands to the phi are the same instruction (e.g. a cast from
8419 // the same type or "+42") we can pull the operation through the PHI, reducing
8420 // code size and simplifying code.
8421 Constant *ConstantOp = 0;
8422 const Type *CastSrcTy = 0;
Chris Lattner76c73142006-11-01 07:13:54 +00008423 bool isVolatile = false;
Chris Lattnerbac32862004-11-14 19:13:23 +00008424 if (isa<CastInst>(FirstInst)) {
8425 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer832254e2007-02-02 02:16:23 +00008426 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00008427 // Can fold binop, compare or shift here if the RHS is a constant,
8428 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattnerbac32862004-11-14 19:13:23 +00008429 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattner7da52b22006-11-01 04:51:18 +00008430 if (ConstantOp == 0)
8431 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner76c73142006-11-01 07:13:54 +00008432 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
8433 isVolatile = LI->isVolatile();
8434 // We can't sink the load if the loaded value could be modified between the
8435 // load and the PHI.
8436 if (LI->getParent() != PN.getIncomingBlock(0) ||
8437 !isSafeToSinkLoad(LI))
8438 return 0;
Chris Lattner9c080502006-11-01 07:43:41 +00008439 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner53738a42006-11-08 19:42:28 +00008440 if (FirstInst->getNumOperands() == 2)
Chris Lattner9c080502006-11-01 07:43:41 +00008441 return FoldPHIArgBinOpIntoPHI(PN);
8442 // Can't handle general GEPs yet.
8443 return 0;
Chris Lattnerbac32862004-11-14 19:13:23 +00008444 } else {
8445 return 0; // Cannot fold this operation.
8446 }
8447
8448 // Check to see if all arguments are the same operation.
8449 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
8450 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
8451 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencere4d87aa2006-12-23 06:05:41 +00008452 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattnerbac32862004-11-14 19:13:23 +00008453 return 0;
8454 if (CastSrcTy) {
8455 if (I->getOperand(0)->getType() != CastSrcTy)
8456 return 0; // Cast operation must match.
Chris Lattner76c73142006-11-01 07:13:54 +00008457 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00008458 // We can't sink the load if the loaded value could be modified between
8459 // the load and the PHI.
Chris Lattner76c73142006-11-01 07:13:54 +00008460 if (LI->isVolatile() != isVolatile ||
8461 LI->getParent() != PN.getIncomingBlock(i) ||
8462 !isSafeToSinkLoad(LI))
8463 return 0;
Chris Lattnerbac32862004-11-14 19:13:23 +00008464 } else if (I->getOperand(1) != ConstantOp) {
8465 return 0;
8466 }
8467 }
8468
8469 // Okay, they are all the same operation. Create a new PHI node of the
8470 // correct type, and PHI together all of the LHS's of the instructions.
8471 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
8472 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +00008473 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +00008474
8475 Value *InVal = FirstInst->getOperand(0);
8476 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00008477
8478 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +00008479 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
8480 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
8481 if (NewInVal != InVal)
8482 InVal = 0;
8483 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
8484 }
8485
8486 Value *PhiVal;
8487 if (InVal) {
8488 // The new PHI unions all of the same values together. This is really
8489 // common, so we handle it intelligently here for compile-time speed.
8490 PhiVal = InVal;
8491 delete NewPN;
8492 } else {
8493 InsertNewInstBefore(NewPN, PN);
8494 PhiVal = NewPN;
8495 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008496
Chris Lattnerbac32862004-11-14 19:13:23 +00008497 // Insert and return the new operation.
Reid Spencer3da59db2006-11-27 01:05:10 +00008498 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
8499 return CastInst::create(FirstCI->getOpcode(), PhiVal, PN.getType());
Reid Spencer3ed469c2006-11-02 20:25:50 +00008500 else if (isa<LoadInst>(FirstInst))
Chris Lattner76c73142006-11-01 07:13:54 +00008501 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattnerbac32862004-11-14 19:13:23 +00008502 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattnerb5893442004-11-14 19:29:34 +00008503 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Reid Spencere4d87aa2006-12-23 06:05:41 +00008504 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
8505 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(),
8506 PhiVal, ConstantOp);
Chris Lattnerbac32862004-11-14 19:13:23 +00008507 else
Reid Spencer832254e2007-02-02 02:16:23 +00008508 assert(0 && "Unknown operation");
Jeff Cohenca5183d2007-03-05 00:00:42 +00008509 return 0;
Chris Lattnerbac32862004-11-14 19:13:23 +00008510}
Chris Lattnera1be5662002-05-02 17:06:02 +00008511
Chris Lattnera3fd1c52005-01-17 05:10:15 +00008512/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
8513/// that is dead.
8514static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
8515 if (PN->use_empty()) return true;
8516 if (!PN->hasOneUse()) return false;
8517
8518 // Remember this node, and if we find the cycle, return.
8519 if (!PotentiallyDeadPHIs.insert(PN).second)
8520 return true;
8521
8522 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
8523 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +00008524
Chris Lattnera3fd1c52005-01-17 05:10:15 +00008525 return false;
8526}
8527
Chris Lattner473945d2002-05-06 18:06:38 +00008528// PHINode simplification
8529//
Chris Lattner7e708292002-06-25 16:13:24 +00008530Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +00008531 // If LCSSA is around, don't mess with Phi nodes
Chris Lattnerf964f322007-03-04 04:27:24 +00008532 if (MustPreserveLCSSA) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +00008533
Owen Anderson7e057142006-07-10 22:03:18 +00008534 if (Value *V = PN.hasConstantValue())
8535 return ReplaceInstUsesWith(PN, V);
8536
Owen Anderson7e057142006-07-10 22:03:18 +00008537 // If all PHI operands are the same operation, pull them through the PHI,
8538 // reducing code size.
8539 if (isa<Instruction>(PN.getIncomingValue(0)) &&
8540 PN.getIncomingValue(0)->hasOneUse())
8541 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
8542 return Result;
8543
8544 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
8545 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
8546 // PHI)... break the cycle.
Chris Lattnerff9f13a2007-01-15 07:30:06 +00008547 if (PN.hasOneUse()) {
8548 Instruction *PHIUser = cast<Instruction>(PN.use_back());
8549 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Owen Anderson7e057142006-07-10 22:03:18 +00008550 std::set<PHINode*> PotentiallyDeadPHIs;
8551 PotentiallyDeadPHIs.insert(&PN);
8552 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
8553 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
8554 }
Chris Lattnerff9f13a2007-01-15 07:30:06 +00008555
8556 // If this phi has a single use, and if that use just computes a value for
8557 // the next iteration of a loop, delete the phi. This occurs with unused
8558 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
8559 // common case here is good because the only other things that catch this
8560 // are induction variable analysis (sometimes) and ADCE, which is only run
8561 // late.
8562 if (PHIUser->hasOneUse() &&
8563 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
8564 PHIUser->use_back() == &PN) {
8565 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
8566 }
8567 }
Owen Anderson7e057142006-07-10 22:03:18 +00008568
Chris Lattner60921c92003-12-19 05:58:40 +00008569 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +00008570}
8571
Reid Spencer17212df2006-12-12 09:18:51 +00008572static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
8573 Instruction *InsertPoint,
8574 InstCombiner *IC) {
Reid Spencerabaa8ca2007-01-08 16:32:00 +00008575 unsigned PtrSize = DTy->getPrimitiveSizeInBits();
8576 unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +00008577 // We must cast correctly to the pointer type. Ensure that we
8578 // sign extend the integer value if it is smaller as this is
8579 // used for address computation.
8580 Instruction::CastOps opcode =
8581 (VTySize < PtrSize ? Instruction::SExt :
8582 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
8583 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
Chris Lattner28977af2004-04-05 01:30:19 +00008584}
8585
Chris Lattnera1be5662002-05-02 17:06:02 +00008586
Chris Lattner7e708292002-06-25 16:13:24 +00008587Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +00008588 Value *PtrOp = GEP.getOperand(0);
Chris Lattnerc54e2b82003-05-22 19:07:21 +00008589 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner7e708292002-06-25 16:13:24 +00008590 // If so, eliminate the noop.
Chris Lattnerc6bd1952004-02-22 05:25:17 +00008591 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +00008592 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +00008593
Chris Lattnere87597f2004-10-16 18:11:37 +00008594 if (isa<UndefValue>(GEP.getOperand(0)))
8595 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
8596
Chris Lattnerc6bd1952004-02-22 05:25:17 +00008597 bool HasZeroPointerIndex = false;
8598 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
8599 HasZeroPointerIndex = C->isNullValue();
8600
8601 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +00008602 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +00008603
Chris Lattner28977af2004-04-05 01:30:19 +00008604 // Eliminate unneeded casts for indices.
8605 bool MadeChange = false;
Chris Lattnercb69a4e2004-04-07 18:38:20 +00008606 gep_type_iterator GTI = gep_type_begin(GEP);
8607 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
8608 if (isa<SequentialType>(*GTI)) {
8609 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
Chris Lattner76b7a062007-01-15 07:02:54 +00008610 if (CI->getOpcode() == Instruction::ZExt ||
8611 CI->getOpcode() == Instruction::SExt) {
8612 const Type *SrcTy = CI->getOperand(0)->getType();
8613 // We can eliminate a cast from i32 to i64 iff the target
8614 // is a 32-bit pointer target.
8615 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
8616 MadeChange = true;
8617 GEP.setOperand(i, CI->getOperand(0));
Chris Lattner28977af2004-04-05 01:30:19 +00008618 }
8619 }
8620 }
Chris Lattnercb69a4e2004-04-07 18:38:20 +00008621 // If we are using a wider index than needed for this platform, shrink it
8622 // to what we need. If the incoming value needs a cast instruction,
8623 // insert it. This explicit cast can make subsequent optimizations more
8624 // obvious.
8625 Value *Op = GEP.getOperand(i);
Reid Spencera54b7cb2007-01-12 07:05:14 +00008626 if (TD->getTypeSize(Op->getType()) > TD->getPointerSize())
Chris Lattner4f1134e2004-04-17 18:16:10 +00008627 if (Constant *C = dyn_cast<Constant>(Op)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00008628 GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
Chris Lattner4f1134e2004-04-17 18:16:10 +00008629 MadeChange = true;
8630 } else {
Reid Spencer17212df2006-12-12 09:18:51 +00008631 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
8632 GEP);
Chris Lattnercb69a4e2004-04-07 18:38:20 +00008633 GEP.setOperand(i, Op);
8634 MadeChange = true;
8635 }
Chris Lattner28977af2004-04-05 01:30:19 +00008636 }
8637 if (MadeChange) return &GEP;
8638
Chris Lattner90ac28c2002-08-02 19:29:35 +00008639 // Combine Indices - If the source pointer to this getelementptr instruction
8640 // is a getelementptr instruction, combine the indices of the two
8641 // getelementptr instructions into a single instruction.
8642 //
Chris Lattner72588fc2007-02-15 22:48:32 +00008643 SmallVector<Value*, 8> SrcGEPOperands;
Chris Lattner574da9b2005-01-13 20:14:25 +00008644 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner72588fc2007-02-15 22:48:32 +00008645 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
Chris Lattnerebd985c2004-03-25 22:59:29 +00008646
8647 if (!SrcGEPOperands.empty()) {
Chris Lattner620ce142004-05-07 22:09:22 +00008648 // Note that if our source is a gep chain itself that we wait for that
8649 // chain to be resolved before we perform this transformation. This
8650 // avoids us creating a TON of code in some cases.
8651 //
8652 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
8653 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
8654 return 0; // Wait until our source is folded to completion.
8655
Chris Lattner72588fc2007-02-15 22:48:32 +00008656 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +00008657
8658 // Find out whether the last index in the source GEP is a sequential idx.
8659 bool EndsWithSequential = false;
8660 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
8661 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +00008662 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +00008663
Chris Lattner90ac28c2002-08-02 19:29:35 +00008664 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +00008665 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +00008666 // Replace: gep (gep %P, long B), long A, ...
8667 // With: T = long A+B; gep %P, T, ...
8668 //
Chris Lattner620ce142004-05-07 22:09:22 +00008669 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner28977af2004-04-05 01:30:19 +00008670 if (SO1 == Constant::getNullValue(SO1->getType())) {
8671 Sum = GO1;
8672 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
8673 Sum = SO1;
8674 } else {
8675 // If they aren't the same type, convert both to an integer of the
8676 // target's pointer size.
8677 if (SO1->getType() != GO1->getType()) {
8678 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +00008679 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +00008680 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +00008681 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +00008682 } else {
8683 unsigned PS = TD->getPointerSize();
Reid Spencera54b7cb2007-01-12 07:05:14 +00008684 if (TD->getTypeSize(SO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +00008685 // Convert GO1 to SO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +00008686 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +00008687
Reid Spencera54b7cb2007-01-12 07:05:14 +00008688 } else if (TD->getTypeSize(GO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +00008689 // Convert SO1 to GO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +00008690 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +00008691 } else {
8692 const Type *PT = TD->getIntPtrType();
Reid Spencer17212df2006-12-12 09:18:51 +00008693 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
8694 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +00008695 }
8696 }
8697 }
Chris Lattner620ce142004-05-07 22:09:22 +00008698 if (isa<Constant>(SO1) && isa<Constant>(GO1))
8699 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
8700 else {
Chris Lattner48595f12004-06-10 02:07:29 +00008701 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
8702 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner620ce142004-05-07 22:09:22 +00008703 }
Chris Lattner28977af2004-04-05 01:30:19 +00008704 }
Chris Lattner620ce142004-05-07 22:09:22 +00008705
8706 // Recycle the GEP we already have if possible.
8707 if (SrcGEPOperands.size() == 2) {
8708 GEP.setOperand(0, SrcGEPOperands[0]);
8709 GEP.setOperand(1, Sum);
8710 return &GEP;
8711 } else {
8712 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
8713 SrcGEPOperands.end()-1);
8714 Indices.push_back(Sum);
8715 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
8716 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008717 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +00008718 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanfd939082005-04-21 23:48:37 +00008719 SrcGEPOperands.size() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +00008720 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerebd985c2004-03-25 22:59:29 +00008721 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
8722 SrcGEPOperands.end());
Chris Lattner90ac28c2002-08-02 19:29:35 +00008723 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
8724 }
8725
8726 if (!Indices.empty())
Chris Lattner1ccd1852007-02-12 22:56:41 +00008727 return new GetElementPtrInst(SrcGEPOperands[0], &Indices[0],
8728 Indices.size(), GEP.getName());
Chris Lattner9b761232002-08-17 22:21:59 +00008729
Chris Lattner620ce142004-05-07 22:09:22 +00008730 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattner9b761232002-08-17 22:21:59 +00008731 // GEP of global variable. If all of the indices for this GEP are
8732 // constants, we can promote this to a constexpr instead of an instruction.
8733
8734 // Scan for nonconstants...
Chris Lattner55eb1c42007-01-31 04:40:53 +00008735 SmallVector<Constant*, 8> Indices;
Chris Lattner9b761232002-08-17 22:21:59 +00008736 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
8737 for (; I != E && isa<Constant>(*I); ++I)
8738 Indices.push_back(cast<Constant>(*I));
8739
8740 if (I == E) { // If they are all constants...
Chris Lattner55eb1c42007-01-31 04:40:53 +00008741 Constant *CE = ConstantExpr::getGetElementPtr(GV,
8742 &Indices[0],Indices.size());
Chris Lattner9b761232002-08-17 22:21:59 +00008743
8744 // Replace all uses of the GEP with the new constexpr...
8745 return ReplaceInstUsesWith(GEP, CE);
8746 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008747 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
Chris Lattnereed48272005-09-13 00:40:14 +00008748 if (!isa<PointerType>(X->getType())) {
8749 // Not interesting. Source pointer must be a cast from pointer.
8750 } else if (HasZeroPointerIndex) {
8751 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
8752 // into : GEP [10 x ubyte]* X, long 0, ...
8753 //
8754 // This occurs when the program declares an array extern like "int X[];"
8755 //
8756 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
8757 const PointerType *XTy = cast<PointerType>(X->getType());
8758 if (const ArrayType *XATy =
8759 dyn_cast<ArrayType>(XTy->getElementType()))
8760 if (const ArrayType *CATy =
8761 dyn_cast<ArrayType>(CPTy->getElementType()))
8762 if (CATy->getElementType() == XATy->getElementType()) {
8763 // At this point, we know that the cast source type is a pointer
8764 // to an array of the same type as the destination pointer
8765 // array. Because the array type is never stepped over (there
8766 // is a leading zero) we can fold the cast into this GEP.
8767 GEP.setOperand(0, X);
8768 return &GEP;
8769 }
8770 } else if (GEP.getNumOperands() == 2) {
8771 // Transform things like:
Chris Lattner7835cdd2005-09-13 18:36:04 +00008772 // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
8773 // into: %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
Chris Lattnereed48272005-09-13 00:40:14 +00008774 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
8775 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
8776 if (isa<ArrayType>(SrcElTy) &&
8777 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
8778 TD->getTypeSize(ResElTy)) {
8779 Value *V = InsertNewInstBefore(
Reid Spencerc5b206b2006-12-31 05:48:39 +00008780 new GetElementPtrInst(X, Constant::getNullValue(Type::Int32Ty),
Chris Lattnereed48272005-09-13 00:40:14 +00008781 GEP.getOperand(1), GEP.getName()), GEP);
Reid Spencer3da59db2006-11-27 01:05:10 +00008782 // V and GEP are both pointer types --> BitCast
8783 return new BitCastInst(V, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +00008784 }
Chris Lattner7835cdd2005-09-13 18:36:04 +00008785
8786 // Transform things like:
8787 // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
8788 // (where tmp = 8*tmp2) into:
8789 // getelementptr [100 x double]* %arr, int 0, int %tmp.2
8790
8791 if (isa<ArrayType>(SrcElTy) &&
Reid Spencerc5b206b2006-12-31 05:48:39 +00008792 (ResElTy == Type::Int8Ty || ResElTy == Type::Int8Ty)) {
Chris Lattner7835cdd2005-09-13 18:36:04 +00008793 uint64_t ArrayEltSize =
8794 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
8795
8796 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
8797 // allow either a mul, shift, or constant here.
8798 Value *NewIdx = 0;
8799 ConstantInt *Scale = 0;
8800 if (ArrayEltSize == 1) {
8801 NewIdx = GEP.getOperand(1);
8802 Scale = ConstantInt::get(NewIdx->getType(), 1);
8803 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattner6e2f8432005-09-14 17:32:56 +00008804 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +00008805 Scale = CI;
8806 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
8807 if (Inst->getOpcode() == Instruction::Shl &&
8808 isa<ConstantInt>(Inst->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00008809 unsigned ShAmt =
8810 cast<ConstantInt>(Inst->getOperand(1))->getZExtValue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00008811 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmt);
Chris Lattner7835cdd2005-09-13 18:36:04 +00008812 NewIdx = Inst->getOperand(0);
8813 } else if (Inst->getOpcode() == Instruction::Mul &&
8814 isa<ConstantInt>(Inst->getOperand(1))) {
8815 Scale = cast<ConstantInt>(Inst->getOperand(1));
8816 NewIdx = Inst->getOperand(0);
8817 }
8818 }
8819
8820 // If the index will be to exactly the right offset with the scale taken
8821 // out, perform the transformation.
Reid Spencerb83eb642006-10-20 07:07:24 +00008822 if (Scale && Scale->getZExtValue() % ArrayEltSize == 0) {
Reid Spencer3ed469c2006-11-02 20:25:50 +00008823 if (isa<ConstantInt>(Scale))
Reid Spencerb83eb642006-10-20 07:07:24 +00008824 Scale = ConstantInt::get(Scale->getType(),
8825 Scale->getZExtValue() / ArrayEltSize);
8826 if (Scale->getZExtValue() != 1) {
Reid Spencer17212df2006-12-12 09:18:51 +00008827 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
8828 true /*SExt*/);
Chris Lattner7835cdd2005-09-13 18:36:04 +00008829 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
8830 NewIdx = InsertNewInstBefore(Sc, GEP);
8831 }
8832
8833 // Insert the new GEP instruction.
Reid Spencer3da59db2006-11-27 01:05:10 +00008834 Instruction *NewGEP =
Reid Spencerc5b206b2006-12-31 05:48:39 +00008835 new GetElementPtrInst(X, Constant::getNullValue(Type::Int32Ty),
Chris Lattner7835cdd2005-09-13 18:36:04 +00008836 NewIdx, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +00008837 NewGEP = InsertNewInstBefore(NewGEP, GEP);
8838 // The NewGEP must be pointer typed, so must the old one -> BitCast
8839 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +00008840 }
8841 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +00008842 }
Chris Lattner8a2a3112001-12-14 16:52:21 +00008843 }
8844
Chris Lattner8a2a3112001-12-14 16:52:21 +00008845 return 0;
8846}
8847
Chris Lattner0864acf2002-11-04 16:18:53 +00008848Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
8849 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
8850 if (AI.isArrayAllocation()) // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +00008851 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
8852 const Type *NewTy =
8853 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattner0006bd72002-11-09 00:49:43 +00008854 AllocationInst *New = 0;
Chris Lattner0864acf2002-11-04 16:18:53 +00008855
8856 // Create and insert the replacement instruction...
8857 if (isa<MallocInst>(AI))
Nate Begeman14b05292005-11-05 09:21:28 +00008858 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +00008859 else {
8860 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman14b05292005-11-05 09:21:28 +00008861 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +00008862 }
Chris Lattner7c881df2004-03-19 06:08:10 +00008863
8864 InsertNewInstBefore(New, AI);
Misha Brukmanfd939082005-04-21 23:48:37 +00008865
Chris Lattner0864acf2002-11-04 16:18:53 +00008866 // Scan to the end of the allocation instructions, to skip over a block of
8867 // allocas if possible...
8868 //
8869 BasicBlock::iterator It = New;
8870 while (isa<AllocationInst>(*It)) ++It;
8871
8872 // Now that I is pointing to the first non-allocation-inst in the block,
8873 // insert our getelementptr instruction...
8874 //
Reid Spencerc5b206b2006-12-31 05:48:39 +00008875 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
Chris Lattner693787a2005-05-04 19:10:26 +00008876 Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
8877 New->getName()+".sub", It);
Chris Lattner0864acf2002-11-04 16:18:53 +00008878
8879 // Now make everything use the getelementptr instead of the original
8880 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +00008881 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +00008882 } else if (isa<UndefValue>(AI.getArraySize())) {
8883 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +00008884 }
Chris Lattner7c881df2004-03-19 06:08:10 +00008885
8886 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
8887 // Note that we only do this for alloca's, because malloc should allocate and
8888 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanfd939082005-04-21 23:48:37 +00008889 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Chris Lattnercf27afb2004-07-02 22:55:47 +00008890 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattner7c881df2004-03-19 06:08:10 +00008891 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
8892
Chris Lattner0864acf2002-11-04 16:18:53 +00008893 return 0;
8894}
8895
Chris Lattner67b1e1b2003-12-07 01:24:23 +00008896Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
8897 Value *Op = FI.getOperand(0);
8898
8899 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
8900 if (CastInst *CI = dyn_cast<CastInst>(Op))
8901 if (isa<PointerType>(CI->getOperand(0)->getType())) {
8902 FI.setOperand(0, CI->getOperand(0));
8903 return &FI;
8904 }
8905
Chris Lattner17be6352004-10-18 02:59:09 +00008906 // free undef -> unreachable.
8907 if (isa<UndefValue>(Op)) {
8908 // Insert a new store to null because we cannot modify the CFG here.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008909 new StoreInst(ConstantInt::getTrue(),
Reid Spencer4fe16d62007-01-11 18:21:29 +00008910 UndefValue::get(PointerType::get(Type::Int1Ty)), &FI);
Chris Lattner17be6352004-10-18 02:59:09 +00008911 return EraseInstFromFunction(FI);
8912 }
8913
Chris Lattner6160e852004-02-28 04:57:37 +00008914 // If we have 'free null' delete the instruction. This can happen in stl code
8915 // when lots of inlining happens.
Chris Lattner17be6352004-10-18 02:59:09 +00008916 if (isa<ConstantPointerNull>(Op))
Chris Lattner7bcc0e72004-02-28 05:22:00 +00008917 return EraseInstFromFunction(FI);
Chris Lattner6160e852004-02-28 04:57:37 +00008918
Chris Lattner67b1e1b2003-12-07 01:24:23 +00008919 return 0;
8920}
8921
8922
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00008923/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Chris Lattnerb89e0712004-07-13 01:49:43 +00008924static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
8925 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +00008926 Value *CastOp = CI->getOperand(0);
Chris Lattnerb89e0712004-07-13 01:49:43 +00008927
8928 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +00008929 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattnerb89e0712004-07-13 01:49:43 +00008930 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +00008931
Reid Spencer42230162007-01-22 05:51:25 +00008932 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +00008933 isa<VectorType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +00008934 // If the source is an array, the code below will not succeed. Check to
8935 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
8936 // constants.
8937 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
8938 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
8939 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +00008940 Value *Idxs[2];
8941 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
8942 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerf9527852005-01-31 04:50:46 +00008943 SrcTy = cast<PointerType>(CastOp->getType());
8944 SrcPTy = SrcTy->getElementType();
8945 }
8946
Reid Spencer42230162007-01-22 05:51:25 +00008947 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +00008948 isa<VectorType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +00008949 // Do not allow turning this into a load of an integer, which is then
8950 // casted to a pointer, this pessimizes pointer analysis a lot.
8951 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Reid Spencer42230162007-01-22 05:51:25 +00008952 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
8953 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +00008954
Chris Lattnerf9527852005-01-31 04:50:46 +00008955 // Okay, we are casting from one integer or pointer type to another of
8956 // the same size. Instead of casting the pointer before the load, cast
8957 // the result of the loaded value.
8958 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
8959 CI->getName(),
8960 LI.isVolatile()),LI);
8961 // Now cast the result of the load.
Reid Spencerd977d862006-12-12 23:36:14 +00008962 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerf9527852005-01-31 04:50:46 +00008963 }
Chris Lattnerb89e0712004-07-13 01:49:43 +00008964 }
8965 }
8966 return 0;
8967}
8968
Chris Lattnerc10aced2004-09-19 18:43:46 +00008969/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattner8a375202004-09-19 19:18:10 +00008970/// from this value cannot trap. If it is not obviously safe to load from the
8971/// specified pointer, we do a quick local scan of the basic block containing
8972/// ScanFrom, to determine if the address is already accessed.
8973static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
8974 // If it is an alloca or global variable, it is always safe to load from.
8975 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
8976
8977 // Otherwise, be a little bit agressive by scanning the local block where we
8978 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00008979 // from/to. If so, the previous load or store would have already trapped,
8980 // so there is no harm doing an extra load (also, CSE will later eliminate
8981 // the load entirely).
Chris Lattner8a375202004-09-19 19:18:10 +00008982 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
8983
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00008984 while (BBI != E) {
Chris Lattner8a375202004-09-19 19:18:10 +00008985 --BBI;
8986
8987 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
8988 if (LI->getOperand(0) == V) return true;
8989 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
8990 if (SI->getOperand(1) == V) return true;
Misha Brukmanfd939082005-04-21 23:48:37 +00008991
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00008992 }
Chris Lattner8a375202004-09-19 19:18:10 +00008993 return false;
Chris Lattnerc10aced2004-09-19 18:43:46 +00008994}
8995
Chris Lattner833b8a42003-06-26 05:06:25 +00008996Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
8997 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +00008998
Chris Lattner37366c12005-05-01 04:24:53 +00008999 // load (cast X) --> cast (load X) iff safe
Reid Spencer3ed469c2006-11-02 20:25:50 +00009000 if (isa<CastInst>(Op))
Chris Lattner37366c12005-05-01 04:24:53 +00009001 if (Instruction *Res = InstCombineLoadCast(*this, LI))
9002 return Res;
9003
9004 // None of the following transforms are legal for volatile loads.
9005 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +00009006
Chris Lattner62f254d2005-09-12 22:00:15 +00009007 if (&LI.getParent()->front() != &LI) {
9008 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattner9c1f0fd2005-09-12 22:21:03 +00009009 // If the instruction immediately before this is a store to the same
9010 // address, do a simple form of store->load forwarding.
Chris Lattner62f254d2005-09-12 22:00:15 +00009011 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
9012 if (SI->getOperand(1) == LI.getOperand(0))
9013 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattner9c1f0fd2005-09-12 22:21:03 +00009014 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
9015 if (LIB->getOperand(0) == LI.getOperand(0))
9016 return ReplaceInstUsesWith(LI, LIB);
Chris Lattner62f254d2005-09-12 22:00:15 +00009017 }
Chris Lattner37366c12005-05-01 04:24:53 +00009018
9019 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
9020 if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
9021 isa<UndefValue>(GEPI->getOperand(0))) {
9022 // Insert a new store to null instruction before the load to indicate
9023 // that this code is not reachable. We do this instead of inserting
9024 // an unreachable instruction directly because we cannot modify the
9025 // CFG.
9026 new StoreInst(UndefValue::get(LI.getType()),
9027 Constant::getNullValue(Op->getType()), &LI);
9028 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
9029 }
9030
Chris Lattnere87597f2004-10-16 18:11:37 +00009031 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner37366c12005-05-01 04:24:53 +00009032 // load null/undef -> undef
9033 if ((C->isNullValue() || isa<UndefValue>(C))) {
Chris Lattner17be6352004-10-18 02:59:09 +00009034 // Insert a new store to null instruction before the load to indicate that
9035 // this code is not reachable. We do this instead of inserting an
9036 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattner37366c12005-05-01 04:24:53 +00009037 new StoreInst(UndefValue::get(LI.getType()),
9038 Constant::getNullValue(Op->getType()), &LI);
Chris Lattnere87597f2004-10-16 18:11:37 +00009039 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner17be6352004-10-18 02:59:09 +00009040 }
Chris Lattner833b8a42003-06-26 05:06:25 +00009041
Chris Lattnere87597f2004-10-16 18:11:37 +00009042 // Instcombine load (constant global) into the value loaded.
9043 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Reid Spencer5cbf9852007-01-30 20:08:39 +00009044 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattnere87597f2004-10-16 18:11:37 +00009045 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +00009046
Chris Lattnere87597f2004-10-16 18:11:37 +00009047 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
9048 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
9049 if (CE->getOpcode() == Instruction::GetElementPtr) {
9050 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Reid Spencer5cbf9852007-01-30 20:08:39 +00009051 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattner363f2a22005-09-26 05:28:06 +00009052 if (Constant *V =
9053 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattnere87597f2004-10-16 18:11:37 +00009054 return ReplaceInstUsesWith(LI, V);
Chris Lattner37366c12005-05-01 04:24:53 +00009055 if (CE->getOperand(0)->isNullValue()) {
9056 // Insert a new store to null instruction before the load to indicate
9057 // that this code is not reachable. We do this instead of inserting
9058 // an unreachable instruction directly because we cannot modify the
9059 // CFG.
9060 new StoreInst(UndefValue::get(LI.getType()),
9061 Constant::getNullValue(Op->getType()), &LI);
9062 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
9063 }
9064
Reid Spencer3da59db2006-11-27 01:05:10 +00009065 } else if (CE->isCast()) {
Chris Lattnere87597f2004-10-16 18:11:37 +00009066 if (Instruction *Res = InstCombineLoadCast(*this, LI))
9067 return Res;
9068 }
9069 }
Chris Lattnerf499eac2004-04-08 20:39:49 +00009070
Chris Lattner37366c12005-05-01 04:24:53 +00009071 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +00009072 // Change select and PHI nodes to select values instead of addresses: this
9073 // helps alias analysis out a lot, allows many others simplifications, and
9074 // exposes redundancy in the code.
9075 //
9076 // Note that we cannot do the transformation unless we know that the
9077 // introduced loads cannot trap! Something like this is valid as long as
9078 // the condition is always false: load (select bool %C, int* null, int* %G),
9079 // but it would not be valid if we transformed it to load from null
9080 // unconditionally.
9081 //
9082 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
9083 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +00009084 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
9085 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerc10aced2004-09-19 18:43:46 +00009086 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner79f0c8e2004-09-20 10:15:10 +00009087 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +00009088 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner79f0c8e2004-09-20 10:15:10 +00009089 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +00009090 return new SelectInst(SI->getCondition(), V1, V2);
9091 }
9092
Chris Lattner684fe212004-09-23 15:46:00 +00009093 // load (select (cond, null, P)) -> load P
9094 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
9095 if (C->isNullValue()) {
9096 LI.setOperand(0, SI->getOperand(2));
9097 return &LI;
9098 }
9099
9100 // load (select (cond, P, null)) -> load P
9101 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
9102 if (C->isNullValue()) {
9103 LI.setOperand(0, SI->getOperand(1));
9104 return &LI;
9105 }
Chris Lattnerc10aced2004-09-19 18:43:46 +00009106 }
9107 }
Chris Lattner833b8a42003-06-26 05:06:25 +00009108 return 0;
9109}
9110
Reid Spencer55af2b52007-01-19 21:20:31 +00009111/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009112/// when possible.
9113static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
9114 User *CI = cast<User>(SI.getOperand(1));
9115 Value *CastOp = CI->getOperand(0);
9116
9117 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
9118 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
9119 const Type *SrcPTy = SrcTy->getElementType();
9120
Reid Spencer42230162007-01-22 05:51:25 +00009121 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009122 // If the source is an array, the code below will not succeed. Check to
9123 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
9124 // constants.
9125 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
9126 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
9127 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +00009128 Value* Idxs[2];
9129 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
9130 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009131 SrcTy = cast<PointerType>(CastOp->getType());
9132 SrcPTy = SrcTy->getElementType();
9133 }
9134
Reid Spencer67f827c2007-01-20 23:35:48 +00009135 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
9136 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
9137 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009138
9139 // Okay, we are casting from one integer or pointer type to another of
Reid Spencer75153962007-01-18 18:54:33 +00009140 // the same size. Instead of casting the pointer before
9141 // the store, cast the value to be stored.
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009142 Value *NewCast;
Reid Spencerd977d862006-12-12 23:36:14 +00009143 Value *SIOp0 = SI.getOperand(0);
Reid Spencer75153962007-01-18 18:54:33 +00009144 Instruction::CastOps opcode = Instruction::BitCast;
9145 const Type* CastSrcTy = SIOp0->getType();
9146 const Type* CastDstTy = SrcPTy;
9147 if (isa<PointerType>(CastDstTy)) {
9148 if (CastSrcTy->isInteger())
Reid Spencerd977d862006-12-12 23:36:14 +00009149 opcode = Instruction::IntToPtr;
Reid Spencer67f827c2007-01-20 23:35:48 +00009150 } else if (isa<IntegerType>(CastDstTy)) {
Reid Spencerc55b2432006-12-13 18:21:21 +00009151 if (isa<PointerType>(SIOp0->getType()))
Reid Spencerd977d862006-12-12 23:36:14 +00009152 opcode = Instruction::PtrToInt;
9153 }
9154 if (Constant *C = dyn_cast<Constant>(SIOp0))
Reid Spencer75153962007-01-18 18:54:33 +00009155 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009156 else
Reid Spencer3da59db2006-11-27 01:05:10 +00009157 NewCast = IC.InsertNewInstBefore(
Reid Spencer75153962007-01-18 18:54:33 +00009158 CastInst::create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
9159 SI);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009160 return new StoreInst(NewCast, CastOp);
9161 }
9162 }
9163 }
9164 return 0;
9165}
9166
Chris Lattner2f503e62005-01-31 05:36:43 +00009167Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
9168 Value *Val = SI.getOperand(0);
9169 Value *Ptr = SI.getOperand(1);
9170
9171 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner9ca96412006-02-08 03:25:32 +00009172 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +00009173 ++NumCombined;
9174 return 0;
9175 }
Chris Lattner836692d2007-01-15 06:51:56 +00009176
9177 // If the RHS is an alloca with a single use, zapify the store, making the
9178 // alloca dead.
9179 if (Ptr->hasOneUse()) {
9180 if (isa<AllocaInst>(Ptr)) {
9181 EraseInstFromFunction(SI);
9182 ++NumCombined;
9183 return 0;
9184 }
9185
9186 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
9187 if (isa<AllocaInst>(GEP->getOperand(0)) &&
9188 GEP->getOperand(0)->hasOneUse()) {
9189 EraseInstFromFunction(SI);
9190 ++NumCombined;
9191 return 0;
9192 }
9193 }
Chris Lattner2f503e62005-01-31 05:36:43 +00009194
Chris Lattner9ca96412006-02-08 03:25:32 +00009195 // Do really simple DSE, to catch cases where there are several consequtive
9196 // stores to the same location, separated by a few arithmetic operations. This
9197 // situation often occurs with bitfield accesses.
9198 BasicBlock::iterator BBI = &SI;
9199 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
9200 --ScanInsts) {
9201 --BBI;
9202
9203 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
9204 // Prev store isn't volatile, and stores to the same location?
9205 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
9206 ++NumDeadStore;
9207 ++BBI;
9208 EraseInstFromFunction(*PrevSI);
9209 continue;
9210 }
9211 break;
9212 }
9213
Chris Lattnerb4db97f2006-05-26 19:19:20 +00009214 // If this is a load, we have to stop. However, if the loaded value is from
9215 // the pointer we're loading and is producing the pointer we're storing,
9216 // then *this* store is dead (X = load P; store X -> P).
9217 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
9218 if (LI == Val && LI->getOperand(0) == Ptr) {
9219 EraseInstFromFunction(SI);
9220 ++NumCombined;
9221 return 0;
9222 }
9223 // Otherwise, this is a load from some other location. Stores before it
9224 // may not be dead.
9225 break;
9226 }
9227
Chris Lattner9ca96412006-02-08 03:25:32 +00009228 // Don't skip over loads or things that can modify memory.
Chris Lattnerb4db97f2006-05-26 19:19:20 +00009229 if (BBI->mayWriteToMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +00009230 break;
9231 }
9232
9233
9234 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +00009235
9236 // store X, null -> turns into 'unreachable' in SimplifyCFG
9237 if (isa<ConstantPointerNull>(Ptr)) {
9238 if (!isa<UndefValue>(Val)) {
9239 SI.setOperand(0, UndefValue::get(Val->getType()));
9240 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattnerdbab3862007-03-02 21:28:56 +00009241 AddToWorkList(U); // Dropped a use.
Chris Lattner2f503e62005-01-31 05:36:43 +00009242 ++NumCombined;
9243 }
9244 return 0; // Do not modify these!
9245 }
9246
9247 // store undef, Ptr -> noop
9248 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +00009249 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +00009250 ++NumCombined;
9251 return 0;
9252 }
9253
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009254 // If the pointer destination is a cast, see if we can fold the cast into the
9255 // source instead.
Reid Spencer3ed469c2006-11-02 20:25:50 +00009256 if (isa<CastInst>(Ptr))
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009257 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
9258 return Res;
9259 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer3da59db2006-11-27 01:05:10 +00009260 if (CE->isCast())
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009261 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
9262 return Res;
9263
Chris Lattner408902b2005-09-12 23:23:25 +00009264
9265 // If this store is the last instruction in the basic block, and if the block
9266 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner9ca96412006-02-08 03:25:32 +00009267 BBI = &SI; ++BBI;
Chris Lattner408902b2005-09-12 23:23:25 +00009268 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
9269 if (BI->isUnconditional()) {
9270 // Check to see if the successor block has exactly two incoming edges. If
9271 // so, see if the other predecessor contains a store to the same location.
9272 // if so, insert a PHI node (if needed) and move the stores down.
9273 BasicBlock *Dest = BI->getSuccessor(0);
9274
9275 pred_iterator PI = pred_begin(Dest);
9276 BasicBlock *Other = 0;
9277 if (*PI != BI->getParent())
9278 Other = *PI;
9279 ++PI;
9280 if (PI != pred_end(Dest)) {
9281 if (*PI != BI->getParent())
9282 if (Other)
9283 Other = 0;
9284 else
9285 Other = *PI;
9286 if (++PI != pred_end(Dest))
9287 Other = 0;
9288 }
9289 if (Other) { // If only one other pred...
9290 BBI = Other->getTerminator();
9291 // Make sure this other block ends in an unconditional branch and that
9292 // there is an instruction before the branch.
9293 if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
9294 BBI != Other->begin()) {
9295 --BBI;
9296 StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
9297
9298 // If this instruction is a store to the same location.
9299 if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
9300 // Okay, we know we can perform this transformation. Insert a PHI
9301 // node now if we need it.
9302 Value *MergedVal = OtherStore->getOperand(0);
9303 if (MergedVal != SI.getOperand(0)) {
9304 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
9305 PN->reserveOperandSpace(2);
9306 PN->addIncoming(SI.getOperand(0), SI.getParent());
9307 PN->addIncoming(OtherStore->getOperand(0), Other);
9308 MergedVal = InsertNewInstBefore(PN, Dest->front());
9309 }
9310
9311 // Advance to a place where it is safe to insert the new store and
9312 // insert it.
9313 BBI = Dest->begin();
9314 while (isa<PHINode>(BBI)) ++BBI;
9315 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
9316 OtherStore->isVolatile()), *BBI);
9317
9318 // Nuke the old stores.
Chris Lattner9ca96412006-02-08 03:25:32 +00009319 EraseInstFromFunction(SI);
9320 EraseInstFromFunction(*OtherStore);
Chris Lattner408902b2005-09-12 23:23:25 +00009321 ++NumCombined;
9322 return 0;
9323 }
9324 }
9325 }
9326 }
9327
Chris Lattner2f503e62005-01-31 05:36:43 +00009328 return 0;
9329}
9330
9331
Chris Lattnerc4d10eb2003-06-04 04:46:00 +00009332Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
9333 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +00009334 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00009335 BasicBlock *TrueDest;
9336 BasicBlock *FalseDest;
9337 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
9338 !isa<Constant>(X)) {
9339 // Swap Destinations and condition...
9340 BI.setCondition(X);
9341 BI.setSuccessor(0, FalseDest);
9342 BI.setSuccessor(1, TrueDest);
9343 return &BI;
9344 }
9345
Reid Spencere4d87aa2006-12-23 06:05:41 +00009346 // Cannonicalize fcmp_one -> fcmp_oeq
9347 FCmpInst::Predicate FPred; Value *Y;
9348 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
9349 TrueDest, FalseDest)))
9350 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
9351 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
9352 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +00009353 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
Chris Lattner6934a042007-02-11 01:23:03 +00009354 Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
9355 NewSCC->takeName(I);
Reid Spencere4d87aa2006-12-23 06:05:41 +00009356 // Swap Destinations and condition...
9357 BI.setCondition(NewSCC);
9358 BI.setSuccessor(0, FalseDest);
9359 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +00009360 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +00009361 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +00009362 AddToWorkList(NewSCC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00009363 return &BI;
9364 }
9365
9366 // Cannonicalize icmp_ne -> icmp_eq
9367 ICmpInst::Predicate IPred;
9368 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
9369 TrueDest, FalseDest)))
9370 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
9371 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
9372 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
9373 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +00009374 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
Chris Lattner6934a042007-02-11 01:23:03 +00009375 Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
9376 NewSCC->takeName(I);
Chris Lattner40f5d702003-06-04 05:10:11 +00009377 // Swap Destinations and condition...
Chris Lattneracd1f0f2004-07-30 07:50:03 +00009378 BI.setCondition(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +00009379 BI.setSuccessor(0, FalseDest);
9380 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +00009381 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +00009382 I->eraseFromParent();;
Chris Lattnerdbab3862007-03-02 21:28:56 +00009383 AddToWorkList(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +00009384 return &BI;
9385 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009386
Chris Lattnerc4d10eb2003-06-04 04:46:00 +00009387 return 0;
9388}
Chris Lattner0864acf2002-11-04 16:18:53 +00009389
Chris Lattner46238a62004-07-03 00:26:11 +00009390Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
9391 Value *Cond = SI.getCondition();
9392 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
9393 if (I->getOpcode() == Instruction::Add)
9394 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
9395 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
9396 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattnere87597f2004-10-16 18:11:37 +00009397 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +00009398 AddRHS));
9399 SI.setOperand(0, I->getOperand(0));
Chris Lattnerdbab3862007-03-02 21:28:56 +00009400 AddToWorkList(I);
Chris Lattner46238a62004-07-03 00:26:11 +00009401 return &SI;
9402 }
9403 }
9404 return 0;
9405}
9406
Chris Lattner220b0cf2006-03-05 00:22:33 +00009407/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
9408/// is to leave as a vector operation.
9409static bool CheapToScalarize(Value *V, bool isConstant) {
9410 if (isa<ConstantAggregateZero>(V))
9411 return true;
Reid Spencer9d6565a2007-02-15 02:26:10 +00009412 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +00009413 if (isConstant) return true;
9414 // If all elts are the same, we can extract.
9415 Constant *Op0 = C->getOperand(0);
9416 for (unsigned i = 1; i < C->getNumOperands(); ++i)
9417 if (C->getOperand(i) != Op0)
9418 return false;
9419 return true;
9420 }
9421 Instruction *I = dyn_cast<Instruction>(V);
9422 if (!I) return false;
9423
9424 // Insert element gets simplified to the inserted element or is deleted if
9425 // this is constant idx extract element and its a constant idx insertelt.
9426 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
9427 isa<ConstantInt>(I->getOperand(2)))
9428 return true;
9429 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
9430 return true;
9431 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
9432 if (BO->hasOneUse() &&
9433 (CheapToScalarize(BO->getOperand(0), isConstant) ||
9434 CheapToScalarize(BO->getOperand(1), isConstant)))
9435 return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +00009436 if (CmpInst *CI = dyn_cast<CmpInst>(I))
9437 if (CI->hasOneUse() &&
9438 (CheapToScalarize(CI->getOperand(0), isConstant) ||
9439 CheapToScalarize(CI->getOperand(1), isConstant)))
9440 return true;
Chris Lattner220b0cf2006-03-05 00:22:33 +00009441
9442 return false;
9443}
9444
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00009445/// Read and decode a shufflevector mask.
9446///
9447/// It turns undef elements into values that are larger than the number of
9448/// elements in the input.
Chris Lattner863bcff2006-05-25 23:48:38 +00009449static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
9450 unsigned NElts = SVI->getType()->getNumElements();
9451 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
9452 return std::vector<unsigned>(NElts, 0);
9453 if (isa<UndefValue>(SVI->getOperand(2)))
9454 return std::vector<unsigned>(NElts, 2*NElts);
9455
9456 std::vector<unsigned> Result;
Reid Spencer9d6565a2007-02-15 02:26:10 +00009457 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Chris Lattner863bcff2006-05-25 23:48:38 +00009458 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
9459 if (isa<UndefValue>(CP->getOperand(i)))
9460 Result.push_back(NElts*2); // undef -> 8
9461 else
Reid Spencerb83eb642006-10-20 07:07:24 +00009462 Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
Chris Lattner863bcff2006-05-25 23:48:38 +00009463 return Result;
9464}
9465
Chris Lattner6e6b0da2006-03-31 23:01:56 +00009466/// FindScalarElement - Given a vector and an element number, see if the scalar
9467/// value is already around as a register, for example if it were inserted then
9468/// extracted from the vector.
9469static Value *FindScalarElement(Value *V, unsigned EltNo) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00009470 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
9471 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +00009472 unsigned Width = PTy->getNumElements();
9473 if (EltNo >= Width) // Out of range access.
Chris Lattner6e6b0da2006-03-31 23:01:56 +00009474 return UndefValue::get(PTy->getElementType());
9475
9476 if (isa<UndefValue>(V))
9477 return UndefValue::get(PTy->getElementType());
9478 else if (isa<ConstantAggregateZero>(V))
9479 return Constant::getNullValue(PTy->getElementType());
Reid Spencer9d6565a2007-02-15 02:26:10 +00009480 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner6e6b0da2006-03-31 23:01:56 +00009481 return CP->getOperand(EltNo);
9482 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
9483 // If this is an insert to a variable element, we don't know what it is.
Reid Spencerb83eb642006-10-20 07:07:24 +00009484 if (!isa<ConstantInt>(III->getOperand(2)))
9485 return 0;
9486 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner6e6b0da2006-03-31 23:01:56 +00009487
9488 // If this is an insert to the element we are looking for, return the
9489 // inserted value.
Reid Spencerb83eb642006-10-20 07:07:24 +00009490 if (EltNo == IIElt)
9491 return III->getOperand(1);
Chris Lattner6e6b0da2006-03-31 23:01:56 +00009492
9493 // Otherwise, the insertelement doesn't modify the value, recurse on its
9494 // vector input.
9495 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner389a6f52006-04-10 23:06:36 +00009496 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Chris Lattner863bcff2006-05-25 23:48:38 +00009497 unsigned InEl = getShuffleMask(SVI)[EltNo];
9498 if (InEl < Width)
9499 return FindScalarElement(SVI->getOperand(0), InEl);
9500 else if (InEl < Width*2)
9501 return FindScalarElement(SVI->getOperand(1), InEl - Width);
9502 else
9503 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +00009504 }
9505
9506 // Otherwise, we don't know.
9507 return 0;
9508}
9509
Robert Bocchino1d7456d2006-01-13 22:48:06 +00009510Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Chris Lattner6e6b0da2006-03-31 23:01:56 +00009511
Chris Lattner1f13c882006-03-31 18:25:14 +00009512 // If packed val is undef, replace extract with scalar undef.
9513 if (isa<UndefValue>(EI.getOperand(0)))
9514 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
9515
9516 // If packed val is constant 0, replace extract with scalar 0.
9517 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
9518 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
9519
Reid Spencer9d6565a2007-02-15 02:26:10 +00009520 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Robert Bocchino1d7456d2006-01-13 22:48:06 +00009521 // If packed val is constant with uniform operands, replace EI
9522 // with that operand
Chris Lattner220b0cf2006-03-05 00:22:33 +00009523 Constant *op0 = C->getOperand(0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +00009524 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +00009525 if (C->getOperand(i) != op0) {
9526 op0 = 0;
9527 break;
9528 }
9529 if (op0)
9530 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +00009531 }
Chris Lattner220b0cf2006-03-05 00:22:33 +00009532
Chris Lattner6e6b0da2006-03-31 23:01:56 +00009533 // If extracting a specified index from the vector, see if we can recursively
9534 // find a previously computed scalar that was inserted into the vector.
Reid Spencerb83eb642006-10-20 07:07:24 +00009535 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner867b99f2006-10-05 06:55:50 +00009536 // This instruction only demands the single element from the input vector.
9537 // If the input vector has a single use, simplify it based on this use
9538 // property.
Reid Spencerb83eb642006-10-20 07:07:24 +00009539 uint64_t IndexVal = IdxC->getZExtValue();
Chris Lattner867b99f2006-10-05 06:55:50 +00009540 if (EI.getOperand(0)->hasOneUse()) {
9541 uint64_t UndefElts;
9542 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Reid Spencerb83eb642006-10-20 07:07:24 +00009543 1 << IndexVal,
Chris Lattner867b99f2006-10-05 06:55:50 +00009544 UndefElts)) {
9545 EI.setOperand(0, V);
9546 return &EI;
9547 }
9548 }
9549
Reid Spencerb83eb642006-10-20 07:07:24 +00009550 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
Chris Lattner6e6b0da2006-03-31 23:01:56 +00009551 return ReplaceInstUsesWith(EI, Elt);
Chris Lattner389a6f52006-04-10 23:06:36 +00009552 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +00009553
Chris Lattner73fa49d2006-05-25 22:53:38 +00009554 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchino1d7456d2006-01-13 22:48:06 +00009555 if (I->hasOneUse()) {
9556 // Push extractelement into predecessor operation if legal and
9557 // profitable to do so
9558 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +00009559 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
9560 if (CheapToScalarize(BO, isConstantElt)) {
9561 ExtractElementInst *newEI0 =
9562 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
9563 EI.getName()+".lhs");
9564 ExtractElementInst *newEI1 =
9565 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
9566 EI.getName()+".rhs");
9567 InsertNewInstBefore(newEI0, EI);
9568 InsertNewInstBefore(newEI1, EI);
9569 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
9570 }
Reid Spencer3ed469c2006-11-02 20:25:50 +00009571 } else if (isa<LoadInst>(I)) {
Reid Spencer17212df2006-12-12 09:18:51 +00009572 Value *Ptr = InsertCastBefore(Instruction::BitCast, I->getOperand(0),
Robert Bocchino1d7456d2006-01-13 22:48:06 +00009573 PointerType::get(EI.getType()), EI);
9574 GetElementPtrInst *GEP =
Reid Spencerde331242006-11-29 01:11:01 +00009575 new GetElementPtrInst(Ptr, EI.getOperand(1), I->getName() + ".gep");
Robert Bocchino1d7456d2006-01-13 22:48:06 +00009576 InsertNewInstBefore(GEP, EI);
9577 return new LoadInst(GEP);
Chris Lattner73fa49d2006-05-25 22:53:38 +00009578 }
9579 }
9580 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
9581 // Extracting the inserted element?
9582 if (IE->getOperand(2) == EI.getOperand(1))
9583 return ReplaceInstUsesWith(EI, IE->getOperand(1));
9584 // If the inserted and extracted elements are constants, they must not
9585 // be the same value, extract from the pre-inserted value instead.
9586 if (isa<Constant>(IE->getOperand(2)) &&
9587 isa<Constant>(EI.getOperand(1))) {
9588 AddUsesToWorkList(EI);
9589 EI.setOperand(0, IE->getOperand(0));
9590 return &EI;
9591 }
9592 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
9593 // If this is extracting an element from a shufflevector, figure out where
9594 // it came from and extract from the appropriate input element instead.
Reid Spencerb83eb642006-10-20 07:07:24 +00009595 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
9596 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner863bcff2006-05-25 23:48:38 +00009597 Value *Src;
9598 if (SrcIdx < SVI->getType()->getNumElements())
9599 Src = SVI->getOperand(0);
9600 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
9601 SrcIdx -= SVI->getType()->getNumElements();
9602 Src = SVI->getOperand(1);
9603 } else {
9604 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +00009605 }
Chris Lattner867b99f2006-10-05 06:55:50 +00009606 return new ExtractElementInst(Src, SrcIdx);
Robert Bocchino1d7456d2006-01-13 22:48:06 +00009607 }
9608 }
Chris Lattner73fa49d2006-05-25 22:53:38 +00009609 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +00009610 return 0;
9611}
9612
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00009613/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
9614/// elements from either LHS or RHS, return the shuffle mask and true.
9615/// Otherwise, return false.
9616static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
9617 std::vector<Constant*> &Mask) {
9618 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
9619 "Invalid CollectSingleShuffleElements");
Reid Spencer9d6565a2007-02-15 02:26:10 +00009620 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00009621
9622 if (isa<UndefValue>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00009623 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00009624 return true;
9625 } else if (V == LHS) {
9626 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +00009627 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00009628 return true;
9629 } else if (V == RHS) {
9630 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +00009631 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00009632 return true;
9633 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
9634 // If this is an insert of an extract from some other vector, include it.
9635 Value *VecOp = IEI->getOperand(0);
9636 Value *ScalarOp = IEI->getOperand(1);
9637 Value *IdxOp = IEI->getOperand(2);
9638
Chris Lattnerd929f062006-04-27 21:14:21 +00009639 if (!isa<ConstantInt>(IdxOp))
9640 return false;
Reid Spencerb83eb642006-10-20 07:07:24 +00009641 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerd929f062006-04-27 21:14:21 +00009642
9643 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
9644 // Okay, we can handle this if the vector we are insertinting into is
9645 // transitively ok.
9646 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
9647 // If so, update the mask to reflect the inserted undef.
Reid Spencerc5b206b2006-12-31 05:48:39 +00009648 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
Chris Lattnerd929f062006-04-27 21:14:21 +00009649 return true;
9650 }
9651 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
9652 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00009653 EI->getOperand(0)->getType() == V->getType()) {
9654 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +00009655 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00009656
9657 // This must be extracting from either LHS or RHS.
9658 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
9659 // Okay, we can handle this if the vector we are insertinting into is
9660 // transitively ok.
9661 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
9662 // If so, update the mask to reflect the inserted value.
9663 if (EI->getOperand(0) == LHS) {
9664 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +00009665 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00009666 } else {
9667 assert(EI->getOperand(0) == RHS);
9668 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +00009669 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00009670
9671 }
9672 return true;
9673 }
9674 }
9675 }
9676 }
9677 }
9678 // TODO: Handle shufflevector here!
9679
9680 return false;
9681}
9682
9683/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
9684/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
9685/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +00009686static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00009687 Value *&RHS) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00009688 assert(isa<VectorType>(V->getType()) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00009689 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +00009690 "Invalid shuffle!");
Reid Spencer9d6565a2007-02-15 02:26:10 +00009691 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattnerefb47352006-04-15 01:39:45 +00009692
9693 if (isa<UndefValue>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00009694 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +00009695 return V;
9696 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00009697 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
Chris Lattnerefb47352006-04-15 01:39:45 +00009698 return V;
9699 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
9700 // If this is an insert of an extract from some other vector, include it.
9701 Value *VecOp = IEI->getOperand(0);
9702 Value *ScalarOp = IEI->getOperand(1);
9703 Value *IdxOp = IEI->getOperand(2);
9704
9705 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
9706 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
9707 EI->getOperand(0)->getType() == V->getType()) {
9708 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +00009709 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
9710 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +00009711
9712 // Either the extracted from or inserted into vector must be RHSVec,
9713 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00009714 if (EI->getOperand(0) == RHS || RHS == 0) {
9715 RHS = EI->getOperand(0);
9716 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +00009717 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +00009718 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +00009719 return V;
9720 }
9721
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00009722 if (VecOp == RHS) {
9723 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +00009724 // Everything but the extracted element is replaced with the RHS.
9725 for (unsigned i = 0; i != NumElts; ++i) {
9726 if (i != InsertedIdx)
Reid Spencerc5b206b2006-12-31 05:48:39 +00009727 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
Chris Lattnerefb47352006-04-15 01:39:45 +00009728 }
9729 return V;
9730 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00009731
9732 // If this insertelement is a chain that comes from exactly these two
9733 // vectors, return the vector and the effective shuffle.
9734 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
9735 return EI->getOperand(0);
9736
Chris Lattnerefb47352006-04-15 01:39:45 +00009737 }
9738 }
9739 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00009740 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +00009741
9742 // Otherwise, can't do anything fancy. Return an identity vector.
9743 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +00009744 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattnerefb47352006-04-15 01:39:45 +00009745 return V;
9746}
9747
9748Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
9749 Value *VecOp = IE.getOperand(0);
9750 Value *ScalarOp = IE.getOperand(1);
9751 Value *IdxOp = IE.getOperand(2);
9752
9753 // If the inserted element was extracted from some other vector, and if the
9754 // indexes are constant, try to turn this into a shufflevector operation.
9755 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
9756 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
9757 EI->getOperand(0)->getType() == IE.getType()) {
9758 unsigned NumVectorElts = IE.getType()->getNumElements();
Reid Spencerb83eb642006-10-20 07:07:24 +00009759 unsigned ExtractedIdx=cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
9760 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +00009761
9762 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
9763 return ReplaceInstUsesWith(IE, VecOp);
9764
9765 if (InsertedIdx >= NumVectorElts) // Out of range insert.
9766 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
9767
9768 // If we are extracting a value from a vector, then inserting it right
9769 // back into the same place, just use the input vector.
9770 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
9771 return ReplaceInstUsesWith(IE, VecOp);
9772
9773 // We could theoretically do this for ANY input. However, doing so could
9774 // turn chains of insertelement instructions into a chain of shufflevector
9775 // instructions, and right now we do not merge shufflevectors. As such,
9776 // only do this in a situation where it is clear that there is benefit.
9777 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
9778 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
9779 // the values of VecOp, except then one read from EIOp0.
9780 // Build a new shuffle mask.
9781 std::vector<Constant*> Mask;
9782 if (isa<UndefValue>(VecOp))
Reid Spencerc5b206b2006-12-31 05:48:39 +00009783 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +00009784 else {
9785 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Reid Spencerc5b206b2006-12-31 05:48:39 +00009786 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
Chris Lattnerefb47352006-04-15 01:39:45 +00009787 NumVectorElts));
9788 }
Reid Spencerc5b206b2006-12-31 05:48:39 +00009789 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +00009790 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Reid Spencer9d6565a2007-02-15 02:26:10 +00009791 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +00009792 }
9793
9794 // If this insertelement isn't used by some other insertelement, turn it
9795 // (and any insertelements it points to), into one big shuffle.
9796 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
9797 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00009798 Value *RHS = 0;
9799 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
9800 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
9801 // We now have a shuffle of LHS, RHS, Mask.
Reid Spencer9d6565a2007-02-15 02:26:10 +00009802 return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +00009803 }
9804 }
9805 }
9806
9807 return 0;
9808}
9809
9810
Chris Lattnera844fc4c2006-04-10 22:45:52 +00009811Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
9812 Value *LHS = SVI.getOperand(0);
9813 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +00009814 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +00009815
9816 bool MadeChange = false;
9817
Chris Lattner867b99f2006-10-05 06:55:50 +00009818 // Undefined shuffle mask -> undefined value.
Chris Lattner863bcff2006-05-25 23:48:38 +00009819 if (isa<UndefValue>(SVI.getOperand(2)))
Chris Lattnera844fc4c2006-04-10 22:45:52 +00009820 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
9821
Chris Lattnere4929dd2007-01-05 07:36:08 +00009822 // If we have shuffle(x, undef, mask) and any elements of mask refer to
Chris Lattnerefb47352006-04-15 01:39:45 +00009823 // the undef, change them to undefs.
Chris Lattnere4929dd2007-01-05 07:36:08 +00009824 if (isa<UndefValue>(SVI.getOperand(1))) {
9825 // Scan to see if there are any references to the RHS. If so, replace them
9826 // with undef element refs and set MadeChange to true.
9827 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
9828 if (Mask[i] >= e && Mask[i] != 2*e) {
9829 Mask[i] = 2*e;
9830 MadeChange = true;
9831 }
9832 }
9833
9834 if (MadeChange) {
9835 // Remap any references to RHS to use LHS.
9836 std::vector<Constant*> Elts;
9837 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
9838 if (Mask[i] == 2*e)
9839 Elts.push_back(UndefValue::get(Type::Int32Ty));
9840 else
9841 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
9842 }
Reid Spencer9d6565a2007-02-15 02:26:10 +00009843 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattnere4929dd2007-01-05 07:36:08 +00009844 }
9845 }
Chris Lattnerefb47352006-04-15 01:39:45 +00009846
Chris Lattner863bcff2006-05-25 23:48:38 +00009847 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
9848 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
9849 if (LHS == RHS || isa<UndefValue>(LHS)) {
9850 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +00009851 // shuffle(undef,undef,mask) -> undef.
9852 return ReplaceInstUsesWith(SVI, LHS);
9853 }
9854
Chris Lattner863bcff2006-05-25 23:48:38 +00009855 // Remap any references to RHS to use LHS.
9856 std::vector<Constant*> Elts;
9857 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +00009858 if (Mask[i] >= 2*e)
Reid Spencerc5b206b2006-12-31 05:48:39 +00009859 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +00009860 else {
9861 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
9862 (Mask[i] < e && isa<UndefValue>(LHS)))
9863 Mask[i] = 2*e; // Turn into undef.
9864 else
9865 Mask[i] &= (e-1); // Force to LHS.
Reid Spencerc5b206b2006-12-31 05:48:39 +00009866 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +00009867 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +00009868 }
Chris Lattner863bcff2006-05-25 23:48:38 +00009869 SVI.setOperand(0, SVI.getOperand(1));
Chris Lattnera844fc4c2006-04-10 22:45:52 +00009870 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Reid Spencer9d6565a2007-02-15 02:26:10 +00009871 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +00009872 LHS = SVI.getOperand(0);
9873 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +00009874 MadeChange = true;
9875 }
9876
Chris Lattner7b2e27922006-05-26 00:29:06 +00009877 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +00009878 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +00009879
Chris Lattner863bcff2006-05-25 23:48:38 +00009880 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
9881 if (Mask[i] >= e*2) continue; // Ignore undef values.
9882 // Is this an identity shuffle of the LHS value?
9883 isLHSID &= (Mask[i] == i);
9884
9885 // Is this an identity shuffle of the RHS value?
9886 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +00009887 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +00009888
Chris Lattner863bcff2006-05-25 23:48:38 +00009889 // Eliminate identity shuffles.
9890 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
9891 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +00009892
Chris Lattner7b2e27922006-05-26 00:29:06 +00009893 // If the LHS is a shufflevector itself, see if we can combine it with this
9894 // one without producing an unusual shuffle. Here we are really conservative:
9895 // we are absolutely afraid of producing a shuffle mask not in the input
9896 // program, because the code gen may not be smart enough to turn a merged
9897 // shuffle into two specific shuffles: it may produce worse code. As such,
9898 // we only merge two shuffles if the result is one of the two input shuffle
9899 // masks. In this case, merging the shuffles just removes one instruction,
9900 // which we know is safe. This is good for things like turning:
9901 // (splat(splat)) -> splat.
9902 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
9903 if (isa<UndefValue>(RHS)) {
9904 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
9905
9906 std::vector<unsigned> NewMask;
9907 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
9908 if (Mask[i] >= 2*e)
9909 NewMask.push_back(2*e);
9910 else
9911 NewMask.push_back(LHSMask[Mask[i]]);
9912
9913 // If the result mask is equal to the src shuffle or this shuffle mask, do
9914 // the replacement.
9915 if (NewMask == LHSMask || NewMask == Mask) {
9916 std::vector<Constant*> Elts;
9917 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
9918 if (NewMask[i] >= e*2) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00009919 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +00009920 } else {
Reid Spencerc5b206b2006-12-31 05:48:39 +00009921 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +00009922 }
9923 }
9924 return new ShuffleVectorInst(LHSSVI->getOperand(0),
9925 LHSSVI->getOperand(1),
Reid Spencer9d6565a2007-02-15 02:26:10 +00009926 ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +00009927 }
9928 }
9929 }
Chris Lattnerc5eff442007-01-30 22:32:46 +00009930
Chris Lattnera844fc4c2006-04-10 22:45:52 +00009931 return MadeChange ? &SVI : 0;
9932}
9933
9934
Robert Bocchino1d7456d2006-01-13 22:48:06 +00009935
Chris Lattnerea1c4542004-12-08 23:43:58 +00009936
9937/// TryToSinkInstruction - Try to move the specified instruction from its
9938/// current block into the beginning of DestBlock, which can only happen if it's
9939/// safe to move the instruction past all of the instructions between it and the
9940/// end of its block.
9941static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
9942 assert(I->hasOneUse() && "Invariants didn't hold!");
9943
Chris Lattner108e9022005-10-27 17:13:11 +00009944 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
9945 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
Misha Brukmanfd939082005-04-21 23:48:37 +00009946
Chris Lattnerea1c4542004-12-08 23:43:58 +00009947 // Do not sink alloca instructions out of the entry block.
9948 if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
9949 return false;
9950
Chris Lattner96a52a62004-12-09 07:14:34 +00009951 // We can only sink load instructions if there is nothing between the load and
9952 // the end of block that could change the value.
9953 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattner96a52a62004-12-09 07:14:34 +00009954 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
9955 Scan != E; ++Scan)
9956 if (Scan->mayWriteToMemory())
9957 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +00009958 }
Chris Lattnerea1c4542004-12-08 23:43:58 +00009959
9960 BasicBlock::iterator InsertPos = DestBlock->begin();
9961 while (isa<PHINode>(InsertPos)) ++InsertPos;
9962
Chris Lattner4bc5f802005-08-08 19:11:57 +00009963 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +00009964 ++NumSunkInst;
9965 return true;
9966}
9967
Chris Lattnerf4f5a772006-05-10 19:00:36 +00009968
9969/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
9970/// all reachable code to the worklist.
9971///
9972/// This has a couple of tricks to make the code faster and more powerful. In
9973/// particular, we constant fold and DCE instructions as we go, to avoid adding
9974/// them to the worklist (this significantly speeds up instcombine on code where
9975/// many instructions are dead or constant). Additionally, if we find a branch
9976/// whose condition is a known constant, we only visit the reachable successors.
9977///
9978static void AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +00009979 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +00009980 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +00009981 const TargetData *TD) {
Chris Lattnerf4f5a772006-05-10 19:00:36 +00009982 // We have now visited this block! If we've already been here, bail out.
Chris Lattner1f87a582007-02-15 19:41:52 +00009983 if (!Visited.insert(BB)) return;
Chris Lattnerf4f5a772006-05-10 19:00:36 +00009984
9985 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
9986 Instruction *Inst = BBI++;
9987
9988 // DCE instruction if trivially dead.
9989 if (isInstructionTriviallyDead(Inst)) {
9990 ++NumDeadInst;
Bill Wendlingb7427032006-11-26 09:46:52 +00009991 DOUT << "IC: DCE: " << *Inst;
Chris Lattnerf4f5a772006-05-10 19:00:36 +00009992 Inst->eraseFromParent();
9993 continue;
9994 }
9995
9996 // ConstantProp instruction if trivially constant.
Chris Lattner0a19ffa2007-01-30 23:16:15 +00009997 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
Bill Wendlingb7427032006-11-26 09:46:52 +00009998 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
Chris Lattnerf4f5a772006-05-10 19:00:36 +00009999 Inst->replaceAllUsesWith(C);
10000 ++NumConstProp;
10001 Inst->eraseFromParent();
10002 continue;
10003 }
10004
Chris Lattnerdbab3862007-03-02 21:28:56 +000010005 IC.AddToWorkList(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000010006 }
10007
10008 // Recursively visit successors. If this is a branch or switch on a constant,
10009 // only visit the reachable successor.
10010 TerminatorInst *TI = BB->getTerminator();
10011 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
Reid Spencera54b7cb2007-01-12 07:05:14 +000010012 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
Reid Spencer579dca12007-01-12 04:24:46 +000010013 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Chris Lattnerdbab3862007-03-02 21:28:56 +000010014 AddReachableCodeToWorklist(BI->getSuccessor(!CondVal), Visited, IC, TD);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000010015 return;
10016 }
10017 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
10018 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
10019 // See if this is an explicit destination.
10020 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
10021 if (SI->getCaseValue(i) == Cond) {
Chris Lattnerdbab3862007-03-02 21:28:56 +000010022 AddReachableCodeToWorklist(SI->getSuccessor(i), Visited, IC, TD);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000010023 return;
10024 }
10025
10026 // Otherwise it is the default destination.
Chris Lattnerdbab3862007-03-02 21:28:56 +000010027 AddReachableCodeToWorklist(SI->getSuccessor(0), Visited, IC, TD);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000010028 return;
10029 }
10030 }
10031
10032 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
Chris Lattnerdbab3862007-03-02 21:28:56 +000010033 AddReachableCodeToWorklist(TI->getSuccessor(i), Visited, IC, TD);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000010034}
10035
Chris Lattnerec9c3582007-03-03 02:04:50 +000010036bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000010037 bool Changed = false;
Chris Lattnerbc61e662003-11-02 05:57:39 +000010038 TD = &getAnalysis<TargetData>();
Chris Lattnerec9c3582007-03-03 02:04:50 +000010039
10040 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
10041 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +000010042
Chris Lattnerb3d59702005-07-07 20:40:38 +000010043 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +000010044 // Do a depth-first traversal of the function, populate the worklist with
10045 // the reachable instructions. Ignore blocks that are not reachable. Keep
10046 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +000010047 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerdbab3862007-03-02 21:28:56 +000010048 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +000010049
Chris Lattnerb3d59702005-07-07 20:40:38 +000010050 // Do a quick scan over the function. If we find any blocks that are
10051 // unreachable, remove any instructions inside of them. This prevents
10052 // the instcombine code from having to deal with some bad special cases.
10053 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
10054 if (!Visited.count(BB)) {
10055 Instruction *Term = BB->getTerminator();
10056 while (Term != BB->begin()) { // Remove instrs bottom-up
10057 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +000010058
Bill Wendlingb7427032006-11-26 09:46:52 +000010059 DOUT << "IC: DCE: " << *I;
Chris Lattnerb3d59702005-07-07 20:40:38 +000010060 ++NumDeadInst;
10061
10062 if (!I->use_empty())
10063 I->replaceAllUsesWith(UndefValue::get(I->getType()));
10064 I->eraseFromParent();
10065 }
10066 }
10067 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000010068
Chris Lattnerdbab3862007-03-02 21:28:56 +000010069 while (!Worklist.empty()) {
10070 Instruction *I = RemoveOneFromWorkList();
10071 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +000010072
Chris Lattner8c8c66a2006-05-11 17:11:52 +000010073 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +000010074 if (isInstructionTriviallyDead(I)) {
Chris Lattner8c8c66a2006-05-11 17:11:52 +000010075 // Add operands to the worklist.
Chris Lattner4bb7c022003-10-06 17:11:01 +000010076 if (I->getNumOperands() < 4)
Chris Lattner7bcc0e72004-02-28 05:22:00 +000010077 AddUsesToWorkList(*I);
Chris Lattner62b14df2002-09-02 04:59:56 +000010078 ++NumDeadInst;
Chris Lattner4bb7c022003-10-06 17:11:01 +000010079
Bill Wendlingb7427032006-11-26 09:46:52 +000010080 DOUT << "IC: DCE: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000010081
10082 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000010083 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000010084 continue;
10085 }
Chris Lattner62b14df2002-09-02 04:59:56 +000010086
Chris Lattner8c8c66a2006-05-11 17:11:52 +000010087 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattner0a19ffa2007-01-30 23:16:15 +000010088 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Bill Wendlingb7427032006-11-26 09:46:52 +000010089 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000010090
Chris Lattner8c8c66a2006-05-11 17:11:52 +000010091 // Add operands to the worklist.
Chris Lattner7bcc0e72004-02-28 05:22:00 +000010092 AddUsesToWorkList(*I);
Chris Lattnerc736d562002-12-05 22:41:53 +000010093 ReplaceInstUsesWith(*I, C);
10094
Chris Lattner62b14df2002-09-02 04:59:56 +000010095 ++NumConstProp;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000010096 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000010097 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000010098 continue;
Chris Lattner62b14df2002-09-02 04:59:56 +000010099 }
Chris Lattner4bb7c022003-10-06 17:11:01 +000010100
Chris Lattnerea1c4542004-12-08 23:43:58 +000010101 // See if we can trivially sink this instruction to a successor basic block.
10102 if (I->hasOneUse()) {
10103 BasicBlock *BB = I->getParent();
10104 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
10105 if (UserParent != BB) {
10106 bool UserIsSuccessor = false;
10107 // See if the user is one of our successors.
10108 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
10109 if (*SI == UserParent) {
10110 UserIsSuccessor = true;
10111 break;
10112 }
10113
10114 // If the user is one of our immediate successors, and if that successor
10115 // only has us as a predecessors (we'd have to split the critical edge
10116 // otherwise), we can keep going.
10117 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
10118 next(pred_begin(UserParent)) == pred_end(UserParent))
10119 // Okay, the CFG is simple enough, try to sink this instruction.
10120 Changed |= TryToSinkInstruction(I, UserParent);
10121 }
10122 }
10123
Chris Lattner8a2a3112001-12-14 16:52:21 +000010124 // Now that we have an instruction, try combining it to simplify it...
Chris Lattner90ac28c2002-08-02 19:29:35 +000010125 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +000010126 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000010127 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000010128 if (Result != I) {
Bill Wendlingb7427032006-11-26 09:46:52 +000010129 DOUT << "IC: Old = " << *I
10130 << " New = " << *Result;
Chris Lattner0cea42a2004-03-13 23:54:27 +000010131
Chris Lattnerf523d062004-06-09 05:08:07 +000010132 // Everything uses the new instruction now.
10133 I->replaceAllUsesWith(Result);
10134
10135 // Push the new instruction and any users onto the worklist.
Chris Lattnerdbab3862007-03-02 21:28:56 +000010136 AddToWorkList(Result);
Chris Lattnerf523d062004-06-09 05:08:07 +000010137 AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000010138
Chris Lattner6934a042007-02-11 01:23:03 +000010139 // Move the name to the new instruction first.
10140 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000010141
10142 // Insert the new instruction into the basic block...
10143 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +000010144 BasicBlock::iterator InsertPos = I;
10145
10146 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
10147 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
10148 ++InsertPos;
10149
10150 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000010151
Chris Lattner00d51312004-05-01 23:27:23 +000010152 // Make sure that we reprocess all operands now that we reduced their
10153 // use counts.
Chris Lattnerdbab3862007-03-02 21:28:56 +000010154 AddUsesToWorkList(*I);
Chris Lattner216d4d82004-05-01 23:19:52 +000010155
Chris Lattnerf523d062004-06-09 05:08:07 +000010156 // Instructions can end up on the worklist more than once. Make sure
10157 // we do not process an instruction that has been deleted.
Chris Lattnerdbab3862007-03-02 21:28:56 +000010158 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000010159
10160 // Erase the old instruction.
10161 InstParent->getInstList().erase(I);
Chris Lattner7e708292002-06-25 16:13:24 +000010162 } else {
Bill Wendlingb7427032006-11-26 09:46:52 +000010163 DOUT << "IC: MOD = " << *I;
Chris Lattner0cea42a2004-03-13 23:54:27 +000010164
Chris Lattner90ac28c2002-08-02 19:29:35 +000010165 // If the instruction was modified, it's possible that it is now dead.
10166 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +000010167 if (isInstructionTriviallyDead(I)) {
10168 // Make sure we process all operands now that we are reducing their
10169 // use counts.
Chris Lattnerec9c3582007-03-03 02:04:50 +000010170 AddUsesToWorkList(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000010171
Chris Lattner00d51312004-05-01 23:27:23 +000010172 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010173 // occurrences of this instruction.
Chris Lattnerdbab3862007-03-02 21:28:56 +000010174 RemoveFromWorkList(I);
Chris Lattner2f503e62005-01-31 05:36:43 +000010175 I->eraseFromParent();
Chris Lattnerf523d062004-06-09 05:08:07 +000010176 } else {
Chris Lattnerec9c3582007-03-03 02:04:50 +000010177 AddToWorkList(I);
10178 AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +000010179 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000010180 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +000010181 Changed = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +000010182 }
10183 }
10184
Chris Lattnerec9c3582007-03-03 02:04:50 +000010185 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattnerdd841ae2002-04-18 17:39:14 +000010186 return Changed;
Chris Lattnerbd0ef772002-02-26 21:46:54 +000010187}
10188
Chris Lattnerec9c3582007-03-03 02:04:50 +000010189
10190bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +000010191 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
10192
Chris Lattnerec9c3582007-03-03 02:04:50 +000010193 bool EverMadeChange = false;
10194
10195 // Iterate while there is work to do.
10196 unsigned Iteration = 0;
10197 while (DoOneIteration(F, Iteration++))
10198 EverMadeChange = true;
10199 return EverMadeChange;
10200}
10201
Brian Gaeke96d4bf72004-07-27 17:43:21 +000010202FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000010203 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +000010204}
Brian Gaeked0fde302003-11-11 22:41:34 +000010205