blob: 82c67d03d93a83018259a651cd4bc8f1196c6268 [file] [log] [blame]
Chris Lattnere6794492002-08-12 21:17:25 +00001//===- InstructionCombining.cpp - Combine multiple instructions -----------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattnerca081252001-12-14 16:52:21 +00009//
10// InstructionCombining - Combine instructions to form fewer, simple
Chris Lattner99f48c62002-09-02 04:59:56 +000011// instructions. This pass does not modify the CFG This pass is where algebraic
12// simplification happens.
Chris Lattnerca081252001-12-14 16:52:21 +000013//
14// This pass combines things like:
Chris Lattner07418422007-03-18 22:51:34 +000015// %Y = add i32 %X, 1
16// %Z = add i32 %Y, 1
Chris Lattnerca081252001-12-14 16:52:21 +000017// into:
Chris Lattner07418422007-03-18 22:51:34 +000018// %Z = add i32 %X, 2
Chris Lattnerca081252001-12-14 16:52:21 +000019//
20// This is a simple worklist driven algorithm.
21//
Chris Lattner216c7b82003-09-10 05:29:43 +000022// This pass guarantees that the following canonicalizations are performed on
Chris Lattnerbfb1d032003-07-23 21:41:57 +000023// the program:
24// 1. If a binary operator has a constant operand, it is moved to the RHS
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +000025// 2. Bitwise operators with constant operands are always grouped so that
26// shifts are performed first, then or's, then and's, then xor's.
Reid Spencer266e42b2006-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 Lattnerede3fe02003-08-13 04:18:28 +000029// 5. add X, X is represented as (X*2) => (X << 1)
30// 6. Multiplies with a power-of-two constant argument are transformed into
31// shifts.
Chris Lattner7515cab2004-11-14 19:13:23 +000032// ... etc.
Chris Lattnerbfb1d032003-07-23 21:41:57 +000033//
Chris Lattnerca081252001-12-14 16:52:21 +000034//===----------------------------------------------------------------------===//
35
Chris Lattner7d2a5392004-03-13 23:54:27 +000036#define DEBUG_TYPE "instcombine"
Chris Lattnerb4cfa7f2002-05-07 20:03:00 +000037#include "llvm/Transforms/Scalar.h"
Chris Lattner00648e12004-10-12 04:52:52 +000038#include "llvm/IntrinsicInst.h"
Chris Lattner04805fa2002-02-26 21:46:54 +000039#include "llvm/Pass.h"
Chris Lattner1085bdf2002-11-04 16:18:53 +000040#include "llvm/DerivedTypes.h"
Chris Lattner0f1d8a32003-06-26 05:06:25 +000041#include "llvm/GlobalVariable.h"
Chris Lattner024f4ab2007-01-30 23:46:24 +000042#include "llvm/Analysis/ConstantFolding.h"
Chris Lattnerf4ad1652003-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 Lattner69193f92004-04-05 01:30:19 +000046#include "llvm/Support/CallSite.h"
Nick Lewycky3b592142008-02-03 16:33:09 +000047#include "llvm/Support/ConstantRange.h"
Chris Lattner39c98bb2004-12-08 23:43:58 +000048#include "llvm/Support/Debug.h"
Chris Lattner69193f92004-04-05 01:30:19 +000049#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner260ab202002-04-18 17:39:14 +000050#include "llvm/Support/InstVisitor.h"
Chris Lattner22d00a82005-08-02 19:16:58 +000051#include "llvm/Support/MathExtras.h"
Chris Lattnerd4252a72004-07-30 07:50:03 +000052#include "llvm/Support/PatternMatch.h"
Chris Lattner3d27be12006-08-27 12:54:02 +000053#include "llvm/Support/Compiler.h"
Chris Lattnerb15e2b12007-03-02 21:28:56 +000054#include "llvm/ADT/DenseMap.h"
Chris Lattnerf96f4a82007-01-31 04:40:53 +000055#include "llvm/ADT/SmallVector.h"
Chris Lattner7907e5f2007-02-15 19:41:52 +000056#include "llvm/ADT/SmallPtrSet.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000057#include "llvm/ADT/Statistic.h"
Chris Lattner39c98bb2004-12-08 23:43:58 +000058#include "llvm/ADT/STLExtras.h"
Chris Lattner053c0932002-05-14 15:24:07 +000059#include <algorithm>
Torok Edwinab207842008-04-20 08:33:11 +000060#include <climits>
Reid Spencer755d0e72007-03-26 17:44:01 +000061#include <sstream>
Chris Lattner8427bff2003-12-07 01:24:23 +000062using namespace llvm;
Chris Lattnerd4252a72004-07-30 07:50:03 +000063using namespace llvm::PatternMatch;
Brian Gaeke960707c2003-11-11 22:41:34 +000064
Chris Lattner79a42ac2006-12-19 21:40:18 +000065STATISTIC(NumCombined , "Number of insts combined");
66STATISTIC(NumConstProp, "Number of constant folds");
67STATISTIC(NumDeadInst , "Number of dead inst eliminated");
68STATISTIC(NumDeadStore, "Number of dead stores eliminated");
69STATISTIC(NumSunkInst , "Number of instructions sunk");
Chris Lattnerbf3a0992002-10-01 22:38:41 +000070
Chris Lattner79a42ac2006-12-19 21:40:18 +000071namespace {
Chris Lattner4a4c7fe2006-06-28 22:08:15 +000072 class VISIBILITY_HIDDEN InstCombiner
73 : public FunctionPass,
74 public InstVisitor<InstCombiner, Instruction*> {
Chris Lattner260ab202002-04-18 17:39:14 +000075 // Worklist of all of the instructions that need to be simplified.
Chris Lattnerb15e2b12007-03-02 21:28:56 +000076 std::vector<Instruction*> Worklist;
77 DenseMap<Instruction*, unsigned> WorklistMap;
Chris Lattnerf4ad1652003-11-02 05:57:39 +000078 TargetData *TD;
Chris Lattner8258b442007-03-04 04:27:24 +000079 bool MustPreserveLCSSA;
Chris Lattnerb15e2b12007-03-02 21:28:56 +000080 public:
Nick Lewyckye7da2d62007-05-06 13:37:16 +000081 static char ID; // Pass identification, replacement for typeid
Devang Patel09f162c2007-05-01 21:15:47 +000082 InstCombiner() : FunctionPass((intptr_t)&ID) {}
83
Chris Lattnerb15e2b12007-03-02 21:28:56 +000084 /// AddToWorkList - Add the specified instruction to the worklist if it
85 /// isn't already in it.
86 void AddToWorkList(Instruction *I) {
87 if (WorklistMap.insert(std::make_pair(I, Worklist.size())))
88 Worklist.push_back(I);
89 }
90
91 // RemoveFromWorkList - remove I from the worklist if it exists.
92 void RemoveFromWorkList(Instruction *I) {
93 DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
94 if (It == WorklistMap.end()) return; // Not in worklist.
95
96 // Don't bother moving everything down, just null out the slot.
97 Worklist[It->second] = 0;
98
99 WorklistMap.erase(It);
100 }
101
102 Instruction *RemoveOneFromWorkList() {
103 Instruction *I = Worklist.back();
104 Worklist.pop_back();
105 WorklistMap.erase(I);
106 return I;
107 }
Chris Lattner260ab202002-04-18 17:39:14 +0000108
Chris Lattnerb15e2b12007-03-02 21:28:56 +0000109
Chris Lattner51ea1272004-02-28 05:22:00 +0000110 /// AddUsersToWorkList - When an instruction is simplified, add all users of
111 /// the instruction to the work lists because they might get more simplified
112 /// now.
113 ///
Chris Lattner2590e512006-02-07 06:56:34 +0000114 void AddUsersToWorkList(Value &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +0000115 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattner260ab202002-04-18 17:39:14 +0000116 UI != UE; ++UI)
Chris Lattnerb15e2b12007-03-02 21:28:56 +0000117 AddToWorkList(cast<Instruction>(*UI));
Chris Lattner260ab202002-04-18 17:39:14 +0000118 }
119
Chris Lattner51ea1272004-02-28 05:22:00 +0000120 /// AddUsesToWorkList - When an instruction is simplified, add operands to
121 /// the work lists because they might get more simplified now.
122 ///
123 void AddUsesToWorkList(Instruction &I) {
124 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
125 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
Chris Lattnerb15e2b12007-03-02 21:28:56 +0000126 AddToWorkList(Op);
Chris Lattner51ea1272004-02-28 05:22:00 +0000127 }
Chris Lattner2deeaea2006-10-05 06:55:50 +0000128
129 /// AddSoonDeadInstToWorklist - The specified instruction is about to become
130 /// dead. Add all of its operands to the worklist, turning them into
131 /// undef's to reduce the number of uses of those instructions.
132 ///
133 /// Return the specified operand before it is turned into an undef.
134 ///
135 Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
136 Value *R = I.getOperand(op);
137
138 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
139 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i))) {
Chris Lattnerb15e2b12007-03-02 21:28:56 +0000140 AddToWorkList(Op);
Chris Lattner2deeaea2006-10-05 06:55:50 +0000141 // Set the operand to undef to drop the use.
142 I.setOperand(i, UndefValue::get(Op->getType()));
143 }
144
145 return R;
146 }
Chris Lattner51ea1272004-02-28 05:22:00 +0000147
Chris Lattner260ab202002-04-18 17:39:14 +0000148 public:
Chris Lattner113f4f42002-06-25 16:13:24 +0000149 virtual bool runOnFunction(Function &F);
Chris Lattner960a5432007-03-03 02:04:50 +0000150
151 bool DoOneIteration(Function &F, unsigned ItNum);
Chris Lattner260ab202002-04-18 17:39:14 +0000152
Chris Lattnerf12cc842002-04-28 21:27:06 +0000153 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerf4ad1652003-11-02 05:57:39 +0000154 AU.addRequired<TargetData>();
Owen Andersona6968f82006-07-10 19:03:49 +0000155 AU.addPreservedID(LCSSAID);
Chris Lattner820d9712002-10-21 20:00:28 +0000156 AU.setPreservesCFG();
Chris Lattnerf12cc842002-04-28 21:27:06 +0000157 }
158
Chris Lattner69193f92004-04-05 01:30:19 +0000159 TargetData &getTargetData() const { return *TD; }
160
Chris Lattner260ab202002-04-18 17:39:14 +0000161 // Visitation implementation - Implement instruction combining for different
162 // instruction types. The semantics are as follows:
163 // Return Value:
164 // null - No change was made
Chris Lattnere6794492002-08-12 21:17:25 +0000165 // I - Change was made, I is still valid, I may be dead though
Chris Lattner260ab202002-04-18 17:39:14 +0000166 // otherwise - Change was made, replace I with returned instruction
Misha Brukmanb1c93172005-04-21 23:48:37 +0000167 //
Chris Lattner113f4f42002-06-25 16:13:24 +0000168 Instruction *visitAdd(BinaryOperator &I);
169 Instruction *visitSub(BinaryOperator &I);
170 Instruction *visitMul(BinaryOperator &I);
Reid Spencer7eb55b32006-11-02 01:53:59 +0000171 Instruction *visitURem(BinaryOperator &I);
172 Instruction *visitSRem(BinaryOperator &I);
173 Instruction *visitFRem(BinaryOperator &I);
174 Instruction *commonRemTransforms(BinaryOperator &I);
175 Instruction *commonIRemTransforms(BinaryOperator &I);
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000176 Instruction *commonDivTransforms(BinaryOperator &I);
177 Instruction *commonIDivTransforms(BinaryOperator &I);
178 Instruction *visitUDiv(BinaryOperator &I);
179 Instruction *visitSDiv(BinaryOperator &I);
180 Instruction *visitFDiv(BinaryOperator &I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000181 Instruction *visitAnd(BinaryOperator &I);
182 Instruction *visitOr (BinaryOperator &I);
183 Instruction *visitXor(BinaryOperator &I);
Reid Spencer2341c222007-02-02 02:16:23 +0000184 Instruction *visitShl(BinaryOperator &I);
185 Instruction *visitAShr(BinaryOperator &I);
186 Instruction *visitLShr(BinaryOperator &I);
187 Instruction *commonShiftTransforms(BinaryOperator &I);
Reid Spencer266e42b2006-12-23 06:05:41 +0000188 Instruction *visitFCmpInst(FCmpInst &I);
189 Instruction *visitICmpInst(ICmpInst &I);
190 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
Chris Lattnera74deaf2007-04-03 17:43:25 +0000191 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
192 Instruction *LHS,
193 ConstantInt *RHS);
Chris Lattner3bbec592007-06-20 23:46:26 +0000194 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
195 ConstantInt *DivRHS);
Chris Lattnerd1f46d32005-04-24 06:59:08 +0000196
Reid Spencer266e42b2006-12-23 06:05:41 +0000197 Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
198 ICmpInst::Predicate Cond, Instruction &I);
Reid Spencere0fc4df2006-10-20 07:07:24 +0000199 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer2341c222007-02-02 02:16:23 +0000200 BinaryOperator &I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000201 Instruction *commonCastTransforms(CastInst &CI);
202 Instruction *commonIntCastTransforms(CastInst &CI);
Chris Lattner1db224d2007-04-27 17:44:50 +0000203 Instruction *commonPointerCastTransforms(CastInst &CI);
Chris Lattner74ff60f2007-04-11 06:57:46 +0000204 Instruction *visitTrunc(TruncInst &CI);
205 Instruction *visitZExt(ZExtInst &CI);
206 Instruction *visitSExt(SExtInst &CI);
Chris Lattnerfa1e7ee2008-01-27 05:29:54 +0000207 Instruction *visitFPTrunc(FPTruncInst &CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000208 Instruction *visitFPExt(CastInst &CI);
209 Instruction *visitFPToUI(CastInst &CI);
210 Instruction *visitFPToSI(CastInst &CI);
211 Instruction *visitUIToFP(CastInst &CI);
212 Instruction *visitSIToFP(CastInst &CI);
213 Instruction *visitPtrToInt(CastInst &CI);
Chris Lattner2940c5c2008-01-08 07:23:51 +0000214 Instruction *visitIntToPtr(IntToPtrInst &CI);
Chris Lattner1db224d2007-04-27 17:44:50 +0000215 Instruction *visitBitCast(BitCastInst &CI);
Chris Lattner411336f2005-01-19 21:50:18 +0000216 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
217 Instruction *FI);
Chris Lattnerb909e8b2004-03-12 05:52:32 +0000218 Instruction *visitSelectInst(SelectInst &CI);
Chris Lattner970c33a2003-06-19 17:00:31 +0000219 Instruction *visitCallInst(CallInst &CI);
220 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner113f4f42002-06-25 16:13:24 +0000221 Instruction *visitPHINode(PHINode &PN);
222 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner1085bdf2002-11-04 16:18:53 +0000223 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner8427bff2003-12-07 01:24:23 +0000224 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner0f1d8a32003-06-26 05:06:25 +0000225 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner31f486c2005-01-31 05:36:43 +0000226 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattner9eef8a72003-06-04 04:46:00 +0000227 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner4c9c20a2004-07-03 00:26:11 +0000228 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattner39fac442006-04-15 01:39:45 +0000229 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchinoa8352962006-01-13 22:48:06 +0000230 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnerfbb77a42006-04-10 22:45:52 +0000231 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Chris Lattner260ab202002-04-18 17:39:14 +0000232
233 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner113f4f42002-06-25 16:13:24 +0000234 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000235
Chris Lattner970c33a2003-06-19 17:00:31 +0000236 private:
Chris Lattneraec3d942003-10-07 22:32:43 +0000237 Instruction *visitCallSite(CallSite CS);
Chris Lattner970c33a2003-06-19 17:00:31 +0000238 bool transformConstExprCastCall(CallSite CS);
Duncan Sands6d5da712007-09-17 10:26:40 +0000239 Instruction *transformCallThroughTrampoline(CallSite CS);
Evan Chengc3cf9f82008-03-24 00:21:34 +0000240 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
241 bool DoXform = true);
Chris Lattner970c33a2003-06-19 17:00:31 +0000242
Chris Lattner69193f92004-04-05 01:30:19 +0000243 public:
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000244 // InsertNewInstBefore - insert an instruction New before instruction Old
245 // in the program. Add the new instruction to the worklist.
246 //
Chris Lattner623826c2004-09-28 21:48:02 +0000247 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattner65217ff2002-08-23 18:32:43 +0000248 assert(New && New->getParent() == 0 &&
249 "New instruction already inserted into a basic block!");
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000250 BasicBlock *BB = Old.getParent();
251 BB->getInstList().insert(&Old, New); // Insert inst
Chris Lattnerb15e2b12007-03-02 21:28:56 +0000252 AddToWorkList(New);
Chris Lattnere79e8542004-02-23 06:38:22 +0000253 return New;
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000254 }
255
Chris Lattner7e794272004-09-24 15:21:34 +0000256 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
257 /// This also adds the cast to the worklist. Finally, this returns the
258 /// cast.
Reid Spencer13bc5d72006-12-12 09:18:51 +0000259 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
260 Instruction &Pos) {
Chris Lattner7e794272004-09-24 15:21:34 +0000261 if (V->getType() == Ty) return V;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000262
Chris Lattnere79d2492006-04-06 19:19:17 +0000263 if (Constant *CV = dyn_cast<Constant>(V))
Reid Spencer13bc5d72006-12-12 09:18:51 +0000264 return ConstantExpr::getCast(opc, CV, Ty);
Chris Lattnere79d2492006-04-06 19:19:17 +0000265
Reid Spencer13bc5d72006-12-12 09:18:51 +0000266 Instruction *C = CastInst::create(opc, V, Ty, V->getName(), &Pos);
Chris Lattnerb15e2b12007-03-02 21:28:56 +0000267 AddToWorkList(C);
Chris Lattner7e794272004-09-24 15:21:34 +0000268 return C;
269 }
Chris Lattner5a866122008-01-13 22:23:22 +0000270
271 Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
272 return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
273 }
274
Chris Lattner7e794272004-09-24 15:21:34 +0000275
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000276 // ReplaceInstUsesWith - This method is to be used when an instruction is
277 // found to be dead, replacable with another preexisting expression. Here
278 // we add all uses of I to the worklist, replace all uses of I with the new
279 // value, then return I, so that the inst combiner will know that I was
280 // modified.
281 //
282 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner51ea1272004-02-28 05:22:00 +0000283 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner8953b902004-04-05 02:10:19 +0000284 if (&I != V) {
285 I.replaceAllUsesWith(V);
286 return &I;
287 } else {
288 // If we are replacing the instruction with itself, this must be in a
289 // segment of unreachable code, so just clobber the instruction.
Chris Lattner8ba9ec92004-10-18 02:59:09 +0000290 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner8953b902004-04-05 02:10:19 +0000291 return &I;
292 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000293 }
Chris Lattner51ea1272004-02-28 05:22:00 +0000294
Chris Lattner2590e512006-02-07 06:56:34 +0000295 // UpdateValueUsesWith - This method is to be used when an value is
296 // found to be replacable with another preexisting expression or was
297 // updated. Here we add all uses of I to the worklist, replace all uses of
298 // I with the new value (unless the instruction was just updated), then
299 // return true, so that the inst combiner will know that I was modified.
300 //
301 bool UpdateValueUsesWith(Value *Old, Value *New) {
302 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
303 if (Old != New)
304 Old->replaceAllUsesWith(New);
305 if (Instruction *I = dyn_cast<Instruction>(Old))
Chris Lattnerb15e2b12007-03-02 21:28:56 +0000306 AddToWorkList(I);
Chris Lattner5b2edb12006-02-12 08:02:11 +0000307 if (Instruction *I = dyn_cast<Instruction>(New))
Chris Lattnerb15e2b12007-03-02 21:28:56 +0000308 AddToWorkList(I);
Chris Lattner2590e512006-02-07 06:56:34 +0000309 return true;
310 }
311
Chris Lattner51ea1272004-02-28 05:22:00 +0000312 // EraseInstFromFunction - When dealing with an instruction that has side
313 // effects or produces a void value, we can't rely on DCE to delete the
314 // instruction. Instead, visit methods should return the value returned by
315 // this function.
316 Instruction *EraseInstFromFunction(Instruction &I) {
317 assert(I.use_empty() && "Cannot erase instruction that is used!");
318 AddUsesToWorkList(I);
Chris Lattnerb15e2b12007-03-02 21:28:56 +0000319 RemoveFromWorkList(&I);
Chris Lattner95307542004-11-18 21:41:39 +0000320 I.eraseFromParent();
Chris Lattner51ea1272004-02-28 05:22:00 +0000321 return 0; // Don't do anything with FI
322 }
323
Chris Lattner3ac7c262003-08-13 20:16:26 +0000324 private:
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000325 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
326 /// InsertBefore instruction. This is specialized a bit to avoid inserting
327 /// casts that are known to not do anything...
328 ///
Reid Spencer13bc5d72006-12-12 09:18:51 +0000329 Value *InsertOperandCastBefore(Instruction::CastOps opcode,
330 Value *V, const Type *DestTy,
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000331 Instruction *InsertBefore);
332
Reid Spencer266e42b2006-12-23 06:05:41 +0000333 /// SimplifyCommutative - This performs a few simplifications for
334 /// commutative operators.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000335 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerba1cb382003-09-19 17:17:26 +0000336
Reid Spencer266e42b2006-12-23 06:05:41 +0000337 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
338 /// most-complex to least-complex order.
339 bool SimplifyCompare(CmpInst &I);
340
Reid Spencer959a21d2007-03-23 21:24:59 +0000341 /// SimplifyDemandedBits - Attempts to replace V with a simpler value based
342 /// on the demanded bits.
Reid Spencer1791f232007-03-12 17:25:59 +0000343 bool SimplifyDemandedBits(Value *V, APInt DemandedMask,
344 APInt& KnownZero, APInt& KnownOne,
345 unsigned Depth = 0);
346
Chris Lattner2deeaea2006-10-05 06:55:50 +0000347 Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
348 uint64_t &UndefElts, unsigned Depth = 0);
349
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000350 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
351 // PHI node as operand #0, see if we can fold the instruction into the PHI
352 // (which is only possible if all operands to the PHI are constants).
353 Instruction *FoldOpIntoPhi(Instruction &I);
354
Chris Lattner7515cab2004-11-14 19:13:23 +0000355 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
356 // operator and they all are only used by the PHI, PHI together their
357 // inputs, and do the operation once, to the result of the PHI.
358 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
Chris Lattnercadac0c2006-11-01 04:51:18 +0000359 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
360
361
Zhou Sheng75b871f2007-01-11 12:24:14 +0000362 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
363 ConstantInt *AndRHS, BinaryOperator &TheAnd);
Chris Lattneraf517572005-09-18 04:24:45 +0000364
Zhou Sheng75b871f2007-01-11 12:24:14 +0000365 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
Chris Lattneraf517572005-09-18 04:24:45 +0000366 bool isSub, Instruction &I);
Chris Lattner6862fbd2004-09-29 17:40:11 +0000367 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencer266e42b2006-12-23 06:05:41 +0000368 bool isSigned, bool Inside, Instruction &IB);
Chris Lattner1db224d2007-04-27 17:44:50 +0000369 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
Chris Lattnerc482a9e2006-06-15 19:07:26 +0000370 Instruction *MatchBSwap(BinaryOperator &I);
Chris Lattner14a251b2007-04-15 00:07:55 +0000371 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattner57974c82008-01-13 23:50:23 +0000372 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
373
Chris Lattnerc482a9e2006-06-15 19:07:26 +0000374
Reid Spencer74a528b2006-12-13 18:21:21 +0000375 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Dan Gohman99b7b3f2008-04-10 18:43:06 +0000376
377 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt& KnownZero,
378 APInt& KnownOne, unsigned Depth = 0);
379 bool MaskedValueIsZero(Value *V, const APInt& Mask, unsigned Depth = 0);
380 bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
381 unsigned CastOpc,
382 int &NumCastsRemoved);
383 unsigned GetOrEnforceKnownAlignment(Value *V,
384 unsigned PrefAlign = 0);
Chris Lattner260ab202002-04-18 17:39:14 +0000385 };
Chris Lattnerb28b6802002-07-23 18:06:35 +0000386
Devang Patel8c78a0b2007-05-03 01:11:54 +0000387 char InstCombiner::ID = 0;
Chris Lattnerc2d3d312006-08-27 22:42:52 +0000388 RegisterPass<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattner260ab202002-04-18 17:39:14 +0000389}
390
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000391// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattner81a7a232004-10-16 18:11:37 +0000392// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000393static unsigned getComplexity(Value *V) {
394 if (isa<Instruction>(V)) {
395 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattner81a7a232004-10-16 18:11:37 +0000396 return 3;
397 return 4;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000398 }
Chris Lattner81a7a232004-10-16 18:11:37 +0000399 if (isa<Argument>(V)) return 3;
400 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000401}
Chris Lattner260ab202002-04-18 17:39:14 +0000402
Chris Lattner7fb29e12003-03-11 00:12:48 +0000403// isOnlyUse - Return true if this instruction will be deleted if we stop using
404// it.
405static bool isOnlyUse(Value *V) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000406 return V->hasOneUse() || isa<Constant>(V);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000407}
408
Chris Lattnere79e8542004-02-23 06:38:22 +0000409// getPromotedType - Return the specified type promoted as it would be to pass
410// though a va_arg area...
411static const Type *getPromotedType(const Type *Ty) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000412 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
413 if (ITy->getBitWidth() < 32)
414 return Type::Int32Ty;
Chris Lattnerf79577d2007-05-23 01:17:04 +0000415 }
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000416 return Ty;
Chris Lattnere79e8542004-02-23 06:38:22 +0000417}
418
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000419/// getBitCastOperand - If the specified operand is a CastInst or a constant
420/// expression bitcast, return the operand value, otherwise return null.
421static Value *getBitCastOperand(Value *V) {
422 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
Chris Lattner567b81f2005-09-13 00:40:14 +0000423 return I->getOperand(0);
424 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000425 if (CE->getOpcode() == Instruction::BitCast)
Chris Lattner567b81f2005-09-13 00:40:14 +0000426 return CE->getOperand(0);
427 return 0;
428}
429
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000430/// This function is a wrapper around CastInst::isEliminableCastPair. It
431/// simply extracts arguments and returns what that function returns.
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000432static Instruction::CastOps
433isEliminableCastPair(
434 const CastInst *CI, ///< The first cast instruction
435 unsigned opcode, ///< The opcode of the second cast instruction
436 const Type *DstTy, ///< The target type for the second cast instruction
437 TargetData *TD ///< The target data for pointer size
438) {
439
440 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
441 const Type *MidTy = CI->getType(); // B from above
Chris Lattner1d441ad2006-05-06 09:00:16 +0000442
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000443 // Get the opcodes of the two Cast instructions
444 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
445 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner1d441ad2006-05-06 09:00:16 +0000446
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000447 return Instruction::CastOps(
448 CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
449 DstTy, TD->getIntPtrType()));
Chris Lattner1d441ad2006-05-06 09:00:16 +0000450}
451
452/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
453/// in any code being generated. It does not require codegen if V is simple
454/// enough or if the cast can be folded into other casts.
Reid Spencer266e42b2006-12-23 06:05:41 +0000455static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
456 const Type *Ty, TargetData *TD) {
Chris Lattner1d441ad2006-05-06 09:00:16 +0000457 if (V->getType() == Ty || isa<Constant>(V)) return false;
458
Chris Lattner99155be2006-05-25 23:24:33 +0000459 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner1d441ad2006-05-06 09:00:16 +0000460 if (const CastInst *CI = dyn_cast<CastInst>(V))
Reid Spencer266e42b2006-12-23 06:05:41 +0000461 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner1d441ad2006-05-06 09:00:16 +0000462 return false;
463 return true;
464}
465
466/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
467/// InsertBefore instruction. This is specialized a bit to avoid inserting
468/// casts that are known to not do anything...
469///
Reid Spencer13bc5d72006-12-12 09:18:51 +0000470Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
471 Value *V, const Type *DestTy,
Chris Lattner1d441ad2006-05-06 09:00:16 +0000472 Instruction *InsertBefore) {
473 if (V->getType() == DestTy) return V;
474 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencer13bc5d72006-12-12 09:18:51 +0000475 return ConstantExpr::getCast(opcode, C, DestTy);
Chris Lattner1d441ad2006-05-06 09:00:16 +0000476
Reid Spencer13bc5d72006-12-12 09:18:51 +0000477 return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
Chris Lattner1d441ad2006-05-06 09:00:16 +0000478}
479
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000480// SimplifyCommutative - This performs a few simplifications for commutative
481// operators:
Chris Lattner260ab202002-04-18 17:39:14 +0000482//
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000483// 1. Order operands such that they are listed from right (least complex) to
484// left (most complex). This puts constants before unary operators before
485// binary operators.
486//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000487// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
488// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000489//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000490bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000491 bool Changed = false;
492 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
493 Changed = !I.swapOperands();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000494
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000495 if (!I.isAssociative()) return Changed;
496 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattner7fb29e12003-03-11 00:12:48 +0000497 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
498 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
499 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner34428442003-05-27 16:40:51 +0000500 Constant *Folded = ConstantExpr::get(I.getOpcode(),
501 cast<Constant>(I.getOperand(1)),
502 cast<Constant>(Op->getOperand(1)));
Chris Lattner7fb29e12003-03-11 00:12:48 +0000503 I.setOperand(0, Op->getOperand(0));
504 I.setOperand(1, Folded);
505 return true;
506 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
507 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
508 isOnlyUse(Op) && isOnlyUse(Op1)) {
509 Constant *C1 = cast<Constant>(Op->getOperand(1));
510 Constant *C2 = cast<Constant>(Op1->getOperand(1));
511
512 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner34428442003-05-27 16:40:51 +0000513 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000514 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
515 Op1->getOperand(0),
516 Op1->getName(), &I);
Chris Lattnerb15e2b12007-03-02 21:28:56 +0000517 AddToWorkList(New);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000518 I.setOperand(0, New);
519 I.setOperand(1, Folded);
520 return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000521 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000522 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000523 return Changed;
Chris Lattner260ab202002-04-18 17:39:14 +0000524}
Chris Lattnerca081252001-12-14 16:52:21 +0000525
Reid Spencer266e42b2006-12-23 06:05:41 +0000526/// SimplifyCompare - For a CmpInst this function just orders the operands
527/// so that theyare listed from right (least complex) to left (most complex).
528/// This puts constants before unary operators before binary operators.
529bool InstCombiner::SimplifyCompare(CmpInst &I) {
530 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
531 return false;
532 I.swapOperands();
533 // Compare instructions are not associative so there's nothing else we can do.
534 return true;
535}
536
Chris Lattnerbb74e222003-03-10 23:06:50 +0000537// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
538// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattner9fa53de2002-05-06 16:49:18 +0000539//
Chris Lattnerbb74e222003-03-10 23:06:50 +0000540static inline Value *dyn_castNegVal(Value *V) {
541 if (BinaryOperator::isNeg(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000542 return BinaryOperator::getNegArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000543
Chris Lattner9ad0d552004-12-14 20:08:06 +0000544 // Constants can be considered to be negated values if they can be folded.
545 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
546 return ConstantExpr::getNeg(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000547 return 0;
Chris Lattner9fa53de2002-05-06 16:49:18 +0000548}
549
Chris Lattnerbb74e222003-03-10 23:06:50 +0000550static inline Value *dyn_castNotVal(Value *V) {
551 if (BinaryOperator::isNot(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000552 return BinaryOperator::getNotArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000553
554 // Constants can be considered to be not'ed values...
Zhou Sheng75b871f2007-01-11 12:24:14 +0000555 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Zhou Sheng9bc8ab12007-04-02 13:45:30 +0000556 return ConstantInt::get(~C->getValue());
Chris Lattnerbb74e222003-03-10 23:06:50 +0000557 return 0;
558}
559
Chris Lattner7fb29e12003-03-11 00:12:48 +0000560// dyn_castFoldableMul - If this value is a multiply that can be folded into
561// other computations (because it has a constant operand), return the
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000562// non-constant operand of the multiply, and set CST to point to the multiplier.
563// Otherwise, return null.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000564//
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000565static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattner03c49532007-01-15 02:27:26 +0000566 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000567 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattner7fb29e12003-03-11 00:12:48 +0000568 if (I->getOpcode() == Instruction::Mul)
Chris Lattner970136362004-11-15 05:54:07 +0000569 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattner7fb29e12003-03-11 00:12:48 +0000570 return I->getOperand(0);
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000571 if (I->getOpcode() == Instruction::Shl)
Chris Lattner970136362004-11-15 05:54:07 +0000572 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000573 // The multiplier is really 1 << CST.
Zhou Sheng4961cf12007-03-29 01:57:21 +0000574 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Zhou Shengb25806f2007-03-30 09:29:48 +0000575 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Zhou Sheng4961cf12007-03-29 01:57:21 +0000576 CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000577 return I->getOperand(0);
578 }
579 }
Chris Lattner7fb29e12003-03-11 00:12:48 +0000580 return 0;
Chris Lattner3082c5a2003-02-18 19:28:33 +0000581}
Chris Lattner31ae8632002-08-14 17:51:49 +0000582
Chris Lattner0798af32005-01-13 20:14:25 +0000583/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
584/// expression, return it.
585static User *dyn_castGetElementPtr(Value *V) {
586 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
587 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
588 if (CE->getOpcode() == Instruction::GetElementPtr)
589 return cast<User>(V);
590 return false;
591}
592
Dan Gohman99b7b3f2008-04-10 18:43:06 +0000593/// getOpcode - If this is an Instruction or a ConstantExpr, return the
594/// opcode value. Otherwise return UserOp1.
595static unsigned getOpcode(User *U) {
596 if (Instruction *I = dyn_cast<Instruction>(U))
597 return I->getOpcode();
598 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U))
599 return CE->getOpcode();
600 // Use UserOp1 to mean there's no opcode.
601 return Instruction::UserOp1;
602}
603
Reid Spencer80263aa2007-03-25 05:33:51 +0000604/// AddOne - Add one to a ConstantInt
Chris Lattner6862fbd2004-09-29 17:40:11 +0000605static ConstantInt *AddOne(ConstantInt *C) {
Reid Spencer624766f2007-03-25 19:55:33 +0000606 APInt Val(C->getValue());
607 return ConstantInt::get(++Val);
Chris Lattner623826c2004-09-28 21:48:02 +0000608}
Reid Spencer80263aa2007-03-25 05:33:51 +0000609/// SubOne - Subtract one from a ConstantInt
Chris Lattner6862fbd2004-09-29 17:40:11 +0000610static ConstantInt *SubOne(ConstantInt *C) {
Reid Spencer624766f2007-03-25 19:55:33 +0000611 APInt Val(C->getValue());
612 return ConstantInt::get(--Val);
Reid Spencer80263aa2007-03-25 05:33:51 +0000613}
614/// Add - Add two ConstantInts together
615static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
616 return ConstantInt::get(C1->getValue() + C2->getValue());
617}
618/// And - Bitwise AND two ConstantInts together
619static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
620 return ConstantInt::get(C1->getValue() & C2->getValue());
621}
622/// Subtract - Subtract one ConstantInt from another
623static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
624 return ConstantInt::get(C1->getValue() - C2->getValue());
625}
626/// Multiply - Multiply two ConstantInts together
627static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
628 return ConstantInt::get(C1->getValue() * C2->getValue());
Chris Lattner623826c2004-09-28 21:48:02 +0000629}
Nick Lewyckyfefd0202008-02-18 22:48:05 +0000630/// MultiplyOverflows - True if the multiply can not be expressed in an int
631/// this size.
632static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
633 uint32_t W = C1->getBitWidth();
634 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
635 if (sign) {
636 LHSExt.sext(W * 2);
637 RHSExt.sext(W * 2);
638 } else {
639 LHSExt.zext(W * 2);
640 RHSExt.zext(W * 2);
641 }
642
643 APInt MulExt = LHSExt * RHSExt;
644
645 if (sign) {
646 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
647 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
648 return MulExt.slt(Min) || MulExt.sgt(Max);
649 } else
650 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
651}
Chris Lattner623826c2004-09-28 21:48:02 +0000652
Chris Lattner4534dd592006-02-09 07:38:58 +0000653/// ComputeMaskedBits - Determine which of the bits specified in Mask are
654/// known to be either zero or one and return them in the KnownZero/KnownOne
Reid Spenceraa696402007-03-08 01:46:38 +0000655/// bit sets. This code only analyzes bits in Mask, in order to short-circuit
656/// processing.
657/// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
658/// we cannot optimize based on the assumption that it is zero without changing
659/// it to be an explicit zero. If we don't change it to zero, other code could
660/// optimized based on the contradictory assumption that it is non-zero.
661/// Because instcombine aggressively folds operations with undef args anyway,
662/// this won't lose us code quality.
Dan Gohman99b7b3f2008-04-10 18:43:06 +0000663void InstCombiner::ComputeMaskedBits(Value *V, const APInt &Mask,
664 APInt& KnownZero, APInt& KnownOne,
665 unsigned Depth) {
Zhou Shengaf4341d2007-03-13 02:23:10 +0000666 assert(V && "No Value?");
667 assert(Depth <= 6 && "Limit Search Depth");
Reid Spenceraa696402007-03-08 01:46:38 +0000668 uint32_t BitWidth = Mask.getBitWidth();
Dan Gohman99b7b3f2008-04-10 18:43:06 +0000669 assert((V->getType()->isInteger() || isa<PointerType>(V->getType())) &&
670 "Not integer or pointer type!");
671 assert((!TD || TD->getTypeSizeInBits(V->getType()) == BitWidth) &&
672 (!isa<IntegerType>(V->getType()) ||
673 V->getType()->getPrimitiveSizeInBits() == BitWidth) &&
Zhou Shengaf4341d2007-03-13 02:23:10 +0000674 KnownZero.getBitWidth() == BitWidth &&
Reid Spenceraa696402007-03-08 01:46:38 +0000675 KnownOne.getBitWidth() == BitWidth &&
Zhou Sheng57e3f732007-03-28 02:19:03 +0000676 "V, Mask, KnownOne and KnownZero should have same BitWidth");
Reid Spenceraa696402007-03-08 01:46:38 +0000677 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
678 // We know all of the bits for a constant!
Zhou Shengaf4341d2007-03-13 02:23:10 +0000679 KnownOne = CI->getValue() & Mask;
Reid Spenceraa696402007-03-08 01:46:38 +0000680 KnownZero = ~KnownOne & Mask;
681 return;
682 }
Dan Gohman99b7b3f2008-04-10 18:43:06 +0000683 // Null is all-zeros.
684 if (isa<ConstantPointerNull>(V)) {
685 KnownOne.clear();
686 KnownZero = Mask;
687 return;
688 }
689 // The address of an aligned GlobalValue has trailing zeros.
690 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
691 unsigned Align = GV->getAlignment();
692 if (Align == 0 && TD && GV->getType()->getElementType()->isSized())
693 Align = TD->getPrefTypeAlignment(GV->getType()->getElementType());
694 if (Align > 0)
695 KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
696 CountTrailingZeros_32(Align));
697 else
698 KnownZero.clear();
699 KnownOne.clear();
700 return;
701 }
Reid Spenceraa696402007-03-08 01:46:38 +0000702
Dan Gohman72ec3f42008-04-28 17:02:21 +0000703 KnownZero.clear(); KnownOne.clear(); // Start out not knowing anything.
704
Reid Spenceraa696402007-03-08 01:46:38 +0000705 if (Depth == 6 || Mask == 0)
706 return; // Limit search depth.
707
Dan Gohman99b7b3f2008-04-10 18:43:06 +0000708 User *I = dyn_cast<User>(V);
Reid Spenceraa696402007-03-08 01:46:38 +0000709 if (!I) return;
710
711 APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
Dan Gohman99b7b3f2008-04-10 18:43:06 +0000712 switch (getOpcode(I)) {
713 default: break;
Reid Spencerd8aad612007-03-25 02:03:12 +0000714 case Instruction::And: {
Reid Spenceraa696402007-03-08 01:46:38 +0000715 // If either the LHS or the RHS are Zero, the result is zero.
716 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
Reid Spencerd8aad612007-03-25 02:03:12 +0000717 APInt Mask2(Mask & ~KnownZero);
718 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
Reid Spenceraa696402007-03-08 01:46:38 +0000719 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
720 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
721
722 // Output known-1 bits are only known if set in both the LHS & RHS.
723 KnownOne &= KnownOne2;
724 // Output known-0 are known to be clear if zero in either the LHS | RHS.
725 KnownZero |= KnownZero2;
726 return;
Reid Spencerd8aad612007-03-25 02:03:12 +0000727 }
728 case Instruction::Or: {
Reid Spenceraa696402007-03-08 01:46:38 +0000729 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
Reid Spencerd8aad612007-03-25 02:03:12 +0000730 APInt Mask2(Mask & ~KnownOne);
731 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
Reid Spenceraa696402007-03-08 01:46:38 +0000732 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
733 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
734
735 // Output known-0 bits are only known if clear in both the LHS & RHS.
736 KnownZero &= KnownZero2;
737 // Output known-1 are known to be set if set in either the LHS | RHS.
738 KnownOne |= KnownOne2;
739 return;
Reid Spencerd8aad612007-03-25 02:03:12 +0000740 }
Reid Spenceraa696402007-03-08 01:46:38 +0000741 case Instruction::Xor: {
742 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
743 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
744 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
745 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
746
747 // Output known-0 bits are known if clear or set in both the LHS & RHS.
748 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
749 // Output known-1 are known to be set if set in only one of the LHS, RHS.
750 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
751 KnownZero = KnownZeroOut;
752 return;
753 }
Dan Gohman99b7b3f2008-04-10 18:43:06 +0000754 case Instruction::Mul: {
755 APInt Mask2 = APInt::getAllOnesValue(BitWidth);
756 ComputeMaskedBits(I->getOperand(1), Mask2, KnownZero, KnownOne, Depth+1);
757 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
758 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
759 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
760
761 // If low bits are zero in either operand, output low known-0 bits.
Dan Gohman72ec3f42008-04-28 17:02:21 +0000762 // Also compute a conserative estimate for high known-0 bits.
Dan Gohman99b7b3f2008-04-10 18:43:06 +0000763 // More trickiness is possible, but this is sufficient for the
764 // interesting case of alignment computation.
765 KnownOne.clear();
766 unsigned TrailZ = KnownZero.countTrailingOnes() +
767 KnownZero2.countTrailingOnes();
Dan Gohman72ec3f42008-04-28 17:02:21 +0000768 unsigned LeadZ = std::max(KnownZero.countLeadingOnes() +
769 KnownZero2.countLeadingOnes() +
770 1, BitWidth) - BitWidth;
771
Dan Gohman99b7b3f2008-04-10 18:43:06 +0000772 TrailZ = std::min(TrailZ, BitWidth);
Dan Gohman72ec3f42008-04-28 17:02:21 +0000773 LeadZ = std::min(LeadZ, BitWidth);
774 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) |
775 APInt::getHighBitsSet(BitWidth, LeadZ);
Dan Gohman99b7b3f2008-04-10 18:43:06 +0000776 KnownZero &= Mask;
777 return;
778 }
Dan Gohman72ec3f42008-04-28 17:02:21 +0000779 case Instruction::UDiv: {
780 // For the purposes of computing leading zeros we can conservatively
781 // treat a udiv as a logical right shift by the power of 2 known to
782 // be greater than the denominator.
783 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
784 ComputeMaskedBits(I->getOperand(0),
785 AllOnes, KnownZero2, KnownOne2, Depth+1);
786 unsigned LeadZ = KnownZero2.countLeadingOnes();
787
788 KnownOne2.clear();
789 KnownZero2.clear();
790 ComputeMaskedBits(I->getOperand(1),
791 AllOnes, KnownZero2, KnownOne2, Depth+1);
792 LeadZ = std::min(BitWidth,
793 LeadZ + BitWidth - KnownOne2.countLeadingZeros());
794
795 KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ) & Mask;
796 return;
797 }
Reid Spenceraa696402007-03-08 01:46:38 +0000798 case Instruction::Select:
799 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
800 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
801 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
802 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
803
804 // Only known if known in both the LHS and RHS.
805 KnownOne &= KnownOne2;
806 KnownZero &= KnownZero2;
807 return;
808 case Instruction::FPTrunc:
809 case Instruction::FPExt:
810 case Instruction::FPToUI:
811 case Instruction::FPToSI:
812 case Instruction::SIToFP:
Reid Spenceraa696402007-03-08 01:46:38 +0000813 case Instruction::UIToFP:
Dan Gohman99b7b3f2008-04-10 18:43:06 +0000814 return; // Can't work with floating point.
815 case Instruction::PtrToInt:
Reid Spenceraa696402007-03-08 01:46:38 +0000816 case Instruction::IntToPtr:
Dan Gohman99b7b3f2008-04-10 18:43:06 +0000817 // We can't handle these if we don't know the pointer size.
818 if (!TD) return;
819 // Fall through and handle them the same as zext/trunc.
820 case Instruction::ZExt:
Zhou Shengaf4341d2007-03-13 02:23:10 +0000821 case Instruction::Trunc: {
Reid Spenceraa696402007-03-08 01:46:38 +0000822 // All these have integer operands
Dan Gohman99b7b3f2008-04-10 18:43:06 +0000823 const Type *SrcTy = I->getOperand(0)->getType();
824 uint32_t SrcBitWidth = TD ?
825 TD->getTypeSizeInBits(SrcTy) :
826 SrcTy->getPrimitiveSizeInBits();
Zhou Sheng57e3f732007-03-28 02:19:03 +0000827 APInt MaskIn(Mask);
Dan Gohman99b7b3f2008-04-10 18:43:06 +0000828 MaskIn.zextOrTrunc(SrcBitWidth);
829 KnownZero.zextOrTrunc(SrcBitWidth);
830 KnownOne.zextOrTrunc(SrcBitWidth);
Zhou Sheng57e3f732007-03-28 02:19:03 +0000831 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
Dan Gohman99b7b3f2008-04-10 18:43:06 +0000832 KnownZero.zextOrTrunc(BitWidth);
833 KnownOne.zextOrTrunc(BitWidth);
834 // Any top bits are known to be zero.
835 if (BitWidth > SrcBitWidth)
836 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spenceraa696402007-03-08 01:46:38 +0000837 return;
Zhou Shengaf4341d2007-03-13 02:23:10 +0000838 }
Reid Spenceraa696402007-03-08 01:46:38 +0000839 case Instruction::BitCast: {
840 const Type *SrcTy = I->getOperand(0)->getType();
Dan Gohman99b7b3f2008-04-10 18:43:06 +0000841 if (SrcTy->isInteger() || isa<PointerType>(SrcTy)) {
Reid Spenceraa696402007-03-08 01:46:38 +0000842 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
843 return;
844 }
845 break;
846 }
Reid Spenceraa696402007-03-08 01:46:38 +0000847 case Instruction::SExt: {
848 // Compute the bits in the result that are not present in the input.
849 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Zhou Shengaf4341d2007-03-13 02:23:10 +0000850 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencercd99fbd2007-03-25 04:26:16 +0000851
Zhou Sheng57e3f732007-03-28 02:19:03 +0000852 APInt MaskIn(Mask);
853 MaskIn.trunc(SrcBitWidth);
854 KnownZero.trunc(SrcBitWidth);
855 KnownOne.trunc(SrcBitWidth);
856 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
Reid Spenceraa696402007-03-08 01:46:38 +0000857 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Zhou Shengaf4341d2007-03-13 02:23:10 +0000858 KnownZero.zext(BitWidth);
859 KnownOne.zext(BitWidth);
Reid Spenceraa696402007-03-08 01:46:38 +0000860
861 // If the sign bit of the input is known set or clear, then we know the
862 // top bits of the result.
Zhou Sheng57e3f732007-03-28 02:19:03 +0000863 if (KnownZero[SrcBitWidth-1]) // Input sign bit known zero
Zhou Sheng117477e2007-03-28 17:38:21 +0000864 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Zhou Sheng57e3f732007-03-28 02:19:03 +0000865 else if (KnownOne[SrcBitWidth-1]) // Input sign bit known set
Zhou Sheng117477e2007-03-28 17:38:21 +0000866 KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spenceraa696402007-03-08 01:46:38 +0000867 return;
868 }
869 case Instruction::Shl:
870 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
871 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Shengb25806f2007-03-30 09:29:48 +0000872 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencerd8aad612007-03-25 02:03:12 +0000873 APInt Mask2(Mask.lshr(ShiftAmt));
874 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, Depth+1);
Reid Spenceraa696402007-03-08 01:46:38 +0000875 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Zhou Shengb3e00c42007-03-12 05:44:52 +0000876 KnownZero <<= ShiftAmt;
877 KnownOne <<= ShiftAmt;
Reid Spencer624766f2007-03-25 19:55:33 +0000878 KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt); // low bits known 0
Reid Spenceraa696402007-03-08 01:46:38 +0000879 return;
880 }
881 break;
882 case Instruction::LShr:
883 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
884 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
885 // Compute the new bits that are at the top now.
Zhou Shengb25806f2007-03-30 09:29:48 +0000886 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spenceraa696402007-03-08 01:46:38 +0000887
888 // Unsigned shift right.
Reid Spencerd8aad612007-03-25 02:03:12 +0000889 APInt Mask2(Mask.shl(ShiftAmt));
890 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
Reid Spenceraa696402007-03-08 01:46:38 +0000891 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
892 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
893 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
Zhou Sheng57e3f732007-03-28 02:19:03 +0000894 // high bits known zero.
895 KnownZero |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
Reid Spenceraa696402007-03-08 01:46:38 +0000896 return;
897 }
898 break;
899 case Instruction::AShr:
Zhou Sheng57e3f732007-03-28 02:19:03 +0000900 // (ashr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
Reid Spenceraa696402007-03-08 01:46:38 +0000901 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
902 // Compute the new bits that are at the top now.
Zhou Shengb25806f2007-03-30 09:29:48 +0000903 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spenceraa696402007-03-08 01:46:38 +0000904
905 // Signed shift right.
Reid Spencerd8aad612007-03-25 02:03:12 +0000906 APInt Mask2(Mask.shl(ShiftAmt));
907 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
Reid Spenceraa696402007-03-08 01:46:38 +0000908 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
909 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
910 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
911
Zhou Sheng57e3f732007-03-28 02:19:03 +0000912 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
913 if (KnownZero[BitWidth-ShiftAmt-1]) // New bits are known zero.
Reid Spenceraa696402007-03-08 01:46:38 +0000914 KnownZero |= HighBits;
Zhou Sheng57e3f732007-03-28 02:19:03 +0000915 else if (KnownOne[BitWidth-ShiftAmt-1]) // New bits are known one.
Reid Spenceraa696402007-03-08 01:46:38 +0000916 KnownOne |= HighBits;
Reid Spenceraa696402007-03-08 01:46:38 +0000917 return;
918 }
919 break;
Dan Gohman99b7b3f2008-04-10 18:43:06 +0000920 case Instruction::Sub: {
921 if (ConstantInt *CLHS = dyn_cast<ConstantInt>(I->getOperand(0))) {
922 // We know that the top bits of C-X are clear if X contains less bits
923 // than C (i.e. no wrap-around can happen). For example, 20-X is
924 // positive if we can prove that X is >= 0 and < 16.
925 if (!CLHS->getValue().isNegative()) {
926 unsigned NLZ = (CLHS->getValue()+1).countLeadingZeros();
927 // NLZ can't be BitWidth with no sign bit
928 APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
Dan Gohman72ec3f42008-04-28 17:02:21 +0000929 ComputeMaskedBits(I->getOperand(1), MaskV, KnownZero2, KnownOne2,
930 Depth+1);
Dan Gohman99b7b3f2008-04-10 18:43:06 +0000931
Dan Gohman72ec3f42008-04-28 17:02:21 +0000932 // If all of the MaskV bits are known to be zero, then we know the
933 // output top bits are zero, because we now know that the output is
934 // from [0-C].
935 if ((KnownZero2 & MaskV) == MaskV) {
Dan Gohman99b7b3f2008-04-10 18:43:06 +0000936 unsigned NLZ2 = CLHS->getValue().countLeadingZeros();
937 // Top bits known zero.
938 KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2) & Mask;
Dan Gohman99b7b3f2008-04-10 18:43:06 +0000939 }
Dan Gohman99b7b3f2008-04-10 18:43:06 +0000940 }
941 }
942 }
943 // fall through
Duncan Sandsc9e09a02008-03-21 08:32:17 +0000944 case Instruction::Add: {
Chris Lattnerc44160c2008-03-21 05:19:58 +0000945 // Output known-0 bits are known if clear or set in both the low clear bits
946 // common to both LHS & RHS. For example, 8+(X<<3) is known to have the
947 // low 3 bits clear.
Dan Gohman72ec3f42008-04-28 17:02:21 +0000948 APInt Mask2 = APInt::getLowBitsSet(BitWidth, Mask.countTrailingOnes());
949 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
950 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
951 unsigned KnownZeroOut = KnownZero2.countTrailingOnes();
952
953 ComputeMaskedBits(I->getOperand(1), Mask2, KnownZero2, KnownOne2, Depth+1);
954 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
955 KnownZeroOut = std::min(KnownZeroOut,
956 KnownZero2.countTrailingOnes());
957
958 KnownZero |= APInt::getLowBitsSet(BitWidth, KnownZeroOut);
Chris Lattnerc44160c2008-03-21 05:19:58 +0000959 return;
Duncan Sandsc9e09a02008-03-21 08:32:17 +0000960 }
Nick Lewyckyd0b62a12008-03-06 06:48:30 +0000961 case Instruction::SRem:
962 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
963 APInt RA = Rem->getValue();
964 if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
965 APInt LowBits = RA.isStrictlyPositive() ? ((RA - 1) | RA) : ~RA;
966 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
967 ComputeMaskedBits(I->getOperand(0), Mask2,KnownZero2,KnownOne2,Depth+1);
968
969 // The sign of a remainder is equal to the sign of the first
970 // operand (zero being positive).
971 if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
972 KnownZero2 |= ~LowBits;
973 else if (KnownOne2[BitWidth-1])
974 KnownOne2 |= ~LowBits;
975
976 KnownZero |= KnownZero2 & Mask;
977 KnownOne |= KnownOne2 & Mask;
978
979 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
980 }
981 }
982 break;
Dan Gohman72ec3f42008-04-28 17:02:21 +0000983 case Instruction::URem: {
Nick Lewyckyd0b62a12008-03-06 06:48:30 +0000984 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
985 APInt RA = Rem->getValue();
986 if (RA.isStrictlyPositive() && RA.isPowerOf2()) {
987 APInt LowBits = (RA - 1) | RA;
988 APInt Mask2 = LowBits & Mask;
989 KnownZero |= ~LowBits & Mask;
990 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne,Depth+1);
991 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
Dan Gohman72ec3f42008-04-28 17:02:21 +0000992 break;
Nick Lewyckyd0b62a12008-03-06 06:48:30 +0000993 }
Nick Lewyckyd0b62a12008-03-06 06:48:30 +0000994 }
Dan Gohman72ec3f42008-04-28 17:02:21 +0000995
996 // Since the result is less than or equal to either operand, any leading
997 // zero bits in either operand must also exist in the result.
998 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
999 ComputeMaskedBits(I->getOperand(0), AllOnes, KnownZero, KnownOne,
1000 Depth+1);
1001 ComputeMaskedBits(I->getOperand(1), AllOnes, KnownZero2, KnownOne2,
1002 Depth+1);
1003
1004 uint32_t Leaders = std::max(KnownZero.countLeadingOnes(),
1005 KnownZero2.countLeadingOnes());
1006 KnownOne.clear();
1007 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & Mask;
Nick Lewyckyd0b62a12008-03-06 06:48:30 +00001008 break;
Dan Gohman72ec3f42008-04-28 17:02:21 +00001009 }
Dan Gohman99b7b3f2008-04-10 18:43:06 +00001010
1011 case Instruction::Alloca:
1012 case Instruction::Malloc: {
1013 AllocationInst *AI = cast<AllocationInst>(V);
1014 unsigned Align = AI->getAlignment();
1015 if (Align == 0 && TD) {
1016 if (isa<AllocaInst>(AI))
1017 Align = TD->getPrefTypeAlignment(AI->getType()->getElementType());
1018 else if (isa<MallocInst>(AI)) {
1019 // Malloc returns maximally aligned memory.
1020 Align = TD->getABITypeAlignment(AI->getType()->getElementType());
1021 Align =
1022 std::max(Align,
1023 (unsigned)TD->getABITypeAlignment(Type::DoubleTy));
1024 Align =
1025 std::max(Align,
1026 (unsigned)TD->getABITypeAlignment(Type::Int64Ty));
1027 }
1028 }
1029
1030 if (Align > 0)
1031 KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
1032 CountTrailingZeros_32(Align));
1033 break;
1034 }
1035 case Instruction::GetElementPtr: {
1036 // Analyze all of the subscripts of this getelementptr instruction
1037 // to determine if we can prove known low zero bits.
1038 APInt LocalMask = APInt::getAllOnesValue(BitWidth);
1039 APInt LocalKnownZero(BitWidth, 0), LocalKnownOne(BitWidth, 0);
1040 ComputeMaskedBits(I->getOperand(0), LocalMask,
1041 LocalKnownZero, LocalKnownOne, Depth+1);
1042 unsigned TrailZ = LocalKnownZero.countTrailingOnes();
1043
1044 gep_type_iterator GTI = gep_type_begin(I);
1045 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) {
1046 Value *Index = I->getOperand(i);
1047 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
1048 // Handle struct member offset arithmetic.
1049 if (!TD) return;
1050 const StructLayout *SL = TD->getStructLayout(STy);
1051 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
1052 uint64_t Offset = SL->getElementOffset(Idx);
1053 TrailZ = std::min(TrailZ,
1054 CountTrailingZeros_64(Offset));
1055 } else {
1056 // Handle array index arithmetic.
1057 const Type *IndexedTy = GTI.getIndexedType();
1058 if (!IndexedTy->isSized()) return;
1059 unsigned GEPOpiBits = Index->getType()->getPrimitiveSizeInBits();
1060 uint64_t TypeSize = TD ? TD->getABITypeSize(IndexedTy) : 1;
1061 LocalMask = APInt::getAllOnesValue(GEPOpiBits);
1062 LocalKnownZero = LocalKnownOne = APInt(GEPOpiBits, 0);
1063 ComputeMaskedBits(Index, LocalMask,
1064 LocalKnownZero, LocalKnownOne, Depth+1);
1065 TrailZ = std::min(TrailZ,
1066 CountTrailingZeros_64(TypeSize) +
1067 LocalKnownZero.countTrailingOnes());
1068 }
1069 }
1070
1071 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) & Mask;
1072 break;
1073 }
1074 case Instruction::PHI: {
1075 PHINode *P = cast<PHINode>(I);
1076 // Handle the case of a simple two-predecessor recurrence PHI.
1077 // There's a lot more that could theoretically be done here, but
1078 // this is sufficient to catch some interesting cases.
1079 if (P->getNumIncomingValues() == 2) {
1080 for (unsigned i = 0; i != 2; ++i) {
1081 Value *L = P->getIncomingValue(i);
1082 Value *R = P->getIncomingValue(!i);
1083 User *LU = dyn_cast<User>(L);
1084 unsigned Opcode = LU ? getOpcode(LU) : (unsigned)Instruction::UserOp1;
1085 // Check for operations that have the property that if
1086 // both their operands have low zero bits, the result
1087 // will have low zero bits.
1088 if (Opcode == Instruction::Add ||
1089 Opcode == Instruction::Sub ||
1090 Opcode == Instruction::And ||
1091 Opcode == Instruction::Or ||
1092 Opcode == Instruction::Mul) {
1093 Value *LL = LU->getOperand(0);
1094 Value *LR = LU->getOperand(1);
1095 // Find a recurrence.
1096 if (LL == I)
1097 L = LR;
1098 else if (LR == I)
1099 L = LL;
1100 else
1101 break;
1102 // Ok, we have a PHI of the form L op= R. Check for low
1103 // zero bits.
1104 APInt Mask2 = APInt::getAllOnesValue(BitWidth);
1105 ComputeMaskedBits(R, Mask2, KnownZero2, KnownOne2, Depth+1);
1106 Mask2 = APInt::getLowBitsSet(BitWidth,
1107 KnownZero2.countTrailingOnes());
1108 KnownOne2.clear();
1109 KnownZero2.clear();
1110 ComputeMaskedBits(L, Mask2, KnownZero2, KnownOne2, Depth+1);
1111 KnownZero = Mask &
1112 APInt::getLowBitsSet(BitWidth,
1113 KnownZero2.countTrailingOnes());
1114 break;
1115 }
1116 }
1117 }
1118 break;
1119 }
Dan Gohman72ec3f42008-04-28 17:02:21 +00001120 case Instruction::Call:
1121 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1122 switch (II->getIntrinsicID()) {
1123 default: break;
1124 case Intrinsic::ctpop:
1125 case Intrinsic::ctlz:
1126 case Intrinsic::cttz: {
1127 unsigned LowBits = Log2_32(BitWidth)+1;
1128 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
1129 break;
1130 }
1131 }
1132 }
1133 break;
Reid Spenceraa696402007-03-08 01:46:38 +00001134 }
1135}
1136
Reid Spencerbb5741f2007-03-08 01:52:58 +00001137/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
1138/// this predicate to simplify operations downstream. Mask is known to be zero
1139/// for bits that V cannot have.
Dan Gohman99b7b3f2008-04-10 18:43:06 +00001140bool InstCombiner::MaskedValueIsZero(Value *V, const APInt& Mask,
1141 unsigned Depth) {
Zhou Shengbe171ee2007-03-12 16:54:56 +00001142 APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
Reid Spencerbb5741f2007-03-08 01:52:58 +00001143 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
1144 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1145 return (KnownZero & Mask) == Mask;
1146}
1147
Chris Lattner0157e7f2006-02-11 09:31:47 +00001148/// ShrinkDemandedConstant - Check to see if the specified operand of the
1149/// specified instruction is a constant integer. If so, check to see if there
1150/// are any bits set in the constant that are not demanded. If so, shrink the
1151/// constant and return true.
1152static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Reid Spencerd9281782007-03-12 17:15:10 +00001153 APInt Demanded) {
1154 assert(I && "No instruction?");
1155 assert(OpNo < I->getNumOperands() && "Operand index too large");
1156
1157 // If the operand is not a constant integer, nothing to do.
1158 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
1159 if (!OpC) return false;
1160
1161 // If there are no bits set that aren't demanded, nothing to do.
1162 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
1163 if ((~Demanded & OpC->getValue()) == 0)
1164 return false;
1165
1166 // This instruction is producing bits that are not demanded. Shrink the RHS.
1167 Demanded &= OpC->getValue();
1168 I->setOperand(OpNo, ConstantInt::get(Demanded));
1169 return true;
1170}
1171
Chris Lattneree0f2802006-02-12 02:07:56 +00001172// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
1173// set of known zero and one bits, compute the maximum and minimum values that
1174// could have the specified known zero and known one bits, returning them in
1175// min/max.
1176static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00001177 const APInt& KnownZero,
1178 const APInt& KnownOne,
1179 APInt& Min, APInt& Max) {
1180 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
1181 assert(KnownZero.getBitWidth() == BitWidth &&
1182 KnownOne.getBitWidth() == BitWidth &&
1183 Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
1184 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencercd99fbd2007-03-25 04:26:16 +00001185 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattneree0f2802006-02-12 02:07:56 +00001186
Chris Lattneree0f2802006-02-12 02:07:56 +00001187 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
1188 // bit if it is unknown.
1189 Min = KnownOne;
1190 Max = KnownOne|UnknownBits;
1191
Zhou Shengc2d33092007-03-28 05:15:57 +00001192 if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
Zhou Sheng9bc8ab12007-04-02 13:45:30 +00001193 Min.set(BitWidth-1);
1194 Max.clear(BitWidth-1);
Chris Lattneree0f2802006-02-12 02:07:56 +00001195 }
Chris Lattneree0f2802006-02-12 02:07:56 +00001196}
1197
1198// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
1199// a set of known zero and one bits, compute the maximum and minimum values that
1200// could have the specified known zero and known one bits, returning them in
1201// min/max.
1202static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
Chris Lattnerf0da7972007-08-05 08:47:58 +00001203 const APInt &KnownZero,
1204 const APInt &KnownOne,
1205 APInt &Min, APInt &Max) {
1206 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth(); BitWidth = BitWidth;
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00001207 assert(KnownZero.getBitWidth() == BitWidth &&
1208 KnownOne.getBitWidth() == BitWidth &&
1209 Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
1210 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencercd99fbd2007-03-25 04:26:16 +00001211 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattneree0f2802006-02-12 02:07:56 +00001212
1213 // The minimum value is when the unknown bits are all zeros.
1214 Min = KnownOne;
1215 // The maximum value is when the unknown bits are all ones.
1216 Max = KnownOne|UnknownBits;
1217}
Chris Lattner0157e7f2006-02-11 09:31:47 +00001218
Reid Spencer1791f232007-03-12 17:25:59 +00001219/// SimplifyDemandedBits - This function attempts to replace V with a simpler
1220/// value based on the demanded bits. When this function is called, it is known
1221/// that only the bits set in DemandedMask of the result of V are ever used
1222/// downstream. Consequently, depending on the mask and V, it may be possible
1223/// to replace V with a constant or one of its operands. In such cases, this
1224/// function does the replacement and returns true. In all other cases, it
1225/// returns false after analyzing the expression and setting KnownOne and known
1226/// to be one in the expression. KnownZero contains all the bits that are known
1227/// to be zero in the expression. These are provided to potentially allow the
1228/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
1229/// the expression. KnownOne and KnownZero always follow the invariant that
1230/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
1231/// the bits in KnownOne and KnownZero may only be accurate for those bits set
1232/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
1233/// and KnownOne must all be the same.
1234bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
1235 APInt& KnownZero, APInt& KnownOne,
1236 unsigned Depth) {
1237 assert(V != 0 && "Null pointer of Value???");
1238 assert(Depth <= 6 && "Limit Search Depth");
1239 uint32_t BitWidth = DemandedMask.getBitWidth();
1240 const IntegerType *VTy = cast<IntegerType>(V->getType());
1241 assert(VTy->getBitWidth() == BitWidth &&
1242 KnownZero.getBitWidth() == BitWidth &&
1243 KnownOne.getBitWidth() == BitWidth &&
1244 "Value *V, DemandedMask, KnownZero and KnownOne \
1245 must have same BitWidth");
1246 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
1247 // We know all of the bits for a constant!
1248 KnownOne = CI->getValue() & DemandedMask;
1249 KnownZero = ~KnownOne & DemandedMask;
1250 return false;
1251 }
1252
Zhou Shengb9128442007-03-14 03:21:24 +00001253 KnownZero.clear();
1254 KnownOne.clear();
Reid Spencer1791f232007-03-12 17:25:59 +00001255 if (!V->hasOneUse()) { // Other users may use these bits.
1256 if (Depth != 0) { // Not at the root.
1257 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
1258 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
1259 return false;
1260 }
1261 // If this is the root being simplified, allow it to have multiple uses,
1262 // just set the DemandedMask to all bits.
1263 DemandedMask = APInt::getAllOnesValue(BitWidth);
1264 } else if (DemandedMask == 0) { // Not demanding any bits from V.
1265 if (V != UndefValue::get(VTy))
1266 return UpdateValueUsesWith(V, UndefValue::get(VTy));
1267 return false;
1268 } else if (Depth == 6) { // Limit search depth.
1269 return false;
1270 }
1271
1272 Instruction *I = dyn_cast<Instruction>(V);
1273 if (!I) return false; // Only analyze instructions.
1274
Reid Spencer1791f232007-03-12 17:25:59 +00001275 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
1276 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
1277 switch (I->getOpcode()) {
Dan Gohman72ec3f42008-04-28 17:02:21 +00001278 default:
1279 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1280 break;
Reid Spencer1791f232007-03-12 17:25:59 +00001281 case Instruction::And:
1282 // If either the LHS or the RHS are Zero, the result is zero.
1283 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1284 RHSKnownZero, RHSKnownOne, Depth+1))
1285 return true;
1286 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1287 "Bits known to be one AND zero?");
1288
1289 // If something is known zero on the RHS, the bits aren't demanded on the
1290 // LHS.
1291 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
1292 LHSKnownZero, LHSKnownOne, Depth+1))
1293 return true;
1294 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1295 "Bits known to be one AND zero?");
1296
1297 // If all of the demanded bits are known 1 on one side, return the other.
1298 // These bits cannot contribute to the result of the 'and'.
1299 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
1300 (DemandedMask & ~LHSKnownZero))
1301 return UpdateValueUsesWith(I, I->getOperand(0));
1302 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
1303 (DemandedMask & ~RHSKnownZero))
1304 return UpdateValueUsesWith(I, I->getOperand(1));
1305
1306 // If all of the demanded bits in the inputs are known zeros, return zero.
1307 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
1308 return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
1309
1310 // If the RHS is a constant, see if we can simplify it.
1311 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
1312 return UpdateValueUsesWith(I, I);
1313
1314 // Output known-1 bits are only known if set in both the LHS & RHS.
1315 RHSKnownOne &= LHSKnownOne;
1316 // Output known-0 are known to be clear if zero in either the LHS | RHS.
1317 RHSKnownZero |= LHSKnownZero;
1318 break;
1319 case Instruction::Or:
1320 // If either the LHS or the RHS are One, the result is One.
1321 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1322 RHSKnownZero, RHSKnownOne, Depth+1))
1323 return true;
1324 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1325 "Bits known to be one AND zero?");
1326 // If something is known one on the RHS, the bits aren't demanded on the
1327 // LHS.
1328 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
1329 LHSKnownZero, LHSKnownOne, Depth+1))
1330 return true;
1331 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1332 "Bits known to be one AND zero?");
1333
1334 // If all of the demanded bits are known zero on one side, return the other.
1335 // These bits cannot contribute to the result of the 'or'.
1336 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
1337 (DemandedMask & ~LHSKnownOne))
1338 return UpdateValueUsesWith(I, I->getOperand(0));
1339 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
1340 (DemandedMask & ~RHSKnownOne))
1341 return UpdateValueUsesWith(I, I->getOperand(1));
1342
1343 // If all of the potentially set bits on one side are known to be set on
1344 // the other side, just use the 'other' side.
1345 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
1346 (DemandedMask & (~RHSKnownZero)))
1347 return UpdateValueUsesWith(I, I->getOperand(0));
1348 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
1349 (DemandedMask & (~LHSKnownZero)))
1350 return UpdateValueUsesWith(I, I->getOperand(1));
1351
1352 // If the RHS is a constant, see if we can simplify it.
1353 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1354 return UpdateValueUsesWith(I, I);
1355
1356 // Output known-0 bits are only known if clear in both the LHS & RHS.
1357 RHSKnownZero &= LHSKnownZero;
1358 // Output known-1 are known to be set if set in either the LHS | RHS.
1359 RHSKnownOne |= LHSKnownOne;
1360 break;
1361 case Instruction::Xor: {
1362 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1363 RHSKnownZero, RHSKnownOne, Depth+1))
1364 return true;
1365 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1366 "Bits known to be one AND zero?");
1367 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1368 LHSKnownZero, LHSKnownOne, Depth+1))
1369 return true;
1370 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1371 "Bits known to be one AND zero?");
1372
1373 // If all of the demanded bits are known zero on one side, return the other.
1374 // These bits cannot contribute to the result of the 'xor'.
1375 if ((DemandedMask & RHSKnownZero) == DemandedMask)
1376 return UpdateValueUsesWith(I, I->getOperand(0));
1377 if ((DemandedMask & LHSKnownZero) == DemandedMask)
1378 return UpdateValueUsesWith(I, I->getOperand(1));
1379
1380 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1381 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1382 (RHSKnownOne & LHSKnownOne);
1383 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1384 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1385 (RHSKnownOne & LHSKnownZero);
1386
1387 // If all of the demanded bits are known to be zero on one side or the
1388 // other, turn this into an *inclusive* or.
1389 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1390 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
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 // If all of the demanded bits on one side are known, and all of the set
1399 // bits on that side are also known to be set on the other side, turn this
1400 // into an AND, as we know the bits will be cleared.
1401 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1402 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1403 // all known
1404 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1405 Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
1406 Instruction *And =
1407 BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
1408 InsertNewInstBefore(And, *I);
1409 return UpdateValueUsesWith(I, And);
1410 }
1411 }
1412
1413 // If the RHS is a constant, see if we can simplify it.
1414 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1415 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1416 return UpdateValueUsesWith(I, I);
1417
1418 RHSKnownZero = KnownZeroOut;
1419 RHSKnownOne = KnownOneOut;
1420 break;
1421 }
1422 case Instruction::Select:
1423 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
1424 RHSKnownZero, RHSKnownOne, Depth+1))
1425 return true;
1426 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1427 LHSKnownZero, LHSKnownOne, Depth+1))
1428 return true;
1429 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1430 "Bits known to be one AND zero?");
1431 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1432 "Bits known to be one AND zero?");
1433
1434 // If the operands are constants, see if we can simplify them.
1435 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1436 return UpdateValueUsesWith(I, I);
1437 if (ShrinkDemandedConstant(I, 2, DemandedMask))
1438 return UpdateValueUsesWith(I, I);
1439
1440 // Only known if known in both the LHS and RHS.
1441 RHSKnownOne &= LHSKnownOne;
1442 RHSKnownZero &= LHSKnownZero;
1443 break;
1444 case Instruction::Trunc: {
1445 uint32_t truncBf =
1446 cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
Zhou Shenga4475572007-03-29 02:26:30 +00001447 DemandedMask.zext(truncBf);
1448 RHSKnownZero.zext(truncBf);
1449 RHSKnownOne.zext(truncBf);
1450 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1451 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer1791f232007-03-12 17:25:59 +00001452 return true;
1453 DemandedMask.trunc(BitWidth);
1454 RHSKnownZero.trunc(BitWidth);
1455 RHSKnownOne.trunc(BitWidth);
1456 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1457 "Bits known to be one AND zero?");
1458 break;
1459 }
1460 case Instruction::BitCast:
1461 if (!I->getOperand(0)->getType()->isInteger())
1462 return false;
1463
1464 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1465 RHSKnownZero, RHSKnownOne, Depth+1))
1466 return true;
1467 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1468 "Bits known to be one AND zero?");
1469 break;
1470 case Instruction::ZExt: {
1471 // Compute the bits in the result that are not present in the input.
1472 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Reid Spencercd99fbd2007-03-25 04:26:16 +00001473 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer1791f232007-03-12 17:25:59 +00001474
Zhou Sheng444af492007-03-29 04:45:55 +00001475 DemandedMask.trunc(SrcBitWidth);
1476 RHSKnownZero.trunc(SrcBitWidth);
1477 RHSKnownOne.trunc(SrcBitWidth);
Zhou Shenga4475572007-03-29 02:26:30 +00001478 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1479 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer1791f232007-03-12 17:25:59 +00001480 return true;
1481 DemandedMask.zext(BitWidth);
1482 RHSKnownZero.zext(BitWidth);
1483 RHSKnownOne.zext(BitWidth);
1484 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1485 "Bits known to be one AND zero?");
1486 // The top bits are known to be zero.
Zhou Shenga4475572007-03-29 02:26:30 +00001487 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer1791f232007-03-12 17:25:59 +00001488 break;
1489 }
1490 case Instruction::SExt: {
1491 // Compute the bits in the result that are not present in the input.
1492 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Reid Spencercd99fbd2007-03-25 04:26:16 +00001493 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer1791f232007-03-12 17:25:59 +00001494
Reid Spencer1791f232007-03-12 17:25:59 +00001495 APInt InputDemandedBits = DemandedMask &
Zhou Shenga4475572007-03-29 02:26:30 +00001496 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
Reid Spencer1791f232007-03-12 17:25:59 +00001497
Zhou Shenga4475572007-03-29 02:26:30 +00001498 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
Reid Spencer1791f232007-03-12 17:25:59 +00001499 // If any of the sign extended bits are demanded, we know that the sign
1500 // bit is demanded.
1501 if ((NewBits & DemandedMask) != 0)
Zhou Sheng9bc8ab12007-04-02 13:45:30 +00001502 InputDemandedBits.set(SrcBitWidth-1);
Reid Spencer1791f232007-03-12 17:25:59 +00001503
Zhou Sheng444af492007-03-29 04:45:55 +00001504 InputDemandedBits.trunc(SrcBitWidth);
1505 RHSKnownZero.trunc(SrcBitWidth);
1506 RHSKnownOne.trunc(SrcBitWidth);
Zhou Shenga4475572007-03-29 02:26:30 +00001507 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1508 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer1791f232007-03-12 17:25:59 +00001509 return true;
1510 InputDemandedBits.zext(BitWidth);
1511 RHSKnownZero.zext(BitWidth);
1512 RHSKnownOne.zext(BitWidth);
1513 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1514 "Bits known to be one AND zero?");
1515
1516 // If the sign bit of the input is known set or clear, then we know the
1517 // top bits of the result.
1518
1519 // If the input sign bit is known zero, or if the NewBits are not demanded
1520 // convert this into a zero extension.
Zhou Shenga4475572007-03-29 02:26:30 +00001521 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits)
Reid Spencer1791f232007-03-12 17:25:59 +00001522 {
1523 // Convert to ZExt cast
1524 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1525 return UpdateValueUsesWith(I, NewCast);
Zhou Shenga4475572007-03-29 02:26:30 +00001526 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
Reid Spencer1791f232007-03-12 17:25:59 +00001527 RHSKnownOne |= NewBits;
Reid Spencer1791f232007-03-12 17:25:59 +00001528 }
1529 break;
1530 }
1531 case Instruction::Add: {
1532 // Figure out what the input bits are. If the top bits of the and result
1533 // are not demanded, then the add doesn't demand them from its input
1534 // either.
Reid Spencer52830322007-03-25 21:11:44 +00001535 uint32_t NLZ = DemandedMask.countLeadingZeros();
Reid Spencer1791f232007-03-12 17:25:59 +00001536
1537 // If there is a constant on the RHS, there are a variety of xformations
1538 // we can do.
1539 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1540 // If null, this should be simplified elsewhere. Some of the xforms here
1541 // won't work if the RHS is zero.
1542 if (RHS->isZero())
1543 break;
1544
1545 // If the top bit of the output is demanded, demand everything from the
1546 // input. Otherwise, we demand all the input bits except NLZ top bits.
Zhou Shenga4475572007-03-29 02:26:30 +00001547 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
Reid Spencer1791f232007-03-12 17:25:59 +00001548
1549 // Find information about known zero/one bits in the input.
1550 if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits,
1551 LHSKnownZero, LHSKnownOne, Depth+1))
1552 return true;
1553
1554 // If the RHS of the add has bits set that can't affect the input, reduce
1555 // the constant.
1556 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1557 return UpdateValueUsesWith(I, I);
1558
1559 // Avoid excess work.
1560 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1561 break;
1562
1563 // Turn it into OR if input bits are zero.
1564 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1565 Instruction *Or =
1566 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1567 I->getName());
1568 InsertNewInstBefore(Or, *I);
1569 return UpdateValueUsesWith(I, Or);
1570 }
1571
1572 // We can say something about the output known-zero and known-one bits,
1573 // depending on potential carries from the input constant and the
1574 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1575 // bits set and the RHS constant is 0x01001, then we know we have a known
1576 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1577
1578 // To compute this, we first compute the potential carry bits. These are
1579 // the bits which may be modified. I'm not aware of a better way to do
1580 // this scan.
Zhou Sheng4f164022007-03-31 02:38:39 +00001581 const APInt& RHSVal = RHS->getValue();
1582 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
Reid Spencer1791f232007-03-12 17:25:59 +00001583
1584 // Now that we know which bits have carries, compute the known-1/0 sets.
1585
1586 // Bits are known one if they are known zero in one operand and one in the
1587 // other, and there is no input carry.
1588 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1589 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1590
1591 // Bits are known zero if they are known zero in both operands and there
1592 // is no input carry.
1593 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1594 } else {
1595 // If the high-bits of this ADD are not demanded, then it does not demand
1596 // the high bits of its LHS or RHS.
Zhou Shenga4475572007-03-29 02:26:30 +00001597 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer1791f232007-03-12 17:25:59 +00001598 // Right fill the mask of bits for this ADD to demand the most
1599 // significant bit and all those below it.
Zhou Shenga4475572007-03-29 02:26:30 +00001600 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Reid Spencer1791f232007-03-12 17:25:59 +00001601 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1602 LHSKnownZero, LHSKnownOne, Depth+1))
1603 return true;
1604 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1605 LHSKnownZero, LHSKnownOne, Depth+1))
1606 return true;
1607 }
1608 }
1609 break;
1610 }
1611 case Instruction::Sub:
1612 // If the high-bits of this SUB are not demanded, then it does not demand
1613 // the high bits of its LHS or RHS.
Zhou Shenga4475572007-03-29 02:26:30 +00001614 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer1791f232007-03-12 17:25:59 +00001615 // Right fill the mask of bits for this SUB to demand the most
1616 // significant bit and all those below it.
Zhou Sheng56cda952007-04-02 08:20:41 +00001617 uint32_t NLZ = DemandedMask.countLeadingZeros();
Zhou Shenga4475572007-03-29 02:26:30 +00001618 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Reid Spencer1791f232007-03-12 17:25:59 +00001619 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1620 LHSKnownZero, LHSKnownOne, Depth+1))
1621 return true;
1622 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1623 LHSKnownZero, LHSKnownOne, Depth+1))
1624 return true;
1625 }
Dan Gohman72ec3f42008-04-28 17:02:21 +00001626 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1627 // the known zeros and ones.
1628 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Reid Spencer1791f232007-03-12 17:25:59 +00001629 break;
1630 case Instruction::Shl:
1631 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Shengb25806f2007-03-30 09:29:48 +00001632 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Zhou Shenga4475572007-03-29 02:26:30 +00001633 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1634 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
Reid Spencer1791f232007-03-12 17:25:59 +00001635 RHSKnownZero, RHSKnownOne, Depth+1))
1636 return true;
1637 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1638 "Bits known to be one AND zero?");
1639 RHSKnownZero <<= ShiftAmt;
1640 RHSKnownOne <<= ShiftAmt;
1641 // low bits known zero.
Zhou Shengd8c645b2007-03-14 09:07:33 +00001642 if (ShiftAmt)
Zhou Sheng23f7a1c2007-03-28 15:02:20 +00001643 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
Reid Spencer1791f232007-03-12 17:25:59 +00001644 }
1645 break;
1646 case Instruction::LShr:
1647 // For a logical shift right
1648 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Shengb25806f2007-03-30 09:29:48 +00001649 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer1791f232007-03-12 17:25:59 +00001650
Reid Spencer1791f232007-03-12 17:25:59 +00001651 // Unsigned shift right.
Zhou Shenga4475572007-03-29 02:26:30 +00001652 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1653 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
Reid Spencer1791f232007-03-12 17:25:59 +00001654 RHSKnownZero, RHSKnownOne, Depth+1))
1655 return true;
1656 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1657 "Bits known to be one AND zero?");
Reid Spencer1791f232007-03-12 17:25:59 +00001658 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1659 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
Zhou Shengd8c645b2007-03-14 09:07:33 +00001660 if (ShiftAmt) {
1661 // Compute the new bits that are at the top now.
Zhou Shenga4475572007-03-29 02:26:30 +00001662 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Zhou Shengd8c645b2007-03-14 09:07:33 +00001663 RHSKnownZero |= HighBits; // high bits known zero.
1664 }
Reid Spencer1791f232007-03-12 17:25:59 +00001665 }
1666 break;
1667 case Instruction::AShr:
1668 // If this is an arithmetic shift right and only the low-bit is set, we can
1669 // always convert this into a logical shr, even if the shift amount is
1670 // variable. The low bit of the shift cannot be an input sign bit unless
1671 // the shift amount is >= the size of the datatype, which is undefined.
1672 if (DemandedMask == 1) {
1673 // Perform the logical shift right.
1674 Value *NewVal = BinaryOperator::createLShr(
1675 I->getOperand(0), I->getOperand(1), I->getName());
1676 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1677 return UpdateValueUsesWith(I, NewVal);
1678 }
Chris Lattnerd4fef8d2007-07-15 20:54:51 +00001679
1680 // If the sign bit is the only bit demanded by this ashr, then there is no
1681 // need to do it, the shift doesn't change the high bit.
1682 if (DemandedMask.isSignBit())
1683 return UpdateValueUsesWith(I, I->getOperand(0));
Reid Spencer1791f232007-03-12 17:25:59 +00001684
1685 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Shengfd28a332007-03-30 17:20:39 +00001686 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer1791f232007-03-12 17:25:59 +00001687
Reid Spencer1791f232007-03-12 17:25:59 +00001688 // Signed shift right.
Zhou Shenga4475572007-03-29 02:26:30 +00001689 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Lauro Ramos Venancio368e8872007-06-06 17:08:48 +00001690 // If any of the "high bits" are demanded, we should set the sign bit as
1691 // demanded.
1692 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1693 DemandedMaskIn.set(BitWidth-1);
Reid Spencer1791f232007-03-12 17:25:59 +00001694 if (SimplifyDemandedBits(I->getOperand(0),
Zhou Shenga4475572007-03-29 02:26:30 +00001695 DemandedMaskIn,
Reid Spencer1791f232007-03-12 17:25:59 +00001696 RHSKnownZero, RHSKnownOne, Depth+1))
1697 return true;
1698 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1699 "Bits known to be one AND zero?");
1700 // Compute the new bits that are at the top now.
Zhou Shenga4475572007-03-29 02:26:30 +00001701 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Reid Spencer1791f232007-03-12 17:25:59 +00001702 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1703 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1704
1705 // Handle the sign bits.
1706 APInt SignBit(APInt::getSignBit(BitWidth));
1707 // Adjust to where it is now in the mask.
1708 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1709
1710 // If the input sign bit is known to be zero, or if none of the top bits
1711 // are demanded, turn this into an unsigned shift right.
Zhou Shenga4475572007-03-29 02:26:30 +00001712 if (RHSKnownZero[BitWidth-ShiftAmt-1] ||
Reid Spencer1791f232007-03-12 17:25:59 +00001713 (HighBits & ~DemandedMask) == HighBits) {
1714 // Perform the logical shift right.
1715 Value *NewVal = BinaryOperator::createLShr(
1716 I->getOperand(0), SA, I->getName());
1717 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1718 return UpdateValueUsesWith(I, NewVal);
1719 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1720 RHSKnownOne |= HighBits;
1721 }
1722 }
1723 break;
Nick Lewyckyd0b62a12008-03-06 06:48:30 +00001724 case Instruction::SRem:
1725 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1726 APInt RA = Rem->getValue();
1727 if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
1728 APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) | RA : ~RA;
1729 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1730 if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1731 LHSKnownZero, LHSKnownOne, Depth+1))
1732 return true;
1733
1734 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1735 LHSKnownZero |= ~LowBits;
1736 else if (LHSKnownOne[BitWidth-1])
1737 LHSKnownOne |= ~LowBits;
1738
1739 KnownZero |= LHSKnownZero & DemandedMask;
1740 KnownOne |= LHSKnownOne & DemandedMask;
1741
1742 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1743 }
1744 }
1745 break;
Dan Gohman72ec3f42008-04-28 17:02:21 +00001746 case Instruction::URem: {
Nick Lewyckyd0b62a12008-03-06 06:48:30 +00001747 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1748 APInt RA = Rem->getValue();
Dan Gohman72ec3f42008-04-28 17:02:21 +00001749 if (RA.isStrictlyPositive() && RA.isPowerOf2()) {
Nick Lewyckyd0b62a12008-03-06 06:48:30 +00001750 APInt LowBits = (RA - 1) | RA;
1751 APInt Mask2 = LowBits & DemandedMask;
1752 KnownZero |= ~LowBits & DemandedMask;
1753 if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1754 KnownZero, KnownOne, Depth+1))
1755 return true;
1756
1757 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
Dan Gohman72ec3f42008-04-28 17:02:21 +00001758 break;
Nick Lewyckyd0b62a12008-03-06 06:48:30 +00001759 }
Nick Lewyckyd0b62a12008-03-06 06:48:30 +00001760 }
Dan Gohman72ec3f42008-04-28 17:02:21 +00001761
1762 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1763 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1764 ComputeMaskedBits(I->getOperand(0), AllOnes,
1765 KnownZero2, KnownOne2, Depth+1);
1766 uint32_t Leaders = KnownZero2.countLeadingOnes();
1767 APInt HighZeros = APInt::getHighBitsSet(BitWidth, Leaders);
1768 if (SimplifyDemandedBits(I->getOperand(1), ~HighZeros,
1769 KnownZero2, KnownOne2, Depth+1))
1770 return true;
1771
1772 Leaders = std::max(Leaders,
1773 KnownZero2.countLeadingOnes());
1774 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyd0b62a12008-03-06 06:48:30 +00001775 break;
Reid Spencer1791f232007-03-12 17:25:59 +00001776 }
Dan Gohman72ec3f42008-04-28 17:02:21 +00001777 }
Reid Spencer1791f232007-03-12 17:25:59 +00001778
1779 // If the client is only demanding bits that we know, return the known
1780 // constant.
1781 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1782 return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
1783 return false;
1784}
1785
Chris Lattner2deeaea2006-10-05 06:55:50 +00001786
1787/// SimplifyDemandedVectorElts - The specified value producecs a vector with
1788/// 64 or fewer elements. DemandedElts contains the set of elements that are
1789/// actually used by the caller. This method analyzes which elements of the
1790/// operand are undef and returns that information in UndefElts.
1791///
1792/// If the information about demanded elements can be used to simplify the
1793/// operation, the operation is simplified, then the resultant value is
1794/// returned. This returns null if no change was made.
1795Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1796 uint64_t &UndefElts,
1797 unsigned Depth) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00001798 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner2deeaea2006-10-05 06:55:50 +00001799 assert(VWidth <= 64 && "Vector too wide to analyze!");
1800 uint64_t EltMask = ~0ULL >> (64-VWidth);
1801 assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1802 "Invalid DemandedElts!");
1803
1804 if (isa<UndefValue>(V)) {
1805 // If the entire vector is undefined, just return this info.
1806 UndefElts = EltMask;
1807 return 0;
1808 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1809 UndefElts = EltMask;
1810 return UndefValue::get(V->getType());
1811 }
1812
1813 UndefElts = 0;
Reid Spencerd84d35b2007-02-15 02:26:10 +00001814 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1815 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner2deeaea2006-10-05 06:55:50 +00001816 Constant *Undef = UndefValue::get(EltTy);
1817
1818 std::vector<Constant*> Elts;
1819 for (unsigned i = 0; i != VWidth; ++i)
1820 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1821 Elts.push_back(Undef);
1822 UndefElts |= (1ULL << i);
1823 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1824 Elts.push_back(Undef);
1825 UndefElts |= (1ULL << i);
1826 } else { // Otherwise, defined.
1827 Elts.push_back(CP->getOperand(i));
1828 }
1829
1830 // If we changed the constant, return it.
Reid Spencerd84d35b2007-02-15 02:26:10 +00001831 Constant *NewCP = ConstantVector::get(Elts);
Chris Lattner2deeaea2006-10-05 06:55:50 +00001832 return NewCP != CP ? NewCP : 0;
1833 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00001834 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner2deeaea2006-10-05 06:55:50 +00001835 // set to undef.
Reid Spencerd84d35b2007-02-15 02:26:10 +00001836 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner2deeaea2006-10-05 06:55:50 +00001837 Constant *Zero = Constant::getNullValue(EltTy);
1838 Constant *Undef = UndefValue::get(EltTy);
1839 std::vector<Constant*> Elts;
1840 for (unsigned i = 0; i != VWidth; ++i)
1841 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1842 UndefElts = DemandedElts ^ EltMask;
Reid Spencerd84d35b2007-02-15 02:26:10 +00001843 return ConstantVector::get(Elts);
Chris Lattner2deeaea2006-10-05 06:55:50 +00001844 }
1845
1846 if (!V->hasOneUse()) { // Other users may use these bits.
1847 if (Depth != 0) { // Not at the root.
1848 // TODO: Just compute the UndefElts information recursively.
1849 return false;
1850 }
1851 return false;
1852 } else if (Depth == 10) { // Limit search depth.
1853 return false;
1854 }
1855
1856 Instruction *I = dyn_cast<Instruction>(V);
1857 if (!I) return false; // Only analyze instructions.
1858
1859 bool MadeChange = false;
1860 uint64_t UndefElts2;
1861 Value *TmpV;
1862 switch (I->getOpcode()) {
1863 default: break;
1864
1865 case Instruction::InsertElement: {
1866 // If this is a variable index, we don't know which element it overwrites.
1867 // demand exactly the same input as we produce.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001868 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner2deeaea2006-10-05 06:55:50 +00001869 if (Idx == 0) {
1870 // Note that we can't propagate undef elt info, because we don't know
1871 // which elt is getting updated.
1872 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1873 UndefElts2, Depth+1);
1874 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1875 break;
1876 }
1877
1878 // If this is inserting an element that isn't demanded, remove this
1879 // insertelement.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001880 unsigned IdxNo = Idx->getZExtValue();
Chris Lattner2deeaea2006-10-05 06:55:50 +00001881 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1882 return AddSoonDeadInstToWorklist(*I, 0);
1883
1884 // Otherwise, the element inserted overwrites whatever was there, so the
1885 // input demanded set is simpler than the output set.
1886 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1887 DemandedElts & ~(1ULL << IdxNo),
1888 UndefElts, Depth+1);
1889 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1890
1891 // The inserted element is defined.
1892 UndefElts |= 1ULL << IdxNo;
1893 break;
1894 }
Chris Lattnerb37fb6a2007-04-14 22:29:23 +00001895 case Instruction::BitCast: {
Dan Gohman06c60b62007-07-16 14:29:03 +00001896 // Vector->vector casts only.
Chris Lattnerb37fb6a2007-04-14 22:29:23 +00001897 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1898 if (!VTy) break;
1899 unsigned InVWidth = VTy->getNumElements();
1900 uint64_t InputDemandedElts = 0;
1901 unsigned Ratio;
1902
1903 if (VWidth == InVWidth) {
Dan Gohman06c60b62007-07-16 14:29:03 +00001904 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
Chris Lattnerb37fb6a2007-04-14 22:29:23 +00001905 // elements as are demanded of us.
1906 Ratio = 1;
1907 InputDemandedElts = DemandedElts;
1908 } else if (VWidth > InVWidth) {
1909 // Untested so far.
1910 break;
1911
1912 // If there are more elements in the result than there are in the source,
1913 // then an input element is live if any of the corresponding output
1914 // elements are live.
1915 Ratio = VWidth/InVWidth;
1916 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1917 if (DemandedElts & (1ULL << OutIdx))
1918 InputDemandedElts |= 1ULL << (OutIdx/Ratio);
1919 }
1920 } else {
1921 // Untested so far.
1922 break;
1923
1924 // If there are more elements in the source than there are in the result,
1925 // then an input element is live if the corresponding output element is
1926 // live.
1927 Ratio = InVWidth/VWidth;
1928 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1929 if (DemandedElts & (1ULL << InIdx/Ratio))
1930 InputDemandedElts |= 1ULL << InIdx;
1931 }
Chris Lattner2deeaea2006-10-05 06:55:50 +00001932
Chris Lattnerb37fb6a2007-04-14 22:29:23 +00001933 // div/rem demand all inputs, because they don't want divide by zero.
1934 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1935 UndefElts2, Depth+1);
1936 if (TmpV) {
1937 I->setOperand(0, TmpV);
1938 MadeChange = true;
1939 }
1940
1941 UndefElts = UndefElts2;
1942 if (VWidth > InVWidth) {
1943 assert(0 && "Unimp");
1944 // If there are more elements in the result than there are in the source,
1945 // then an output element is undef if the corresponding input element is
1946 // undef.
1947 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1948 if (UndefElts2 & (1ULL << (OutIdx/Ratio)))
1949 UndefElts |= 1ULL << OutIdx;
1950 } else if (VWidth < InVWidth) {
1951 assert(0 && "Unimp");
1952 // If there are more elements in the source than there are in the result,
1953 // then a result element is undef if all of the corresponding input
1954 // elements are undef.
1955 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1956 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1957 if ((UndefElts2 & (1ULL << InIdx)) == 0) // Not undef?
1958 UndefElts &= ~(1ULL << (InIdx/Ratio)); // Clear undef bit.
1959 }
1960 break;
1961 }
Chris Lattner2deeaea2006-10-05 06:55:50 +00001962 case Instruction::And:
1963 case Instruction::Or:
1964 case Instruction::Xor:
1965 case Instruction::Add:
1966 case Instruction::Sub:
1967 case Instruction::Mul:
1968 // div/rem demand all inputs, because they don't want divide by zero.
1969 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1970 UndefElts, Depth+1);
1971 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1972 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1973 UndefElts2, Depth+1);
1974 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1975
1976 // Output elements are undefined if both are undefined. Consider things
1977 // like undef&0. The result is known zero, not undef.
1978 UndefElts &= UndefElts2;
1979 break;
1980
1981 case Instruction::Call: {
1982 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1983 if (!II) break;
1984 switch (II->getIntrinsicID()) {
1985 default: break;
1986
1987 // Binary vector operations that work column-wise. A dest element is a
1988 // function of the corresponding input elements from the two inputs.
1989 case Intrinsic::x86_sse_sub_ss:
1990 case Intrinsic::x86_sse_mul_ss:
1991 case Intrinsic::x86_sse_min_ss:
1992 case Intrinsic::x86_sse_max_ss:
1993 case Intrinsic::x86_sse2_sub_sd:
1994 case Intrinsic::x86_sse2_mul_sd:
1995 case Intrinsic::x86_sse2_min_sd:
1996 case Intrinsic::x86_sse2_max_sd:
1997 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1998 UndefElts, Depth+1);
1999 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
2000 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
2001 UndefElts2, Depth+1);
2002 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
2003
2004 // If only the low elt is demanded and this is a scalarizable intrinsic,
2005 // scalarize it now.
2006 if (DemandedElts == 1) {
2007 switch (II->getIntrinsicID()) {
2008 default: break;
2009 case Intrinsic::x86_sse_sub_ss:
2010 case Intrinsic::x86_sse_mul_ss:
2011 case Intrinsic::x86_sse2_sub_sd:
2012 case Intrinsic::x86_sse2_mul_sd:
2013 // TODO: Lower MIN/MAX/ABS/etc
2014 Value *LHS = II->getOperand(1);
2015 Value *RHS = II->getOperand(2);
2016 // Extract the element as scalars.
2017 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
2018 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
2019
2020 switch (II->getIntrinsicID()) {
2021 default: assert(0 && "Case stmts out of sync!");
2022 case Intrinsic::x86_sse_sub_ss:
2023 case Intrinsic::x86_sse2_sub_sd:
2024 TmpV = InsertNewInstBefore(BinaryOperator::createSub(LHS, RHS,
2025 II->getName()), *II);
2026 break;
2027 case Intrinsic::x86_sse_mul_ss:
2028 case Intrinsic::x86_sse2_mul_sd:
2029 TmpV = InsertNewInstBefore(BinaryOperator::createMul(LHS, RHS,
2030 II->getName()), *II);
2031 break;
2032 }
2033
2034 Instruction *New =
Gabor Greife9ecc682008-04-06 20:25:17 +00002035 InsertElementInst::Create(UndefValue::get(II->getType()), TmpV, 0U,
2036 II->getName());
Chris Lattner2deeaea2006-10-05 06:55:50 +00002037 InsertNewInstBefore(New, *II);
2038 AddSoonDeadInstToWorklist(*II, 0);
2039 return New;
2040 }
2041 }
2042
2043 // Output elements are undefined if both are undefined. Consider things
2044 // like undef&0. The result is known zero, not undef.
2045 UndefElts &= UndefElts2;
2046 break;
2047 }
2048 break;
2049 }
2050 }
2051 return MadeChange ? I : 0;
2052}
2053
Nick Lewycky0c5c4792007-09-06 02:40:25 +00002054/// @returns true if the specified compare predicate is
Reid Spencer266e42b2006-12-23 06:05:41 +00002055/// true when both operands are equal...
Nick Lewycky0c5c4792007-09-06 02:40:25 +00002056/// @brief Determine if the icmp Predicate is true when both operands are equal
2057static bool isTrueWhenEqual(ICmpInst::Predicate pred) {
Reid Spencer266e42b2006-12-23 06:05:41 +00002058 return pred == ICmpInst::ICMP_EQ || pred == ICmpInst::ICMP_UGE ||
2059 pred == ICmpInst::ICMP_SGE || pred == ICmpInst::ICMP_ULE ||
2060 pred == ICmpInst::ICMP_SLE;
2061}
2062
Nick Lewycky0c5c4792007-09-06 02:40:25 +00002063/// @returns true if the specified compare instruction is
2064/// true when both operands are equal...
2065/// @brief Determine if the ICmpInst returns true when both operands are equal
2066static bool isTrueWhenEqual(ICmpInst &ICI) {
2067 return isTrueWhenEqual(ICI.getPredicate());
2068}
2069
Chris Lattnerb8b97502003-08-13 19:01:45 +00002070/// AssociativeOpt - Perform an optimization on an associative operator. This
2071/// function is designed to check a chain of associative operators for a
2072/// potential to apply a certain optimization. Since the optimization may be
2073/// applicable if the expression was reassociated, this checks the chain, then
2074/// reassociates the expression as necessary to expose the optimization
2075/// opportunity. This makes use of a special Functor, which must define
2076/// 'shouldApply' and 'apply' methods.
2077///
2078template<typename Functor>
2079Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
2080 unsigned Opcode = Root.getOpcode();
2081 Value *LHS = Root.getOperand(0);
2082
2083 // Quick check, see if the immediate LHS matches...
2084 if (F.shouldApply(LHS))
2085 return F.apply(Root);
2086
2087 // Otherwise, if the LHS is not of the same opcode as the root, return.
2088 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002089 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +00002090 // Should we apply this transform to the RHS?
2091 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
2092
2093 // If not to the RHS, check to see if we should apply to the LHS...
2094 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
2095 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
2096 ShouldApply = true;
2097 }
2098
2099 // If the functor wants to apply the optimization to the RHS of LHSI,
2100 // reassociate the expression from ((? op A) op B) to (? op (A op B))
2101 if (ShouldApply) {
2102 BasicBlock *BB = Root.getParent();
Misha Brukmanb1c93172005-04-21 23:48:37 +00002103
Chris Lattnerb8b97502003-08-13 19:01:45 +00002104 // Now all of the instructions are in the current basic block, go ahead
2105 // and perform the reassociation.
2106 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
2107
2108 // First move the selected RHS to the LHS of the root...
2109 Root.setOperand(0, LHSI->getOperand(1));
2110
2111 // Make what used to be the LHS of the root be the user of the root...
2112 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner284d3b02004-04-16 18:08:07 +00002113 if (&Root == TmpLHSI) {
Chris Lattner8953b902004-04-05 02:10:19 +00002114 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
2115 return 0;
2116 }
Chris Lattner284d3b02004-04-16 18:08:07 +00002117 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattnerb8b97502003-08-13 19:01:45 +00002118 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner284d3b02004-04-16 18:08:07 +00002119 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
2120 BasicBlock::iterator ARI = &Root; ++ARI;
2121 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
2122 ARI = Root;
Chris Lattnerb8b97502003-08-13 19:01:45 +00002123
2124 // Now propagate the ExtraOperand down the chain of instructions until we
2125 // get to LHSI.
2126 while (TmpLHSI != LHSI) {
2127 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner284d3b02004-04-16 18:08:07 +00002128 // Move the instruction to immediately before the chain we are
2129 // constructing to avoid breaking dominance properties.
2130 NextLHSI->getParent()->getInstList().remove(NextLHSI);
2131 BB->getInstList().insert(ARI, NextLHSI);
2132 ARI = NextLHSI;
2133
Chris Lattnerb8b97502003-08-13 19:01:45 +00002134 Value *NextOp = NextLHSI->getOperand(1);
2135 NextLHSI->setOperand(1, ExtraOperand);
2136 TmpLHSI = NextLHSI;
2137 ExtraOperand = NextOp;
2138 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002139
Chris Lattnerb8b97502003-08-13 19:01:45 +00002140 // Now that the instructions are reassociated, have the functor perform
2141 // the transformation...
2142 return F.apply(Root);
2143 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002144
Chris Lattnerb8b97502003-08-13 19:01:45 +00002145 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
2146 }
2147 return 0;
2148}
2149
2150
2151// AddRHS - Implements: X + X --> X << 1
2152struct AddRHS {
2153 Value *RHS;
2154 AddRHS(Value *rhs) : RHS(rhs) {}
2155 bool shouldApply(Value *LHS) const { return LHS == RHS; }
2156 Instruction *apply(BinaryOperator &Add) const {
Reid Spencer0d5f9232007-02-02 14:08:20 +00002157 return BinaryOperator::createShl(Add.getOperand(0),
Reid Spencer2341c222007-02-02 02:16:23 +00002158 ConstantInt::get(Add.getType(), 1));
Chris Lattnerb8b97502003-08-13 19:01:45 +00002159 }
2160};
2161
2162// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
2163// iff C1&C2 == 0
2164struct AddMaskingAnd {
2165 Constant *C2;
2166 AddMaskingAnd(Constant *c) : C2(c) {}
2167 bool shouldApply(Value *LHS) const {
Chris Lattnerd4252a72004-07-30 07:50:03 +00002168 ConstantInt *C1;
Misha Brukmanb1c93172005-04-21 23:48:37 +00002169 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattnerd4252a72004-07-30 07:50:03 +00002170 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattnerb8b97502003-08-13 19:01:45 +00002171 }
2172 Instruction *apply(BinaryOperator &Add) const {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002173 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattnerb8b97502003-08-13 19:01:45 +00002174 }
2175};
2176
Chris Lattner86102b82005-01-01 16:22:27 +00002177static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner183b3362004-04-09 19:05:30 +00002178 InstCombiner *IC) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002179 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Chris Lattner86102b82005-01-01 16:22:27 +00002180 if (Constant *SOC = dyn_cast<Constant>(SO))
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002181 return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
Misha Brukmanb1c93172005-04-21 23:48:37 +00002182
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002183 return IC->InsertNewInstBefore(CastInst::create(
2184 CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
Chris Lattner86102b82005-01-01 16:22:27 +00002185 }
2186
Chris Lattner183b3362004-04-09 19:05:30 +00002187 // Figure out if the constant is the left or the right argument.
Chris Lattner86102b82005-01-01 16:22:27 +00002188 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
2189 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattnerb8b97502003-08-13 19:01:45 +00002190
Chris Lattner183b3362004-04-09 19:05:30 +00002191 if (Constant *SOC = dyn_cast<Constant>(SO)) {
2192 if (ConstIsRHS)
Chris Lattner86102b82005-01-01 16:22:27 +00002193 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
2194 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner183b3362004-04-09 19:05:30 +00002195 }
2196
2197 Value *Op0 = SO, *Op1 = ConstOperand;
2198 if (!ConstIsRHS)
2199 std::swap(Op0, Op1);
2200 Instruction *New;
Chris Lattner86102b82005-01-01 16:22:27 +00002201 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
2202 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Reid Spencer266e42b2006-12-23 06:05:41 +00002203 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2204 New = CmpInst::create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
2205 SO->getName()+".cmp");
Chris Lattnerf9d96652004-04-10 19:15:56 +00002206 else {
Chris Lattner183b3362004-04-09 19:05:30 +00002207 assert(0 && "Unknown binary instruction type!");
Chris Lattnerf9d96652004-04-10 19:15:56 +00002208 abort();
2209 }
Chris Lattner86102b82005-01-01 16:22:27 +00002210 return IC->InsertNewInstBefore(New, I);
2211}
2212
2213// FoldOpIntoSelect - Given an instruction with a select as one operand and a
2214// constant as the other operand, try to fold the binary operator into the
2215// select arguments. This also works for Cast instructions, which obviously do
2216// not have a second operand.
2217static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
2218 InstCombiner *IC) {
2219 // Don't modify shared select instructions
2220 if (!SI->hasOneUse()) return 0;
2221 Value *TV = SI->getOperand(1);
2222 Value *FV = SI->getOperand(2);
2223
2224 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner374e6592005-04-21 05:43:13 +00002225 // Bool selects with constant operands can be folded to logical ops.
Reid Spencer542964f2007-01-11 18:21:29 +00002226 if (SI->getType() == Type::Int1Ty) return 0;
Chris Lattner374e6592005-04-21 05:43:13 +00002227
Chris Lattner86102b82005-01-01 16:22:27 +00002228 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
2229 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
2230
Gabor Greife9ecc682008-04-06 20:25:17 +00002231 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
2232 SelectFalseVal);
Chris Lattner86102b82005-01-01 16:22:27 +00002233 }
2234 return 0;
Chris Lattner183b3362004-04-09 19:05:30 +00002235}
2236
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002237
2238/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
2239/// node as operand #0, see if we can fold the instruction into the PHI (which
2240/// is only possible if all operands to the PHI are constants).
2241Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
2242 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00002243 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner04689872006-09-09 22:02:56 +00002244 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002245
Chris Lattner04689872006-09-09 22:02:56 +00002246 // Check to see if all of the operands of the PHI are constants. If there is
2247 // one non-constant value, remember the BB it is. If there is more than one
Chris Lattnerc4d8e7e2007-02-24 01:03:45 +00002248 // or if *it* is a PHI, bail out.
Chris Lattner04689872006-09-09 22:02:56 +00002249 BasicBlock *NonConstBB = 0;
2250 for (unsigned i = 0; i != NumPHIValues; ++i)
2251 if (!isa<Constant>(PN->getIncomingValue(i))) {
2252 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerc4d8e7e2007-02-24 01:03:45 +00002253 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner04689872006-09-09 22:02:56 +00002254 NonConstBB = PN->getIncomingBlock(i);
2255
2256 // If the incoming non-constant value is in I's block, we have an infinite
2257 // loop.
2258 if (NonConstBB == I.getParent())
2259 return 0;
2260 }
2261
2262 // If there is exactly one non-constant value, we can insert a copy of the
2263 // operation in that block. However, if this is a critical edge, we would be
2264 // inserting the computation one some other paths (e.g. inside a loop). Only
2265 // do this if the pred block is unconditionally branching into the phi block.
2266 if (NonConstBB) {
2267 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
2268 if (!BI || !BI->isUnconditional()) return 0;
2269 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002270
2271 // Okay, we can do the transformation: create the new PHI node.
Gabor Greife9ecc682008-04-06 20:25:17 +00002272 PHINode *NewPN = PHINode::Create(I.getType(), "");
Chris Lattnerd8e20182005-01-29 00:39:08 +00002273 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002274 InsertNewInstBefore(NewPN, *PN);
Chris Lattner6e0123b2007-02-11 01:23:03 +00002275 NewPN->takeName(PN);
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002276
2277 // Next, add all of the operands to the PHI.
2278 if (I.getNumOperands() == 2) {
2279 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattner7515cab2004-11-14 19:13:23 +00002280 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnerf0da7972007-08-05 08:47:58 +00002281 Value *InV = 0;
Chris Lattner04689872006-09-09 22:02:56 +00002282 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer266e42b2006-12-23 06:05:41 +00002283 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2284 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
2285 else
2286 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner04689872006-09-09 22:02:56 +00002287 } else {
2288 assert(PN->getIncomingBlock(i) == NonConstBB);
2289 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
2290 InV = BinaryOperator::create(BO->getOpcode(),
2291 PN->getIncomingValue(i), C, "phitmp",
2292 NonConstBB->getTerminator());
Reid Spencer266e42b2006-12-23 06:05:41 +00002293 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2294 InV = CmpInst::create(CI->getOpcode(),
2295 CI->getPredicate(),
2296 PN->getIncomingValue(i), C, "phitmp",
2297 NonConstBB->getTerminator());
Chris Lattner04689872006-09-09 22:02:56 +00002298 else
2299 assert(0 && "Unknown binop!");
2300
Chris Lattnerb15e2b12007-03-02 21:28:56 +00002301 AddToWorkList(cast<Instruction>(InV));
Chris Lattner04689872006-09-09 22:02:56 +00002302 }
2303 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002304 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002305 } else {
2306 CastInst *CI = cast<CastInst>(&I);
2307 const Type *RetTy = CI->getType();
Chris Lattner7515cab2004-11-14 19:13:23 +00002308 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner04689872006-09-09 22:02:56 +00002309 Value *InV;
2310 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002311 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner04689872006-09-09 22:02:56 +00002312 } else {
2313 assert(PN->getIncomingBlock(i) == NonConstBB);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002314 InV = CastInst::create(CI->getOpcode(), PN->getIncomingValue(i),
2315 I.getType(), "phitmp",
2316 NonConstBB->getTerminator());
Chris Lattnerb15e2b12007-03-02 21:28:56 +00002317 AddToWorkList(cast<Instruction>(InV));
Chris Lattner04689872006-09-09 22:02:56 +00002318 }
2319 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002320 }
2321 }
2322 return ReplaceInstUsesWith(I, NewPN);
2323}
2324
Chris Lattner17819d92008-01-29 06:52:45 +00002325
2326/// CannotBeNegativeZero - Return true if we can prove that the specified FP
2327/// value is never equal to -0.0.
2328///
2329/// Note that this function will need to be revisited when we support nondefault
2330/// rounding modes!
2331///
2332static bool CannotBeNegativeZero(const Value *V) {
2333 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
2334 return !CFP->getValueAPF().isNegZero();
2335
2336 // (add x, 0.0) is guaranteed to return +0.0, not -0.0.
2337 if (const Instruction *I = dyn_cast<Instruction>(V)) {
2338 if (I->getOpcode() == Instruction::Add &&
2339 isa<ConstantFP>(I->getOperand(1)) &&
2340 cast<ConstantFP>(I->getOperand(1))->isNullValue())
2341 return true;
2342
2343 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
2344 if (II->getIntrinsicID() == Intrinsic::sqrt)
2345 return CannotBeNegativeZero(II->getOperand(1));
2346
2347 if (const CallInst *CI = dyn_cast<CallInst>(I))
2348 if (const Function *F = CI->getCalledFunction()) {
2349 if (F->isDeclaration()) {
2350 switch (F->getNameLen()) {
2351 case 3: // abs(x) != -0.0
2352 if (!strcmp(F->getNameStart(), "abs")) return true;
2353 break;
2354 case 4: // abs[lf](x) != -0.0
2355 if (!strcmp(F->getNameStart(), "absf")) return true;
2356 if (!strcmp(F->getNameStart(), "absl")) return true;
2357 break;
2358 }
2359 }
2360 }
2361 }
2362
2363 return false;
2364}
2365
2366
Chris Lattner113f4f42002-06-25 16:13:24 +00002367Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002368 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00002369 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattner9fa53de2002-05-06 16:49:18 +00002370
Chris Lattnercf4a9962004-04-10 22:01:55 +00002371 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattner81a7a232004-10-16 18:11:37 +00002372 // X + undef -> undef
2373 if (isa<UndefValue>(RHS))
2374 return ReplaceInstUsesWith(I, RHS);
2375
Chris Lattnercf4a9962004-04-10 22:01:55 +00002376 // X + 0 --> X
Chris Lattner7a002fe2006-12-02 00:13:08 +00002377 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
Chris Lattner7fde91e2005-10-17 17:56:38 +00002378 if (RHSC->isNullValue())
2379 return ReplaceInstUsesWith(I, LHS);
Chris Lattnerda1b1522005-10-17 20:18:38 +00002380 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Dale Johannesen98d3a082007-09-14 22:26:36 +00002381 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
2382 (I.getType())->getValueAPF()))
Chris Lattnerda1b1522005-10-17 20:18:38 +00002383 return ReplaceInstUsesWith(I, LHS);
Chris Lattner7fde91e2005-10-17 17:56:38 +00002384 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002385
Chris Lattnercf4a9962004-04-10 22:01:55 +00002386 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattner6e2c15c2006-11-09 05:12:27 +00002387 // X + (signbit) --> X ^ signbit
Zhou Sheng150f3bb2007-04-01 17:13:37 +00002388 const APInt& Val = CI->getValue();
Zhou Sheng56cda952007-04-02 08:20:41 +00002389 uint32_t BitWidth = Val.getBitWidth();
Reid Spencer959a21d2007-03-23 21:24:59 +00002390 if (Val == APInt::getSignBit(BitWidth))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002391 return BinaryOperator::createXor(LHS, RHS);
Chris Lattner6e2c15c2006-11-09 05:12:27 +00002392
2393 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2394 // (X & 254)+1 -> (X&254)|1
Reid Spencer959a21d2007-03-23 21:24:59 +00002395 if (!isa<VectorType>(I.getType())) {
2396 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2397 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
2398 KnownZero, KnownOne))
2399 return &I;
2400 }
Chris Lattnercf4a9962004-04-10 22:01:55 +00002401 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002402
2403 if (isa<PHINode>(LHS))
2404 if (Instruction *NV = FoldOpIntoPhi(I))
2405 return NV;
Chris Lattner0b3557f2005-09-24 23:43:33 +00002406
Chris Lattner330628a2006-01-06 17:59:59 +00002407 ConstantInt *XorRHS = 0;
2408 Value *XorLHS = 0;
Chris Lattner4284f642007-01-30 22:32:46 +00002409 if (isa<ConstantInt>(RHSC) &&
2410 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Zhou Sheng56cda952007-04-02 08:20:41 +00002411 uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
Zhou Sheng150f3bb2007-04-01 17:13:37 +00002412 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner0b3557f2005-09-24 23:43:33 +00002413
Zhou Sheng56cda952007-04-02 08:20:41 +00002414 uint32_t Size = TySizeBits / 2;
Reid Spencer959a21d2007-03-23 21:24:59 +00002415 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2416 APInt CFF80Val(-C0080Val);
Chris Lattner0b3557f2005-09-24 23:43:33 +00002417 do {
2418 if (TySizeBits > Size) {
Chris Lattner0b3557f2005-09-24 23:43:33 +00002419 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2420 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer959a21d2007-03-23 21:24:59 +00002421 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2422 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner0b3557f2005-09-24 23:43:33 +00002423 // This is a sign extend if the top bits are known zero.
Zhou Shengb3a80b12007-03-29 08:15:12 +00002424 if (!MaskedValueIsZero(XorLHS,
2425 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner0b3557f2005-09-24 23:43:33 +00002426 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer959a21d2007-03-23 21:24:59 +00002427 break;
Chris Lattner0b3557f2005-09-24 23:43:33 +00002428 }
2429 }
2430 Size >>= 1;
Reid Spencer959a21d2007-03-23 21:24:59 +00002431 C0080Val = APIntOps::lshr(C0080Val, Size);
2432 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2433 } while (Size >= 1);
Chris Lattner0b3557f2005-09-24 23:43:33 +00002434
Reid Spencera5c18bf2007-03-28 01:36:16 +00002435 // FIXME: This shouldn't be necessary. When the backends can handle types
2436 // with funny bit widths then this whole cascade of if statements should
2437 // be removed. It is just here to get the size of the "middle" type back
2438 // up to something that the back ends can handle.
2439 const Type *MiddleType = 0;
2440 switch (Size) {
2441 default: break;
2442 case 32: MiddleType = Type::Int32Ty; break;
2443 case 16: MiddleType = Type::Int16Ty; break;
2444 case 8: MiddleType = Type::Int8Ty; break;
2445 }
2446 if (MiddleType) {
Reid Spencerbb65ebf2006-12-12 23:36:14 +00002447 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
Chris Lattner0b3557f2005-09-24 23:43:33 +00002448 InsertNewInstBefore(NewTrunc, I);
Reid Spencera5c18bf2007-03-28 01:36:16 +00002449 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner0b3557f2005-09-24 23:43:33 +00002450 }
2451 }
Chris Lattnercf4a9962004-04-10 22:01:55 +00002452 }
Chris Lattner9fa53de2002-05-06 16:49:18 +00002453
Chris Lattnerb8b97502003-08-13 19:01:45 +00002454 // X + X --> X << 1
Chris Lattner03c49532007-01-15 02:27:26 +00002455 if (I.getType()->isInteger() && I.getType() != Type::Int1Ty) {
Chris Lattnerb8b97502003-08-13 19:01:45 +00002456 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner47060462005-04-07 17:14:51 +00002457
2458 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2459 if (RHSI->getOpcode() == Instruction::Sub)
2460 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2461 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2462 }
2463 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2464 if (LHSI->getOpcode() == Instruction::Sub)
2465 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2466 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2467 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00002468 }
Chris Lattnerede3fe02003-08-13 04:18:28 +00002469
Chris Lattner147e9752002-05-08 22:46:53 +00002470 // -A + B --> B - A
Chris Lattnercc226012008-02-17 21:03:36 +00002471 // -A + -B --> -(A + B)
2472 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattner1e3c5012008-02-18 17:50:16 +00002473 if (LHS->getType()->isIntOrIntVector()) {
2474 if (Value *RHSV = dyn_castNegVal(RHS)) {
2475 Instruction *NewAdd = BinaryOperator::createAdd(LHSV, RHSV, "sum");
2476 InsertNewInstBefore(NewAdd, I);
2477 return BinaryOperator::createNeg(NewAdd);
2478 }
Chris Lattnercc226012008-02-17 21:03:36 +00002479 }
2480
2481 return BinaryOperator::createSub(RHS, LHSV);
2482 }
Chris Lattner9fa53de2002-05-06 16:49:18 +00002483
2484 // A + -B --> A - B
Chris Lattnerbb74e222003-03-10 23:06:50 +00002485 if (!isa<Constant>(RHS))
2486 if (Value *V = dyn_castNegVal(RHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002487 return BinaryOperator::createSub(LHS, V);
Chris Lattner260ab202002-04-18 17:39:14 +00002488
Misha Brukmanb1c93172005-04-21 23:48:37 +00002489
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002490 ConstantInt *C2;
2491 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2492 if (X == RHS) // X*C + X --> X * (C+1)
2493 return BinaryOperator::createMul(RHS, AddOne(C2));
2494
2495 // X*C1 + X*C2 --> X * (C1+C2)
2496 ConstantInt *C1;
2497 if (X == dyn_castFoldableMul(RHS, C1))
Reid Spencer80263aa2007-03-25 05:33:51 +00002498 return BinaryOperator::createMul(X, Add(C1, C2));
Chris Lattner57c8d992003-02-18 19:57:07 +00002499 }
2500
2501 // X + X*C --> X * (C+1)
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002502 if (dyn_castFoldableMul(RHS, C2) == LHS)
2503 return BinaryOperator::createMul(LHS, AddOne(C2));
2504
Chris Lattner23eb8ec2007-01-05 02:17:46 +00002505 // X + ~X --> -1 since ~X = -X-1
Chris Lattner37338922007-06-15 06:23:19 +00002506 if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2507 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattner23eb8ec2007-01-05 02:17:46 +00002508
Chris Lattner57c8d992003-02-18 19:57:07 +00002509
Chris Lattnerb8b97502003-08-13 19:01:45 +00002510 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +00002511 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattner23eb8ec2007-01-05 02:17:46 +00002512 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2513 return R;
Chris Lattner7fb29e12003-03-11 00:12:48 +00002514
Nick Lewyckye6e3a7f2008-02-03 07:42:09 +00002515 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewyckyc7a4ba02008-02-03 08:19:11 +00002516 if (I.getType()->isIntOrIntVector()) {
Nick Lewyckye6e3a7f2008-02-03 07:42:09 +00002517 Value *W, *X, *Y, *Z;
2518 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2519 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2520 if (W != Y) {
2521 if (W == Z) {
Bill Wendlingd188e032008-02-26 10:53:30 +00002522 std::swap(Y, Z);
Nick Lewyckye6e3a7f2008-02-03 07:42:09 +00002523 } else if (Y == X) {
Bill Wendlingd188e032008-02-26 10:53:30 +00002524 std::swap(W, X);
2525 } else if (X == Z) {
Nick Lewyckye6e3a7f2008-02-03 07:42:09 +00002526 std::swap(Y, Z);
2527 std::swap(W, X);
2528 }
2529 }
2530
2531 if (W == Y) {
2532 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, Z,
2533 LHS->getName()), I);
2534 return BinaryOperator::createMul(W, NewAdd);
2535 }
2536 }
2537 }
2538
Chris Lattnerb9cde762003-10-02 15:11:26 +00002539 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner330628a2006-01-06 17:59:59 +00002540 Value *X = 0;
Reid Spencer80263aa2007-03-25 05:33:51 +00002541 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
2542 return BinaryOperator::createSub(SubOne(CRHS), X);
Chris Lattnerd4252a72004-07-30 07:50:03 +00002543
Chris Lattnerbff91d92004-10-08 05:07:56 +00002544 // (X & FF00) + xx00 -> (X+xx00) & FF00
2545 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Reid Spencer80263aa2007-03-25 05:33:51 +00002546 Constant *Anded = And(CRHS, C2);
Chris Lattnerbff91d92004-10-08 05:07:56 +00002547 if (Anded == CRHS) {
2548 // See if all bits from the first bit set in the Add RHS up are included
2549 // in the mask. First, get the rightmost bit.
Zhou Sheng150f3bb2007-04-01 17:13:37 +00002550 const APInt& AddRHSV = CRHS->getValue();
Chris Lattnerbff91d92004-10-08 05:07:56 +00002551
2552 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng150f3bb2007-04-01 17:13:37 +00002553 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerbff91d92004-10-08 05:07:56 +00002554
2555 // See if the and mask includes all of these bits.
Zhou Sheng150f3bb2007-04-01 17:13:37 +00002556 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanb1c93172005-04-21 23:48:37 +00002557
Chris Lattnerbff91d92004-10-08 05:07:56 +00002558 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2559 // Okay, the xform is safe. Insert the new add pronto.
2560 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
2561 LHS->getName()), I);
2562 return BinaryOperator::createAnd(NewAdd, C2);
2563 }
2564 }
2565 }
2566
Chris Lattnerd4252a72004-07-30 07:50:03 +00002567 // Try to fold constant add into select arguments.
2568 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner86102b82005-01-01 16:22:27 +00002569 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerd4252a72004-07-30 07:50:03 +00002570 return R;
Chris Lattnerb9cde762003-10-02 15:11:26 +00002571 }
2572
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002573 // add (cast *A to intptrtype) B ->
Chris Lattner16a51da2007-12-20 01:56:58 +00002574 // cast (GEP (cast *A to sbyte*) B) --> intptrtype
Andrew Lenharth4f339be2006-09-19 18:24:51 +00002575 {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002576 CastInst *CI = dyn_cast<CastInst>(LHS);
2577 Value *Other = RHS;
Andrew Lenharth4f339be2006-09-19 18:24:51 +00002578 if (!CI) {
2579 CI = dyn_cast<CastInst>(RHS);
2580 Other = LHS;
2581 }
Andrew Lenharth44cb67a2006-09-20 15:37:57 +00002582 if (CI && CI->getType()->isSized() &&
Reid Spencer8f166b02007-01-08 16:32:00 +00002583 (CI->getType()->getPrimitiveSizeInBits() ==
2584 TD->getIntPtrType()->getPrimitiveSizeInBits())
Andrew Lenharth44cb67a2006-09-20 15:37:57 +00002585 && isa<PointerType>(CI->getOperand(0)->getType())) {
Christopher Lambedf07882007-12-17 01:12:55 +00002586 unsigned AS =
2587 cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
Chris Lattner5a866122008-01-13 22:23:22 +00002588 Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2589 PointerType::get(Type::Int8Ty, AS), I);
Gabor Greife9ecc682008-04-06 20:25:17 +00002590 I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002591 return new PtrToIntInst(I2, CI->getType());
Andrew Lenharth4f339be2006-09-19 18:24:51 +00002592 }
2593 }
Christopher Lamb8b09a462007-12-18 09:34:41 +00002594
Chris Lattner16a51da2007-12-20 01:56:58 +00002595 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb8b09a462007-12-18 09:34:41 +00002596 {
2597 SelectInst *SI = dyn_cast<SelectInst>(LHS);
2598 Value *Other = RHS;
2599 if (!SI) {
2600 SI = dyn_cast<SelectInst>(RHS);
2601 Other = LHS;
2602 }
Chris Lattner16a51da2007-12-20 01:56:58 +00002603 if (SI && SI->hasOneUse()) {
Christopher Lamb8b09a462007-12-18 09:34:41 +00002604 Value *TV = SI->getTrueValue();
2605 Value *FV = SI->getFalseValue();
Chris Lattner16a51da2007-12-20 01:56:58 +00002606 Value *A, *N;
Christopher Lamb8b09a462007-12-18 09:34:41 +00002607
2608 // Can we fold the add into the argument of the select?
2609 // We check both true and false select arguments for a matching subtract.
Chris Lattner16a51da2007-12-20 01:56:58 +00002610 if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Value(A))) &&
2611 A == Other) // Fold the add into the true select value.
Gabor Greife9ecc682008-04-06 20:25:17 +00002612 return SelectInst::Create(SI->getCondition(), N, A);
Chris Lattner16a51da2007-12-20 01:56:58 +00002613 if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Value(A))) &&
2614 A == Other) // Fold the add into the false select value.
Gabor Greife9ecc682008-04-06 20:25:17 +00002615 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb8b09a462007-12-18 09:34:41 +00002616 }
2617 }
Chris Lattner17819d92008-01-29 06:52:45 +00002618
2619 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2620 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2621 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2622 return ReplaceInstUsesWith(I, LHS);
Andrew Lenharth4f339be2006-09-19 18:24:51 +00002623
Chris Lattner113f4f42002-06-25 16:13:24 +00002624 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00002625}
2626
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00002627// isSignBit - Return true if the value represented by the constant only has the
2628// highest order bit set.
2629static bool isSignBit(ConstantInt *CI) {
Zhou Sheng56cda952007-04-02 08:20:41 +00002630 uint32_t NumBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencer450434e2007-03-19 20:58:18 +00002631 return CI->getValue() == APInt::getSignBit(NumBits);
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00002632}
2633
Chris Lattner113f4f42002-06-25 16:13:24 +00002634Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00002635 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002636
Chris Lattnere6794492002-08-12 21:17:25 +00002637 if (Op0 == Op1) // sub X, X -> 0
2638 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner260ab202002-04-18 17:39:14 +00002639
Chris Lattnere6794492002-08-12 21:17:25 +00002640 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattnerbb74e222003-03-10 23:06:50 +00002641 if (Value *V = dyn_castNegVal(Op1))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002642 return BinaryOperator::createAdd(Op0, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +00002643
Chris Lattner81a7a232004-10-16 18:11:37 +00002644 if (isa<UndefValue>(Op0))
2645 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2646 if (isa<UndefValue>(Op1))
2647 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2648
Chris Lattner8f2f5982003-11-05 01:06:05 +00002649 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2650 // Replace (-1 - A) with (~A)...
Chris Lattner3082c5a2003-02-18 19:28:33 +00002651 if (C->isAllOnesValue())
2652 return BinaryOperator::createNot(Op1);
Chris Lattnerad3c4952002-05-09 01:29:19 +00002653
Chris Lattner8f2f5982003-11-05 01:06:05 +00002654 // C - ~X == X + (1+C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00002655 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00002656 if (match(Op1, m_Not(m_Value(X))))
Reid Spencer80263aa2007-03-25 05:33:51 +00002657 return BinaryOperator::createAdd(X, AddOne(C));
2658
Chris Lattner27df1db2007-01-15 07:02:54 +00002659 // -(X >>u 31) -> (X >>s 31)
2660 // -(X >>s 31) -> (X >>u 31)
Zhou Shengfd28a332007-03-30 17:20:39 +00002661 if (C->isZero()) {
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +00002662 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Reid Spencerfdff9382006-11-08 06:47:33 +00002663 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002664 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner92295c52004-03-12 23:53:13 +00002665 // Check to see if we are shifting out everything but the sign bit.
Zhou Shengfd28a332007-03-30 17:20:39 +00002666 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencere0fc4df2006-10-20 07:07:24 +00002667 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerfdff9382006-11-08 06:47:33 +00002668 // Ok, the transformation is safe. Insert AShr.
Reid Spencer2341c222007-02-02 02:16:23 +00002669 return BinaryOperator::create(Instruction::AShr,
2670 SI->getOperand(0), CU, SI->getName());
Chris Lattner92295c52004-03-12 23:53:13 +00002671 }
2672 }
Reid Spencerfdff9382006-11-08 06:47:33 +00002673 }
2674 else if (SI->getOpcode() == Instruction::AShr) {
2675 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2676 // Check to see if we are shifting out everything but the sign bit.
Zhou Shengfd28a332007-03-30 17:20:39 +00002677 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerfdff9382006-11-08 06:47:33 +00002678 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc635f472006-12-31 05:48:39 +00002679 // Ok, the transformation is safe. Insert LShr.
Reid Spencer0d5f9232007-02-02 14:08:20 +00002680 return BinaryOperator::createLShr(
Reid Spencer2341c222007-02-02 02:16:23 +00002681 SI->getOperand(0), CU, SI->getName());
Reid Spencerfdff9382006-11-08 06:47:33 +00002682 }
2683 }
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +00002684 }
2685 }
Chris Lattner022167f2004-03-13 00:11:49 +00002686 }
Chris Lattner183b3362004-04-09 19:05:30 +00002687
2688 // Try to fold constant sub into select arguments.
2689 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00002690 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002691 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002692
2693 if (isa<PHINode>(Op0))
2694 if (Instruction *NV = FoldOpIntoPhi(I))
2695 return NV;
Chris Lattner8f2f5982003-11-05 01:06:05 +00002696 }
2697
Chris Lattnera9be4492005-04-07 16:15:25 +00002698 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2699 if (Op1I->getOpcode() == Instruction::Add &&
Chris Lattner7a002fe2006-12-02 00:13:08 +00002700 !Op0->getType()->isFPOrFPVector()) {
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00002701 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +00002702 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00002703 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +00002704 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00002705 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2706 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2707 // C1-(X+C2) --> (C1-C2)-X
Reid Spencer80263aa2007-03-25 05:33:51 +00002708 return BinaryOperator::createSub(Subtract(CI1, CI2),
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00002709 Op1I->getOperand(0));
2710 }
Chris Lattnera9be4492005-04-07 16:15:25 +00002711 }
2712
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002713 if (Op1I->hasOneUse()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002714 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2715 // is not used by anyone else...
2716 //
Chris Lattnerc2f0aa52004-02-02 20:09:56 +00002717 if (Op1I->getOpcode() == Instruction::Sub &&
Chris Lattner7a002fe2006-12-02 00:13:08 +00002718 !Op1I->getType()->isFPOrFPVector()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002719 // Swap the two operands of the subexpr...
2720 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2721 Op1I->setOperand(0, IIOp1);
2722 Op1I->setOperand(1, IIOp0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002723
Chris Lattner3082c5a2003-02-18 19:28:33 +00002724 // Create the new top level add instruction...
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002725 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002726 }
2727
2728 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2729 //
2730 if (Op1I->getOpcode() == Instruction::And &&
2731 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2732 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2733
Chris Lattner396dbfe2004-06-09 05:08:07 +00002734 Value *NewNot =
2735 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002736 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002737 }
Chris Lattner57c8d992003-02-18 19:57:07 +00002738
Reid Spencer3c514952006-10-16 23:08:08 +00002739 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002740 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencere0fc4df2006-10-20 07:07:24 +00002741 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Zhou Shengaafe4e22007-04-19 05:39:12 +00002742 if (CSI->isZero())
Chris Lattner0aee4b72004-10-06 15:08:25 +00002743 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002744 return BinaryOperator::createSDiv(Op1I->getOperand(0),
Chris Lattner0aee4b72004-10-06 15:08:25 +00002745 ConstantExpr::getNeg(DivRHS));
2746
Chris Lattner57c8d992003-02-18 19:57:07 +00002747 // X - X*C --> X * (1-C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00002748 ConstantInt *C2 = 0;
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002749 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Reid Spencer80263aa2007-03-25 05:33:51 +00002750 Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002751 return BinaryOperator::createMul(Op0, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +00002752 }
Dan Gohman2ac26522007-09-17 17:31:57 +00002753
2754 // X - ((X / Y) * Y) --> X % Y
2755 if (Op1I->getOpcode() == Instruction::Mul)
2756 if (Instruction *I = dyn_cast<Instruction>(Op1I->getOperand(0)))
2757 if (Op0 == I->getOperand(0) &&
2758 Op1I->getOperand(1) == I->getOperand(1)) {
2759 if (I->getOpcode() == Instruction::SDiv)
2760 return BinaryOperator::createSRem(Op0, Op1I->getOperand(1));
2761 if (I->getOpcode() == Instruction::UDiv)
2762 return BinaryOperator::createURem(Op0, Op1I->getOperand(1));
2763 }
Chris Lattnerad3c4952002-05-09 01:29:19 +00002764 }
Chris Lattnera9be4492005-04-07 16:15:25 +00002765 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00002766
Chris Lattner7a002fe2006-12-02 00:13:08 +00002767 if (!Op0->getType()->isFPOrFPVector())
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +00002768 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner47060462005-04-07 17:14:51 +00002769 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner411336f2005-01-19 21:50:18 +00002770 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2771 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2772 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2773 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner47060462005-04-07 17:14:51 +00002774 } else if (Op0I->getOpcode() == Instruction::Sub) {
2775 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
2776 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
Chris Lattner411336f2005-01-19 21:50:18 +00002777 }
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +00002778 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002779
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002780 ConstantInt *C1;
2781 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Reid Spencer80263aa2007-03-25 05:33:51 +00002782 if (X == Op1) // X*C - X --> X * (C-1)
2783 return BinaryOperator::createMul(Op1, SubOne(C1));
Chris Lattner57c8d992003-02-18 19:57:07 +00002784
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002785 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2786 if (X == dyn_castFoldableMul(Op1, C2))
Zhou Sheng3b8eb702008-02-22 10:00:35 +00002787 return BinaryOperator::createMul(X, Subtract(C1, C2));
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002788 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002789 return 0;
Chris Lattner260ab202002-04-18 17:39:14 +00002790}
2791
Chris Lattner06205d52007-07-15 20:42:37 +00002792/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2793/// comparison only checks the sign bit. If it only checks the sign bit, set
2794/// TrueIfSigned if the result of the comparison is true when the input value is
2795/// signed.
2796static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2797 bool &TrueIfSigned) {
Reid Spencer266e42b2006-12-23 06:05:41 +00002798 switch (pred) {
Chris Lattner06205d52007-07-15 20:42:37 +00002799 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2800 TrueIfSigned = true;
2801 return RHS->isZero();
Chris Lattner640fd512007-07-16 04:15:34 +00002802 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2803 TrueIfSigned = true;
2804 return RHS->isAllOnesValue();
Chris Lattner06205d52007-07-15 20:42:37 +00002805 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2806 TrueIfSigned = false;
2807 return RHS->isAllOnesValue();
Chris Lattner640fd512007-07-16 04:15:34 +00002808 case ICmpInst::ICMP_UGT:
2809 // True if LHS u> RHS and RHS == high-bit-mask - 1
2810 TrueIfSigned = true;
2811 return RHS->getValue() ==
2812 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2813 case ICmpInst::ICMP_UGE:
2814 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2815 TrueIfSigned = true;
2816 return RHS->getValue() ==
2817 APInt::getSignBit(RHS->getType()->getPrimitiveSizeInBits());
Chris Lattner06205d52007-07-15 20:42:37 +00002818 default:
2819 return false;
Chris Lattnere79e8542004-02-23 06:38:22 +00002820 }
Chris Lattnere79e8542004-02-23 06:38:22 +00002821}
2822
Chris Lattner113f4f42002-06-25 16:13:24 +00002823Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002824 bool Changed = SimplifyCommutative(I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002825 Value *Op0 = I.getOperand(0);
Chris Lattner260ab202002-04-18 17:39:14 +00002826
Chris Lattner81a7a232004-10-16 18:11:37 +00002827 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2828 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2829
Chris Lattnere6794492002-08-12 21:17:25 +00002830 // Simplify mul instructions with a constant RHS...
Chris Lattner3082c5a2003-02-18 19:28:33 +00002831 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2832 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerede3fe02003-08-13 04:18:28 +00002833
2834 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer2341c222007-02-02 02:16:23 +00002835 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnerede3fe02003-08-13 04:18:28 +00002836 if (SI->getOpcode() == Instruction::Shl)
2837 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002838 return BinaryOperator::createMul(SI->getOperand(0),
2839 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanb1c93172005-04-21 23:48:37 +00002840
Zhou Shengaafe4e22007-04-19 05:39:12 +00002841 if (CI->isZero())
Chris Lattnercce81be2003-09-11 22:24:54 +00002842 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2843 if (CI->equalsInt(1)) // X * 1 == X
2844 return ReplaceInstUsesWith(I, Op0);
2845 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner35236d82003-06-25 17:09:20 +00002846 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner31ba1292002-04-29 22:24:47 +00002847
Zhou Sheng4961cf12007-03-29 01:57:21 +00002848 const APInt& Val = cast<ConstantInt>(CI)->getValue();
Reid Spencer6d392062007-03-23 20:05:17 +00002849 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Reid Spencer0d5f9232007-02-02 14:08:20 +00002850 return BinaryOperator::createShl(Op0,
Reid Spencer6d392062007-03-23 20:05:17 +00002851 ConstantInt::get(Op0->getType(), Val.logBase2()));
Chris Lattner22d00a82005-08-02 19:16:58 +00002852 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00002853 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002854 if (Op1F->isNullValue())
2855 return ReplaceInstUsesWith(I, Op1);
Chris Lattner31ba1292002-04-29 22:24:47 +00002856
Chris Lattner3082c5a2003-02-18 19:28:33 +00002857 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2858 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
Dale Johannesen98d3a082007-09-14 22:26:36 +00002859 // We need a better interface for long double here.
2860 if (Op1->getType() == Type::FloatTy || Op1->getType() == Type::DoubleTy)
2861 if (Op1F->isExactlyValue(1.0))
2862 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
Chris Lattner3082c5a2003-02-18 19:28:33 +00002863 }
Chris Lattner32c01df2006-03-04 06:04:02 +00002864
2865 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2866 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2867 isa<ConstantInt>(Op0I->getOperand(1))) {
2868 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2869 Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
2870 Op1, "tmp");
2871 InsertNewInstBefore(Add, I);
2872 Value *C1C2 = ConstantExpr::getMul(Op1,
2873 cast<Constant>(Op0I->getOperand(1)));
2874 return BinaryOperator::createAdd(Add, C1C2);
2875
2876 }
Chris Lattner183b3362004-04-09 19:05:30 +00002877
2878 // Try to fold constant mul into select arguments.
2879 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00002880 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002881 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002882
2883 if (isa<PHINode>(Op0))
2884 if (Instruction *NV = FoldOpIntoPhi(I))
2885 return NV;
Chris Lattner260ab202002-04-18 17:39:14 +00002886 }
2887
Chris Lattner934a64cf2003-03-10 23:23:04 +00002888 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2889 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002890 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattner934a64cf2003-03-10 23:23:04 +00002891
Chris Lattner2635b522004-02-23 05:39:21 +00002892 // If one of the operands of the multiply is a cast from a boolean value, then
2893 // we know the bool is either zero or one, so this is a 'masking' multiply.
2894 // See if we can simplify things based on how the boolean was originally
2895 // formed.
2896 CastInst *BoolCast = 0;
Reid Spencer74a528b2006-12-13 18:21:21 +00002897 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(0)))
Reid Spencer542964f2007-01-11 18:21:29 +00002898 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattner2635b522004-02-23 05:39:21 +00002899 BoolCast = CI;
2900 if (!BoolCast)
Reid Spencer74a528b2006-12-13 18:21:21 +00002901 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
Reid Spencer542964f2007-01-11 18:21:29 +00002902 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattner2635b522004-02-23 05:39:21 +00002903 BoolCast = CI;
2904 if (BoolCast) {
Reid Spencer266e42b2006-12-23 06:05:41 +00002905 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattner2635b522004-02-23 05:39:21 +00002906 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2907 const Type *SCOpTy = SCIOp0->getType();
Chris Lattner06205d52007-07-15 20:42:37 +00002908 bool TIS = false;
2909
Reid Spencer266e42b2006-12-23 06:05:41 +00002910 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattnere79e8542004-02-23 06:38:22 +00002911 // multiply into a shift/and combination.
2912 if (isa<ConstantInt>(SCIOp1) &&
Chris Lattner06205d52007-07-15 20:42:37 +00002913 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2914 TIS) {
Chris Lattner2635b522004-02-23 05:39:21 +00002915 // Shift the X value right to turn it into "all signbits".
Reid Spencer2341c222007-02-02 02:16:23 +00002916 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002917 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattnere79e8542004-02-23 06:38:22 +00002918 Value *V =
Reid Spencer2341c222007-02-02 02:16:23 +00002919 InsertNewInstBefore(
2920 BinaryOperator::create(Instruction::AShr, SCIOp0, Amt,
Chris Lattnere79e8542004-02-23 06:38:22 +00002921 BoolCast->getOperand(0)->getName()+
2922 ".mask"), I);
Chris Lattner2635b522004-02-23 05:39:21 +00002923
2924 // If the multiply type is not the same as the source type, sign extend
2925 // or truncate to the multiply type.
Reid Spencer13bc5d72006-12-12 09:18:51 +00002926 if (I.getType() != V->getType()) {
Zhou Sheng56cda952007-04-02 08:20:41 +00002927 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2928 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
Reid Spencer13bc5d72006-12-12 09:18:51 +00002929 Instruction::CastOps opcode =
2930 (SrcBits == DstBits ? Instruction::BitCast :
2931 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2932 V = InsertCastBefore(opcode, V, I.getType(), I);
2933 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002934
Chris Lattner2635b522004-02-23 05:39:21 +00002935 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002936 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattner2635b522004-02-23 05:39:21 +00002937 }
2938 }
2939 }
2940
Chris Lattner113f4f42002-06-25 16:13:24 +00002941 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00002942}
2943
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002944/// This function implements the transforms on div instructions that work
2945/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2946/// used by the visitors to those instructions.
2947/// @brief Transforms common to all three div instructions
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002948Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002949 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner81a7a232004-10-16 18:11:37 +00002950
Chris Lattner0fe6bce2008-02-19 06:12:18 +00002951 // undef / X -> 0 for integer.
2952 // undef / X -> undef for FP (the undef could be a snan).
2953 if (isa<UndefValue>(Op0)) {
2954 if (Op0->getType()->isFPOrFPVector())
2955 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002956 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner0fe6bce2008-02-19 06:12:18 +00002957 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002958
2959 // X / undef -> undef
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002960 if (isa<UndefValue>(Op1))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002961 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002962
Chris Lattner710b4412008-01-28 00:58:18 +00002963 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2964 // This does not apply for fdiv.
Chris Lattnerd79dc792006-09-09 20:26:32 +00002965 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
Chris Lattner710b4412008-01-28 00:58:18 +00002966 // [su]div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in
2967 // the same basic block, then we replace the select with Y, and the
2968 // condition of the select with false (if the cond value is in the same BB).
2969 // If the select has uses other than the div, this allows them to be
2970 // simplified also. Note that div X, Y is just as good as div X, 0 (undef)
2971 if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(1)))
Chris Lattnerd79dc792006-09-09 20:26:32 +00002972 if (ST->isNullValue()) {
2973 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2974 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng75b871f2007-01-11 12:24:14 +00002975 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Chris Lattnerd79dc792006-09-09 20:26:32 +00002976 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2977 I.setOperand(1, SI->getOperand(2));
2978 else
2979 UpdateValueUsesWith(SI, SI->getOperand(2));
2980 return &I;
2981 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002982
Chris Lattner710b4412008-01-28 00:58:18 +00002983 // Likewise for: [su]div X, (Cond ? Y : 0) -> div X, Y
2984 if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(2)))
Chris Lattnerd79dc792006-09-09 20:26:32 +00002985 if (ST->isNullValue()) {
2986 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2987 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng75b871f2007-01-11 12:24:14 +00002988 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Chris Lattnerd79dc792006-09-09 20:26:32 +00002989 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2990 I.setOperand(1, SI->getOperand(1));
2991 else
2992 UpdateValueUsesWith(SI, SI->getOperand(1));
2993 return &I;
2994 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002995 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002996
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002997 return 0;
2998}
Misha Brukmanb1c93172005-04-21 23:48:37 +00002999
Reid Spencer7e80b0b2006-10-26 06:15:43 +00003000/// This function implements the transforms common to both integer division
3001/// instructions (udiv and sdiv). It is called by the visitors to those integer
3002/// division instructions.
3003/// @brief Common integer divide transforms
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003004Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00003005 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3006
3007 if (Instruction *Common = commonDivTransforms(I))
3008 return Common;
3009
3010 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3011 // div X, 1 == X
3012 if (RHS->equalsInt(1))
3013 return ReplaceInstUsesWith(I, Op0);
3014
3015 // (X / C1) / C2 -> X / (C1*C2)
3016 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
3017 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
3018 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Nick Lewyckyfefd0202008-02-18 22:48:05 +00003019 if (MultiplyOverflows(RHS, LHSRHS, I.getOpcode()==Instruction::SDiv))
3020 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3021 else
3022 return BinaryOperator::create(I.getOpcode(), LHS->getOperand(0),
3023 Multiply(RHS, LHSRHS));
Chris Lattner42362612005-04-08 04:03:26 +00003024 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00003025
Reid Spencer6d392062007-03-23 20:05:17 +00003026 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer7e80b0b2006-10-26 06:15:43 +00003027 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3028 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3029 return R;
3030 if (isa<PHINode>(Op0))
3031 if (Instruction *NV = FoldOpIntoPhi(I))
3032 return NV;
3033 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00003034 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003035
Chris Lattner3082c5a2003-02-18 19:28:33 +00003036 // 0 / X == 0, we don't need to preserve faults!
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00003037 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattner3082c5a2003-02-18 19:28:33 +00003038 if (LHS->equalsInt(0))
3039 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3040
Reid Spencer7e80b0b2006-10-26 06:15:43 +00003041 return 0;
3042}
3043
3044Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3045 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3046
3047 // Handle the integer div common cases
3048 if (Instruction *Common = commonIDivTransforms(I))
3049 return Common;
3050
3051 // X udiv C^2 -> X >> C
3052 // Check to see if this is an unsigned division with an exact power of 2,
3053 // if so, convert to a right shift.
3054 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Reid Spencer54d5b1b2007-03-26 23:58:26 +00003055 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Reid Spencer6d392062007-03-23 20:05:17 +00003056 return BinaryOperator::createLShr(Op0,
Zhou Sheng222d5eb2007-03-25 05:01:29 +00003057 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00003058 }
3059
3060 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer2341c222007-02-02 02:16:23 +00003061 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00003062 if (RHSI->getOpcode() == Instruction::Shl &&
3063 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng150f3bb2007-04-01 17:13:37 +00003064 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencer6d392062007-03-23 20:05:17 +00003065 if (C1.isPowerOf2()) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00003066 Value *N = RHSI->getOperand(1);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003067 const Type *NTy = N->getType();
Reid Spencer959a21d2007-03-23 21:24:59 +00003068 if (uint32_t C2 = C1.logBase2()) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00003069 Constant *C2V = ConstantInt::get(NTy, C2);
3070 N = InsertNewInstBefore(BinaryOperator::createAdd(N, C2V, "tmp"), I);
Chris Lattner2e90b732006-02-05 07:54:04 +00003071 }
Reid Spencer0d5f9232007-02-02 14:08:20 +00003072 return BinaryOperator::createLShr(Op0, N);
Chris Lattner2e90b732006-02-05 07:54:04 +00003073 }
3074 }
Chris Lattnerdd0c1742005-11-05 07:40:31 +00003075 }
3076
Reid Spencer7e80b0b2006-10-26 06:15:43 +00003077 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3078 // where C1&C2 are powers of two.
Reid Spencer3939b1a2007-03-05 23:36:13 +00003079 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00003080 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencer3939b1a2007-03-05 23:36:13 +00003081 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng150f3bb2007-04-01 17:13:37 +00003082 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencer6d392062007-03-23 20:05:17 +00003083 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencer3939b1a2007-03-05 23:36:13 +00003084 // Compute the shift amounts
Reid Spencer6d392062007-03-23 20:05:17 +00003085 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencer3939b1a2007-03-05 23:36:13 +00003086 // Construct the "on true" case of the select
3087 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
3088 Instruction *TSI = BinaryOperator::createLShr(
3089 Op0, TC, SI->getName()+".t");
3090 TSI = InsertNewInstBefore(TSI, I);
3091
3092 // Construct the "on false" case of the select
3093 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
3094 Instruction *FSI = BinaryOperator::createLShr(
3095 Op0, FC, SI->getName()+".f");
3096 FSI = InsertNewInstBefore(FSI, I);
Reid Spencer7e80b0b2006-10-26 06:15:43 +00003097
Reid Spencer3939b1a2007-03-05 23:36:13 +00003098 // construct the select instruction and return it.
Gabor Greife9ecc682008-04-06 20:25:17 +00003099 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer7e80b0b2006-10-26 06:15:43 +00003100 }
Reid Spencer3939b1a2007-03-05 23:36:13 +00003101 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003102 return 0;
3103}
3104
Reid Spencer7e80b0b2006-10-26 06:15:43 +00003105Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3106 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3107
3108 // Handle the integer div common cases
3109 if (Instruction *Common = commonIDivTransforms(I))
3110 return Common;
3111
3112 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3113 // sdiv X, -1 == -X
3114 if (RHS->isAllOnesValue())
3115 return BinaryOperator::createNeg(Op0);
3116
3117 // -X/C -> X/-C
3118 if (Value *LHSNeg = dyn_castNegVal(Op0))
3119 return BinaryOperator::createSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
3120 }
3121
3122 // If the sign bits of both operands are zero (i.e. we can prove they are
3123 // unsigned inputs), turn this into a udiv.
Chris Lattner03c49532007-01-15 02:27:26 +00003124 if (I.getType()->isInteger()) {
Reid Spencer6d392062007-03-23 20:05:17 +00003125 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00003126 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Dan Gohman4decbc52007-11-05 23:16:33 +00003127 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
Reid Spencer7e80b0b2006-10-26 06:15:43 +00003128 return BinaryOperator::createUDiv(Op0, Op1, I.getName());
3129 }
3130 }
3131
3132 return 0;
3133}
3134
3135Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3136 return commonDivTransforms(I);
3137}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003138
Reid Spencer7eb55b32006-11-02 01:53:59 +00003139/// This function implements the transforms on rem instructions that work
3140/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3141/// is used by the visitors to those instructions.
3142/// @brief Transforms common to all three rem instructions
3143Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00003144 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer7eb55b32006-11-02 01:53:59 +00003145
Chris Lattner0fe6bce2008-02-19 06:12:18 +00003146 // 0 % X == 0 for integer, we don't need to preserve faults!
Chris Lattner0de4a8d2006-02-28 05:30:45 +00003147 if (Constant *LHS = dyn_cast<Constant>(Op0))
3148 if (LHS->isNullValue())
3149 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3150
Chris Lattner0fe6bce2008-02-19 06:12:18 +00003151 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3152 if (I.getType()->isFPOrFPVector())
3153 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Chris Lattner0de4a8d2006-02-28 05:30:45 +00003154 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner0fe6bce2008-02-19 06:12:18 +00003155 }
Chris Lattner0de4a8d2006-02-28 05:30:45 +00003156 if (isa<UndefValue>(Op1))
3157 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer7eb55b32006-11-02 01:53:59 +00003158
3159 // Handle cases involving: rem X, (select Cond, Y, Z)
3160 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3161 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
3162 // the same basic block, then we replace the select with Y, and the
3163 // condition of the select with false (if the cond value is in the same
3164 // BB). If the select has uses other than the div, this allows them to be
3165 // simplified also.
3166 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
3167 if (ST->isNullValue()) {
3168 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3169 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng75b871f2007-01-11 12:24:14 +00003170 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Reid Spencer7eb55b32006-11-02 01:53:59 +00003171 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3172 I.setOperand(1, SI->getOperand(2));
3173 else
3174 UpdateValueUsesWith(SI, SI->getOperand(2));
Chris Lattner7fd5f072004-07-06 07:01:22 +00003175 return &I;
3176 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00003177 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
3178 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
3179 if (ST->isNullValue()) {
3180 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3181 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng75b871f2007-01-11 12:24:14 +00003182 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Reid Spencer7eb55b32006-11-02 01:53:59 +00003183 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3184 I.setOperand(1, SI->getOperand(1));
3185 else
3186 UpdateValueUsesWith(SI, SI->getOperand(1));
3187 return &I;
3188 }
Chris Lattnere9ff0ea2005-11-05 07:28:37 +00003189 }
Chris Lattner7fd5f072004-07-06 07:01:22 +00003190
Reid Spencer7eb55b32006-11-02 01:53:59 +00003191 return 0;
3192}
3193
3194/// This function implements the transforms common to both integer remainder
3195/// instructions (urem and srem). It is called by the visitors to those integer
3196/// remainder instructions.
3197/// @brief Common integer remainder transforms
3198Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3199 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3200
3201 if (Instruction *common = commonRemTransforms(I))
3202 return common;
3203
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00003204 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner0de4a8d2006-02-28 05:30:45 +00003205 // X % 0 == undef, we don't need to preserve faults!
3206 if (RHS->equalsInt(0))
3207 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3208
Chris Lattner3082c5a2003-02-18 19:28:33 +00003209 if (RHS->equalsInt(1)) // X % 1 == 0
3210 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3211
Chris Lattnerb70f1412006-02-28 05:49:21 +00003212 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3213 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3214 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3215 return R;
3216 } else if (isa<PHINode>(Op0I)) {
3217 if (Instruction *NV = FoldOpIntoPhi(I))
3218 return NV;
Chris Lattnerb70f1412006-02-28 05:49:21 +00003219 }
Nick Lewyckyd0b62a12008-03-06 06:48:30 +00003220
3221 // See if we can fold away this rem instruction.
3222 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3223 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3224 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3225 KnownZero, KnownOne))
3226 return &I;
Chris Lattnerb70f1412006-02-28 05:49:21 +00003227 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00003228 }
3229
Reid Spencer7eb55b32006-11-02 01:53:59 +00003230 return 0;
3231}
3232
3233Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3234 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3235
3236 if (Instruction *common = commonIRemTransforms(I))
3237 return common;
3238
3239 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3240 // X urem C^2 -> X and C
3241 // Check to see if this is an unsigned remainder with an exact power of 2,
3242 // if so, convert to a bitwise and.
3243 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencer6d392062007-03-23 20:05:17 +00003244 if (C->getValue().isPowerOf2())
Reid Spencer7eb55b32006-11-02 01:53:59 +00003245 return BinaryOperator::createAnd(Op0, SubOne(C));
3246 }
3247
Chris Lattner2e90b732006-02-05 07:54:04 +00003248 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00003249 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3250 if (RHSI->getOpcode() == Instruction::Shl &&
3251 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng222d5eb2007-03-25 05:01:29 +00003252 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Chris Lattner2e90b732006-02-05 07:54:04 +00003253 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
3254 Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
3255 "tmp"), I);
3256 return BinaryOperator::createAnd(Op0, Add);
3257 }
3258 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00003259 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00003260
Reid Spencer7eb55b32006-11-02 01:53:59 +00003261 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3262 // where C1&C2 are powers of two.
3263 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3264 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3265 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3266 // STO == 0 and SFO == 0 handled above.
Reid Spencer6d392062007-03-23 20:05:17 +00003267 if ((STO->getValue().isPowerOf2()) &&
3268 (SFO->getValue().isPowerOf2())) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00003269 Value *TrueAnd = InsertNewInstBefore(
3270 BinaryOperator::createAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
3271 Value *FalseAnd = InsertNewInstBefore(
3272 BinaryOperator::createAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
Gabor Greife9ecc682008-04-06 20:25:17 +00003273 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Reid Spencer7eb55b32006-11-02 01:53:59 +00003274 }
3275 }
Chris Lattner2e90b732006-02-05 07:54:04 +00003276 }
3277
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003278 return 0;
3279}
3280
Reid Spencer7eb55b32006-11-02 01:53:59 +00003281Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3282 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3283
Dan Gohman4decbc52007-11-05 23:16:33 +00003284 // Handle the integer rem common cases
Reid Spencer7eb55b32006-11-02 01:53:59 +00003285 if (Instruction *common = commonIRemTransforms(I))
3286 return common;
3287
3288 if (Value *RHSNeg = dyn_castNegVal(Op1))
3289 if (!isa<ConstantInt>(RHSNeg) ||
Zhou Sheng222d5eb2007-03-25 05:01:29 +00003290 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive()) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00003291 // X % -Y -> X % Y
3292 AddUsesToWorkList(I);
3293 I.setOperand(1, RHSNeg);
3294 return &I;
3295 }
3296
Dan Gohman4decbc52007-11-05 23:16:33 +00003297 // If the sign bits of both operands are zero (i.e. we can prove they are
Reid Spencer7eb55b32006-11-02 01:53:59 +00003298 // unsigned inputs), turn this into a urem.
Dan Gohman4decbc52007-11-05 23:16:33 +00003299 if (I.getType()->isInteger()) {
3300 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3301 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3302 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
3303 return BinaryOperator::createURem(Op0, Op1, I.getName());
3304 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00003305 }
3306
3307 return 0;
3308}
3309
3310Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00003311 return commonRemTransforms(I);
3312}
3313
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003314// isMaxValueMinusOne - return true if this is Max-1
Reid Spencer266e42b2006-12-23 06:05:41 +00003315static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
Reid Spenceref599b02007-03-19 21:10:28 +00003316 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner06205d52007-07-15 20:42:37 +00003317 if (!isSigned)
3318 return C->getValue() == APInt::getAllOnesValue(TypeBits) - 1;
3319 return C->getValue() == APInt::getSignedMaxValue(TypeBits)-1;
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003320}
3321
3322// isMinValuePlusOne - return true if this is Min+1
Reid Spencer266e42b2006-12-23 06:05:41 +00003323static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
Chris Lattner06205d52007-07-15 20:42:37 +00003324 if (!isSigned)
3325 return C->getValue() == 1; // unsigned
3326
3327 // Calculate 1111111111000000000000
3328 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
3329 return C->getValue() == APInt::getSignedMinValue(TypeBits)+1;
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003330}
3331
Chris Lattner35167c32004-06-09 07:59:58 +00003332// isOneBitSet - Return true if there is exactly one bit set in the specified
3333// constant.
3334static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer66827212007-03-20 00:16:52 +00003335 return CI->getValue().isPowerOf2();
Chris Lattner35167c32004-06-09 07:59:58 +00003336}
3337
Chris Lattner8fc5af42004-09-23 21:46:38 +00003338// isHighOnes - Return true if the constant is of the form 1+0+.
3339// This is the same as lowones(~X).
3340static bool isHighOnes(const ConstantInt *CI) {
Zhou Shengb3949342007-03-20 12:49:06 +00003341 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattner8fc5af42004-09-23 21:46:38 +00003342}
3343
Reid Spencer266e42b2006-12-23 06:05:41 +00003344/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattner3ac7c262003-08-13 20:16:26 +00003345/// are carefully arranged to allow folding of expressions such as:
3346///
3347/// (A < B) | (A > B) --> (A != B)
3348///
Reid Spencer266e42b2006-12-23 06:05:41 +00003349/// Note that this is only valid if the first and second predicates have the
3350/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattner3ac7c262003-08-13 20:16:26 +00003351///
Reid Spencer266e42b2006-12-23 06:05:41 +00003352/// Three bits are used to represent the condition, as follows:
3353/// 0 A > B
3354/// 1 A == B
3355/// 2 A < B
3356///
3357/// <=> Value Definition
3358/// 000 0 Always false
3359/// 001 1 A > B
3360/// 010 2 A == B
3361/// 011 3 A >= B
3362/// 100 4 A < B
3363/// 101 5 A != B
3364/// 110 6 A <= B
3365/// 111 7 Always true
3366///
3367static unsigned getICmpCode(const ICmpInst *ICI) {
3368 switch (ICI->getPredicate()) {
Chris Lattner3ac7c262003-08-13 20:16:26 +00003369 // False -> 0
Reid Spencer266e42b2006-12-23 06:05:41 +00003370 case ICmpInst::ICMP_UGT: return 1; // 001
3371 case ICmpInst::ICMP_SGT: return 1; // 001
3372 case ICmpInst::ICMP_EQ: return 2; // 010
3373 case ICmpInst::ICMP_UGE: return 3; // 011
3374 case ICmpInst::ICMP_SGE: return 3; // 011
3375 case ICmpInst::ICMP_ULT: return 4; // 100
3376 case ICmpInst::ICMP_SLT: return 4; // 100
3377 case ICmpInst::ICMP_NE: return 5; // 101
3378 case ICmpInst::ICMP_ULE: return 6; // 110
3379 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattner3ac7c262003-08-13 20:16:26 +00003380 // True -> 7
3381 default:
Reid Spencer266e42b2006-12-23 06:05:41 +00003382 assert(0 && "Invalid ICmp predicate!");
Chris Lattner3ac7c262003-08-13 20:16:26 +00003383 return 0;
3384 }
3385}
3386
Reid Spencer266e42b2006-12-23 06:05:41 +00003387/// getICmpValue - This is the complement of getICmpCode, which turns an
3388/// opcode and two operands into either a constant true or false, or a brand
Dan Gohman2ac26522007-09-17 17:31:57 +00003389/// new ICmp instruction. The sign is passed in to determine which kind
Reid Spencer266e42b2006-12-23 06:05:41 +00003390/// of predicate to use in new icmp instructions.
3391static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3392 switch (code) {
3393 default: assert(0 && "Illegal ICmp code!");
Zhou Sheng75b871f2007-01-11 12:24:14 +00003394 case 0: return ConstantInt::getFalse();
Reid Spencer266e42b2006-12-23 06:05:41 +00003395 case 1:
3396 if (sign)
3397 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3398 else
3399 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3400 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
3401 case 3:
3402 if (sign)
3403 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3404 else
3405 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3406 case 4:
3407 if (sign)
3408 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3409 else
3410 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3411 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
3412 case 6:
3413 if (sign)
3414 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3415 else
3416 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Zhou Sheng75b871f2007-01-11 12:24:14 +00003417 case 7: return ConstantInt::getTrue();
Chris Lattner3ac7c262003-08-13 20:16:26 +00003418 }
3419}
3420
Reid Spencer266e42b2006-12-23 06:05:41 +00003421static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3422 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3423 (ICmpInst::isSignedPredicate(p1) &&
3424 (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
3425 (ICmpInst::isSignedPredicate(p2) &&
3426 (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
3427}
3428
3429namespace {
3430// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3431struct FoldICmpLogical {
Chris Lattner3ac7c262003-08-13 20:16:26 +00003432 InstCombiner &IC;
3433 Value *LHS, *RHS;
Reid Spencer266e42b2006-12-23 06:05:41 +00003434 ICmpInst::Predicate pred;
3435 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3436 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3437 pred(ICI->getPredicate()) {}
Chris Lattner3ac7c262003-08-13 20:16:26 +00003438 bool shouldApply(Value *V) const {
Reid Spencer266e42b2006-12-23 06:05:41 +00003439 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3440 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +00003441 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3442 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Chris Lattner3ac7c262003-08-13 20:16:26 +00003443 return false;
3444 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003445 Instruction *apply(Instruction &Log) const {
3446 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3447 if (ICI->getOperand(0) != LHS) {
3448 assert(ICI->getOperand(1) == LHS);
3449 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattner3ac7c262003-08-13 20:16:26 +00003450 }
3451
Chris Lattnerd1bce952007-03-13 14:27:42 +00003452 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencer266e42b2006-12-23 06:05:41 +00003453 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerd1bce952007-03-13 14:27:42 +00003454 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattner3ac7c262003-08-13 20:16:26 +00003455 unsigned Code;
3456 switch (Log.getOpcode()) {
3457 case Instruction::And: Code = LHSCode & RHSCode; break;
3458 case Instruction::Or: Code = LHSCode | RHSCode; break;
3459 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner2caaaba2003-09-22 20:33:34 +00003460 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattner3ac7c262003-08-13 20:16:26 +00003461 }
3462
Chris Lattnerd1bce952007-03-13 14:27:42 +00003463 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3464 ICmpInst::isSignedPredicate(ICI->getPredicate());
3465
3466 Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
Chris Lattner3ac7c262003-08-13 20:16:26 +00003467 if (Instruction *I = dyn_cast<Instruction>(RV))
3468 return I;
3469 // Otherwise, it's a constant boolean value...
3470 return IC.ReplaceInstUsesWith(Log, RV);
3471 }
3472};
Chris Lattnere3a63d12006-11-15 04:53:24 +00003473} // end anonymous namespace
Chris Lattner3ac7c262003-08-13 20:16:26 +00003474
Chris Lattnerba1cb382003-09-19 17:17:26 +00003475// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3476// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer2341c222007-02-02 02:16:23 +00003477// guaranteed to be a binary operator.
Chris Lattnerba1cb382003-09-19 17:17:26 +00003478Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng75b871f2007-01-11 12:24:14 +00003479 ConstantInt *OpRHS,
3480 ConstantInt *AndRHS,
Chris Lattnerba1cb382003-09-19 17:17:26 +00003481 BinaryOperator &TheAnd) {
3482 Value *X = Op->getOperand(0);
Chris Lattnerfcf21a72004-01-12 19:47:05 +00003483 Constant *Together = 0;
Reid Spencer2341c222007-02-02 02:16:23 +00003484 if (!Op->isShift())
Reid Spencer80263aa2007-03-25 05:33:51 +00003485 Together = And(AndRHS, OpRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003486
Chris Lattnerba1cb382003-09-19 17:17:26 +00003487 switch (Op->getOpcode()) {
3488 case Instruction::Xor:
Chris Lattner86102b82005-01-01 16:22:27 +00003489 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00003490 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Chris Lattner6e0123b2007-02-11 01:23:03 +00003491 Instruction *And = BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00003492 InsertNewInstBefore(And, TheAnd);
Chris Lattner6e0123b2007-02-11 01:23:03 +00003493 And->takeName(Op);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003494 return BinaryOperator::createXor(And, Together);
Chris Lattnerba1cb382003-09-19 17:17:26 +00003495 }
3496 break;
3497 case Instruction::Or:
Chris Lattner86102b82005-01-01 16:22:27 +00003498 if (Together == AndRHS) // (X | C) & C --> C
3499 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003500
Chris Lattner86102b82005-01-01 16:22:27 +00003501 if (Op->hasOneUse() && Together != OpRHS) {
3502 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Chris Lattner6e0123b2007-02-11 01:23:03 +00003503 Instruction *Or = BinaryOperator::createOr(X, Together);
Chris Lattner86102b82005-01-01 16:22:27 +00003504 InsertNewInstBefore(Or, TheAnd);
Chris Lattner6e0123b2007-02-11 01:23:03 +00003505 Or->takeName(Op);
Chris Lattner86102b82005-01-01 16:22:27 +00003506 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00003507 }
3508 break;
3509 case Instruction::Add:
Chris Lattnerf95d9b92003-10-15 16:48:29 +00003510 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00003511 // Adding a one to a single bit bit-field should be turned into an XOR
3512 // of the bit. First thing to check is to see if this AND is with a
3513 // single bit constant.
Zhou Sheng150f3bb2007-04-01 17:13:37 +00003514 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00003515
3516 // If there is only one bit set...
Chris Lattner35167c32004-06-09 07:59:58 +00003517 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00003518 // Ok, at this point, we know that we are masking the result of the
3519 // ADD down to exactly one bit. If the constant we are adding has
3520 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng150f3bb2007-04-01 17:13:37 +00003521 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00003522
Chris Lattnerba1cb382003-09-19 17:17:26 +00003523 // Check to see if any bits below the one bit set in AndRHSV are set.
3524 if ((AddRHS & (AndRHSV-1)) == 0) {
3525 // If not, the only thing that can effect the output of the AND is
3526 // the bit specified by AndRHSV. If that bit is set, the effect of
3527 // the XOR is to toggle the bit. If it is clear, then the ADD has
3528 // no effect.
3529 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3530 TheAnd.setOperand(0, X);
3531 return &TheAnd;
3532 } else {
Chris Lattnerba1cb382003-09-19 17:17:26 +00003533 // Pull the XOR out of the AND.
Chris Lattner6e0123b2007-02-11 01:23:03 +00003534 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00003535 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner6e0123b2007-02-11 01:23:03 +00003536 NewAnd->takeName(Op);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003537 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00003538 }
3539 }
3540 }
3541 }
3542 break;
Chris Lattner2da29172003-09-19 19:05:02 +00003543
3544 case Instruction::Shl: {
3545 // We know that the AND will not produce any of the bits shifted in, so if
3546 // the anded constant includes them, clear them now!
3547 //
Zhou Shengb3a80b12007-03-29 08:15:12 +00003548 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Shengb25806f2007-03-30 09:29:48 +00003549 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Shengb3a80b12007-03-29 08:15:12 +00003550 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3551 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003552
Zhou Shengb3a80b12007-03-29 08:15:12 +00003553 if (CI->getValue() == ShlMask) {
3554 // Masking out bits that the shift already masks
Chris Lattner7e794272004-09-24 15:21:34 +00003555 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3556 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner2da29172003-09-19 19:05:02 +00003557 TheAnd.setOperand(1, CI);
3558 return &TheAnd;
3559 }
3560 break;
Misha Brukmanb1c93172005-04-21 23:48:37 +00003561 }
Reid Spencerfdff9382006-11-08 06:47:33 +00003562 case Instruction::LShr:
3563 {
Chris Lattner2da29172003-09-19 19:05:02 +00003564 // We know that the AND will not produce any of the bits shifted in, so if
3565 // the anded constant includes them, clear them now! This only applies to
3566 // unsigned shifts, because a signed shr may bring in set bits!
3567 //
Zhou Shengb3a80b12007-03-29 08:15:12 +00003568 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Shengb25806f2007-03-30 09:29:48 +00003569 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Shengb3a80b12007-03-29 08:15:12 +00003570 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3571 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
Chris Lattner7e794272004-09-24 15:21:34 +00003572
Zhou Shengb3a80b12007-03-29 08:15:12 +00003573 if (CI->getValue() == ShrMask) {
3574 // Masking out bits that the shift already masks.
Reid Spencerfdff9382006-11-08 06:47:33 +00003575 return ReplaceInstUsesWith(TheAnd, Op);
3576 } else if (CI != AndRHS) {
3577 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3578 return &TheAnd;
3579 }
3580 break;
3581 }
3582 case Instruction::AShr:
3583 // Signed shr.
3584 // See if this is shifting in some sign extension, then masking it out
3585 // with an and.
3586 if (Op->hasOneUse()) {
Zhou Shengb3a80b12007-03-29 08:15:12 +00003587 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Shengb25806f2007-03-30 09:29:48 +00003588 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Shengb3a80b12007-03-29 08:15:12 +00003589 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3590 Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
Reid Spencer2a499b02006-12-13 17:19:09 +00003591 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer13bc5d72006-12-12 09:18:51 +00003592 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencerfdff9382006-11-08 06:47:33 +00003593 // Make the argument unsigned.
3594 Value *ShVal = Op->getOperand(0);
Reid Spencer2341c222007-02-02 02:16:23 +00003595 ShVal = InsertNewInstBefore(
Reid Spencer0d5f9232007-02-02 14:08:20 +00003596 BinaryOperator::createLShr(ShVal, OpRHS,
Reid Spencer2341c222007-02-02 02:16:23 +00003597 Op->getName()), TheAnd);
Reid Spencer2a499b02006-12-13 17:19:09 +00003598 return BinaryOperator::createAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner7e794272004-09-24 15:21:34 +00003599 }
Chris Lattner2da29172003-09-19 19:05:02 +00003600 }
3601 break;
Chris Lattnerba1cb382003-09-19 17:17:26 +00003602 }
3603 return 0;
3604}
3605
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003606
Chris Lattner6862fbd2004-09-29 17:40:11 +00003607/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3608/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencer266e42b2006-12-23 06:05:41 +00003609/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3610/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattner6862fbd2004-09-29 17:40:11 +00003611/// insert new instructions.
3612Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencer266e42b2006-12-23 06:05:41 +00003613 bool isSigned, bool Inside,
3614 Instruction &IB) {
Zhou Sheng75b871f2007-01-11 12:24:14 +00003615 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencercddc9df2007-01-12 04:24:46 +00003616 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattner6862fbd2004-09-29 17:40:11 +00003617 "Lo is not <= Hi in range emission code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003618
Chris Lattner6862fbd2004-09-29 17:40:11 +00003619 if (Inside) {
3620 if (Lo == Hi) // Trivially false.
Reid Spencer266e42b2006-12-23 06:05:41 +00003621 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003622
Reid Spencer266e42b2006-12-23 06:05:41 +00003623 // V >= Min && V < Hi --> V < Hi
Zhou Sheng75b871f2007-01-11 12:24:14 +00003624 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencerf4071162007-03-21 23:19:50 +00003625 ICmpInst::Predicate pred = (isSigned ?
Reid Spencer266e42b2006-12-23 06:05:41 +00003626 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3627 return new ICmpInst(pred, V, Hi);
3628 }
3629
3630 // Emit V-Lo <u Hi-Lo
3631 Constant *NegLo = ConstantExpr::getNeg(Lo);
3632 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
Chris Lattner6862fbd2004-09-29 17:40:11 +00003633 InsertNewInstBefore(Add, IB);
Reid Spencer266e42b2006-12-23 06:05:41 +00003634 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3635 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00003636 }
3637
3638 if (Lo == Hi) // Trivially true.
Reid Spencer266e42b2006-12-23 06:05:41 +00003639 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattner6862fbd2004-09-29 17:40:11 +00003640
Reid Spencerf4071162007-03-21 23:19:50 +00003641 // V < Min || V >= Hi -> V > Hi-1
Chris Lattner6862fbd2004-09-29 17:40:11 +00003642 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng75b871f2007-01-11 12:24:14 +00003643 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00003644 ICmpInst::Predicate pred = (isSigned ?
3645 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3646 return new ICmpInst(pred, V, Hi);
3647 }
Reid Spencere0fc4df2006-10-20 07:07:24 +00003648
Reid Spencerf4071162007-03-21 23:19:50 +00003649 // Emit V-Lo >u Hi-1-Lo
3650 // Note that Hi has already had one subtracted from it, above.
3651 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Reid Spencer266e42b2006-12-23 06:05:41 +00003652 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
Chris Lattner6862fbd2004-09-29 17:40:11 +00003653 InsertNewInstBefore(Add, IB);
Reid Spencer266e42b2006-12-23 06:05:41 +00003654 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3655 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00003656}
3657
Chris Lattnerb4b25302005-09-18 07:22:02 +00003658// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3659// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3660// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3661// not, since all 1s are not contiguous.
Zhou Sheng56cda952007-04-02 08:20:41 +00003662static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng150f3bb2007-04-01 17:13:37 +00003663 const APInt& V = Val->getValue();
Reid Spencera962d182007-03-24 00:42:08 +00003664 uint32_t BitWidth = Val->getType()->getBitWidth();
3665 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattnerb4b25302005-09-18 07:22:02 +00003666
3667 // look for the first zero bit after the run of ones
Reid Spencera962d182007-03-24 00:42:08 +00003668 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattnerb4b25302005-09-18 07:22:02 +00003669 // look for the first non-zero bit
Reid Spencera962d182007-03-24 00:42:08 +00003670 ME = V.getActiveBits();
Chris Lattnerb4b25302005-09-18 07:22:02 +00003671 return true;
3672}
3673
Chris Lattnerb4b25302005-09-18 07:22:02 +00003674/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3675/// where isSub determines whether the operator is a sub. If we can fold one of
3676/// the following xforms:
Chris Lattneraf517572005-09-18 04:24:45 +00003677///
3678/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3679/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3680/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3681///
3682/// return (A +/- B).
3683///
3684Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng75b871f2007-01-11 12:24:14 +00003685 ConstantInt *Mask, bool isSub,
Chris Lattneraf517572005-09-18 04:24:45 +00003686 Instruction &I) {
3687 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3688 if (!LHSI || LHSI->getNumOperands() != 2 ||
3689 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3690
3691 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3692
3693 switch (LHSI->getOpcode()) {
3694 default: return 0;
3695 case Instruction::And:
Reid Spencer80263aa2007-03-25 05:33:51 +00003696 if (And(N, Mask) == Mask) {
Chris Lattnerb4b25302005-09-18 07:22:02 +00003697 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Shenge9ebd3f2007-03-24 15:34:37 +00003698 if ((Mask->getValue().countLeadingZeros() +
3699 Mask->getValue().countPopulation()) ==
3700 Mask->getValue().getBitWidth())
Chris Lattnerb4b25302005-09-18 07:22:02 +00003701 break;
3702
3703 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3704 // part, we don't need any explicit masks to take them out of A. If that
3705 // is all N is, ignore it.
Zhou Sheng56cda952007-04-02 08:20:41 +00003706 uint32_t MB = 0, ME = 0;
Chris Lattnerb4b25302005-09-18 07:22:02 +00003707 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencer6274c722007-03-23 18:46:34 +00003708 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Shengb3a80b12007-03-29 08:15:12 +00003709 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003710 if (MaskedValueIsZero(RHS, Mask))
Chris Lattnerb4b25302005-09-18 07:22:02 +00003711 break;
3712 }
3713 }
Chris Lattneraf517572005-09-18 04:24:45 +00003714 return 0;
3715 case Instruction::Or:
3716 case Instruction::Xor:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003717 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Shenge9ebd3f2007-03-24 15:34:37 +00003718 if ((Mask->getValue().countLeadingZeros() +
3719 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Reid Spencer54d5b1b2007-03-26 23:58:26 +00003720 && And(N, Mask)->isZero())
Chris Lattneraf517572005-09-18 04:24:45 +00003721 break;
3722 return 0;
3723 }
3724
3725 Instruction *New;
3726 if (isSub)
3727 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
3728 else
3729 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
3730 return InsertNewInstBefore(New, I);
3731}
3732
Chris Lattner113f4f42002-06-25 16:13:24 +00003733Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003734 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003735 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003736
Chris Lattner81a7a232004-10-16 18:11:37 +00003737 if (isa<UndefValue>(Op1)) // X & undef -> 0
3738 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3739
Chris Lattner86102b82005-01-01 16:22:27 +00003740 // and X, X = X
3741 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00003742 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003743
Chris Lattner5b2edb12006-02-12 08:02:11 +00003744 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner5997cf92006-02-08 03:25:32 +00003745 // purpose is to compute bits we don't care about.
Reid Spencerd84d35b2007-02-15 02:26:10 +00003746 if (!isa<VectorType>(I.getType())) {
Reid Spencerb722f2b2007-03-22 22:19:58 +00003747 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3748 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3749 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
Chris Lattner120ab032007-01-18 22:16:33 +00003750 KnownZero, KnownOne))
Reid Spencer54d5b1b2007-03-26 23:58:26 +00003751 return &I;
Chris Lattner120ab032007-01-18 22:16:33 +00003752 } else {
Reid Spencerd84d35b2007-02-15 02:26:10 +00003753 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
Chris Lattnerf14e5172007-06-15 05:26:55 +00003754 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
Chris Lattner120ab032007-01-18 22:16:33 +00003755 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattnerf14e5172007-06-15 05:26:55 +00003756 } else if (isa<ConstantAggregateZero>(Op1)) {
3757 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
Chris Lattner120ab032007-01-18 22:16:33 +00003758 }
3759 }
Chris Lattner5997cf92006-02-08 03:25:32 +00003760
Zhou Sheng75b871f2007-01-11 12:24:14 +00003761 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Zhou Sheng150f3bb2007-04-01 17:13:37 +00003762 const APInt& AndRHSMask = AndRHS->getValue();
3763 APInt NotAndRHS(~AndRHSMask);
Chris Lattner86102b82005-01-01 16:22:27 +00003764
Chris Lattnerba1cb382003-09-19 17:17:26 +00003765 // Optimize a variety of ((val OP C1) & C2) combinations...
Reid Spencer2341c222007-02-02 02:16:23 +00003766 if (isa<BinaryOperator>(Op0)) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00003767 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner86102b82005-01-01 16:22:27 +00003768 Value *Op0LHS = Op0I->getOperand(0);
3769 Value *Op0RHS = Op0I->getOperand(1);
3770 switch (Op0I->getOpcode()) {
3771 case Instruction::Xor:
3772 case Instruction::Or:
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00003773 // If the mask is only needed on one incoming arm, push it up.
3774 if (Op0I->hasOneUse()) {
3775 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3776 // Not masking anything out for the LHS, move to RHS.
3777 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
3778 Op0RHS->getName()+".masked");
3779 InsertNewInstBefore(NewRHS, I);
3780 return BinaryOperator::create(
3781 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003782 }
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003783 if (!isa<Constant>(Op0RHS) &&
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00003784 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3785 // Not masking anything out for the RHS, move to LHS.
3786 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
3787 Op0LHS->getName()+".masked");
3788 InsertNewInstBefore(NewLHS, I);
3789 return BinaryOperator::create(
3790 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3791 }
3792 }
3793
Chris Lattner86102b82005-01-01 16:22:27 +00003794 break;
Chris Lattneraf517572005-09-18 04:24:45 +00003795 case Instruction::Add:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003796 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3797 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3798 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3799 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3800 return BinaryOperator::createAnd(V, AndRHS);
3801 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3802 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
Chris Lattneraf517572005-09-18 04:24:45 +00003803 break;
3804
3805 case Instruction::Sub:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003806 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3807 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3808 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3809 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3810 return BinaryOperator::createAnd(V, AndRHS);
Chris Lattneraf517572005-09-18 04:24:45 +00003811 break;
Chris Lattner86102b82005-01-01 16:22:27 +00003812 }
3813
Chris Lattner16464b32003-07-23 19:25:52 +00003814 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner86102b82005-01-01 16:22:27 +00003815 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerba1cb382003-09-19 17:17:26 +00003816 return Res;
Chris Lattner86102b82005-01-01 16:22:27 +00003817 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2c14cf72005-08-07 07:03:10 +00003818 // If this is an integer truncation or change from signed-to-unsigned, and
3819 // if the source is an and/or with immediate, transform it. This
3820 // frequently occurs for bitfield accesses.
3821 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003822 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2c14cf72005-08-07 07:03:10 +00003823 CastOp->getNumOperands() == 2)
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +00003824 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
Chris Lattner2c14cf72005-08-07 07:03:10 +00003825 if (CastOp->getOpcode() == Instruction::And) {
3826 // Change: and (cast (and X, C1) to T), C2
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003827 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
3828 // This will fold the two constants together, which may allow
3829 // other simplifications.
Reid Spencerbb65ebf2006-12-12 23:36:14 +00003830 Instruction *NewCast = CastInst::createTruncOrBitCast(
3831 CastOp->getOperand(0), I.getType(),
3832 CastOp->getName()+".shrunk");
Chris Lattner2c14cf72005-08-07 07:03:10 +00003833 NewCast = InsertNewInstBefore(NewCast, I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003834 // trunc_or_bitcast(C1)&C2
Reid Spencerbb65ebf2006-12-12 23:36:14 +00003835 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003836 C3 = ConstantExpr::getAnd(C3, AndRHS);
Chris Lattner2c14cf72005-08-07 07:03:10 +00003837 return BinaryOperator::createAnd(NewCast, C3);
3838 } else if (CastOp->getOpcode() == Instruction::Or) {
3839 // Change: and (cast (or X, C1) to T), C2
3840 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattner2dc148e2006-12-12 19:11:20 +00003841 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Chris Lattner2c14cf72005-08-07 07:03:10 +00003842 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3843 return ReplaceInstUsesWith(I, AndRHS);
3844 }
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +00003845 }
Chris Lattner2c14cf72005-08-07 07:03:10 +00003846 }
Chris Lattner33217db2003-07-23 19:36:21 +00003847 }
Chris Lattner183b3362004-04-09 19:05:30 +00003848
3849 // Try to fold constant and into select arguments.
3850 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003851 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003852 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003853 if (isa<PHINode>(Op0))
3854 if (Instruction *NV = FoldOpIntoPhi(I))
3855 return NV;
Chris Lattner49b47ae2003-07-23 17:57:01 +00003856 }
3857
Chris Lattnerbb74e222003-03-10 23:06:50 +00003858 Value *Op0NotVal = dyn_castNotVal(Op0);
3859 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00003860
Chris Lattner023a4832004-06-18 06:07:51 +00003861 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3862 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3863
Misha Brukman9c003d82004-07-30 12:50:08 +00003864 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerbb74e222003-03-10 23:06:50 +00003865 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003866 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
3867 I.getName()+".demorgan");
Chris Lattner49b47ae2003-07-23 17:57:01 +00003868 InsertNewInstBefore(Or, I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00003869 return BinaryOperator::createNot(Or);
3870 }
Chris Lattner8b10ab32006-02-13 23:07:23 +00003871
3872 {
Chris Lattner481e28b2007-06-15 05:58:24 +00003873 Value *A = 0, *B = 0, *C = 0, *D = 0;
3874 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner8b10ab32006-02-13 23:07:23 +00003875 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3876 return ReplaceInstUsesWith(I, Op1);
Chris Lattner481e28b2007-06-15 05:58:24 +00003877
3878 // (A|B) & ~(A&B) -> A^B
3879 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
3880 if ((A == C && B == D) || (A == D && B == C))
3881 return BinaryOperator::createXor(A, B);
3882 }
3883 }
3884
3885 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner8b10ab32006-02-13 23:07:23 +00003886 if (A == Op0 || B == Op0) // A & (A | ?) --> A
3887 return ReplaceInstUsesWith(I, Op0);
Chris Lattner481e28b2007-06-15 05:58:24 +00003888
3889 // ~(A&B) & (A|B) -> A^B
3890 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
3891 if ((A == C && B == D) || (A == D && B == C))
3892 return BinaryOperator::createXor(A, B);
3893 }
3894 }
Chris Lattnerdcd07922006-04-01 08:03:55 +00003895
3896 if (Op0->hasOneUse() &&
3897 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3898 if (A == Op1) { // (A^B)&A -> A&(A^B)
3899 I.swapOperands(); // Simplify below
3900 std::swap(Op0, Op1);
3901 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
3902 cast<BinaryOperator>(Op0)->swapOperands();
3903 I.swapOperands(); // Simplify below
3904 std::swap(Op0, Op1);
3905 }
3906 }
3907 if (Op1->hasOneUse() &&
3908 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3909 if (B == Op0) { // B&(A^B) -> B&(B^A)
3910 cast<BinaryOperator>(Op1)->swapOperands();
3911 std::swap(A, B);
3912 }
3913 if (A == Op0) { // A&(A^B) -> A & ~B
3914 Instruction *NotB = BinaryOperator::createNot(B, "tmp");
3915 InsertNewInstBefore(NotB, I);
3916 return BinaryOperator::createAnd(A, NotB);
3917 }
3918 }
Chris Lattner8b10ab32006-02-13 23:07:23 +00003919 }
3920
Reid Spencer266e42b2006-12-23 06:05:41 +00003921 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3922 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3923 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattner3ac7c262003-08-13 20:16:26 +00003924 return R;
3925
Chris Lattner623826c2004-09-28 21:48:02 +00003926 Value *LHSVal, *RHSVal;
3927 ConstantInt *LHSCst, *RHSCst;
Reid Spencer266e42b2006-12-23 06:05:41 +00003928 ICmpInst::Predicate LHSCC, RHSCC;
3929 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3930 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3931 if (LHSVal == RHSVal && // Found (X icmp C1) & (X icmp C2)
3932 // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3933 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3934 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3935 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
Chris Lattner1985d962007-11-22 23:47:13 +00003936 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
3937
3938 // Don't try to fold ICMP_SLT + ICMP_ULT.
3939 (ICmpInst::isEquality(LHSCC) || ICmpInst::isEquality(RHSCC) ||
3940 ICmpInst::isSignedPredicate(LHSCC) ==
3941 ICmpInst::isSignedPredicate(RHSCC))) {
Chris Lattner623826c2004-09-28 21:48:02 +00003942 // Ensure that the larger constant is on the RHS.
Chris Lattner5bc253c2008-01-13 20:59:02 +00003943 ICmpInst::Predicate GT;
3944 if (ICmpInst::isSignedPredicate(LHSCC) ||
3945 (ICmpInst::isEquality(LHSCC) &&
3946 ICmpInst::isSignedPredicate(RHSCC)))
3947 GT = ICmpInst::ICMP_SGT;
3948 else
3949 GT = ICmpInst::ICMP_UGT;
3950
Reid Spencer266e42b2006-12-23 06:05:41 +00003951 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3952 ICmpInst *LHS = cast<ICmpInst>(Op0);
Reid Spencercddc9df2007-01-12 04:24:46 +00003953 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
Chris Lattner623826c2004-09-28 21:48:02 +00003954 std::swap(LHS, RHS);
3955 std::swap(LHSCst, RHSCst);
3956 std::swap(LHSCC, RHSCC);
3957 }
3958
Reid Spencer266e42b2006-12-23 06:05:41 +00003959 // At this point, we know we have have two icmp instructions
Chris Lattner623826c2004-09-28 21:48:02 +00003960 // comparing a value against two constants and and'ing the result
3961 // together. Because of the above check, we know that we only have
Reid Spencer266e42b2006-12-23 06:05:41 +00003962 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3963 // (from the FoldICmpLogical check above), that the two constants
3964 // are not equal and that the larger constant is on the RHS
Chris Lattner623826c2004-09-28 21:48:02 +00003965 assert(LHSCst != RHSCst && "Compares not folded above?");
3966
3967 switch (LHSCC) {
3968 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003969 case ICmpInst::ICMP_EQ:
Chris Lattner623826c2004-09-28 21:48:02 +00003970 switch (RHSCC) {
3971 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003972 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3973 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3974 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Zhou Sheng75b871f2007-01-11 12:24:14 +00003975 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00003976 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3977 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3978 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
Chris Lattner623826c2004-09-28 21:48:02 +00003979 return ReplaceInstUsesWith(I, LHS);
3980 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003981 case ICmpInst::ICMP_NE:
Chris Lattner623826c2004-09-28 21:48:02 +00003982 switch (RHSCC) {
3983 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003984 case ICmpInst::ICMP_ULT:
3985 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3986 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
3987 break; // (X != 13 & X u< 15) -> no change
3988 case ICmpInst::ICMP_SLT:
3989 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3990 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
3991 break; // (X != 13 & X s< 15) -> no change
3992 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3993 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3994 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
Chris Lattner623826c2004-09-28 21:48:02 +00003995 return ReplaceInstUsesWith(I, RHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003996 case ICmpInst::ICMP_NE:
3997 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Chris Lattner623826c2004-09-28 21:48:02 +00003998 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3999 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
4000 LHSVal->getName()+".off");
4001 InsertNewInstBefore(Add, I);
Chris Lattnerc8fb6de2007-01-27 23:08:34 +00004002 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
4003 ConstantInt::get(Add->getType(), 1));
Chris Lattner623826c2004-09-28 21:48:02 +00004004 }
4005 break; // (X != 13 & X != 15) -> no change
4006 }
4007 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00004008 case ICmpInst::ICMP_ULT:
Chris Lattner623826c2004-09-28 21:48:02 +00004009 switch (RHSCC) {
4010 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00004011 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
4012 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Zhou Sheng75b871f2007-01-11 12:24:14 +00004013 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004014 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
4015 break;
4016 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
4017 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
Chris Lattner623826c2004-09-28 21:48:02 +00004018 return ReplaceInstUsesWith(I, LHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00004019 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
4020 break;
Chris Lattner623826c2004-09-28 21:48:02 +00004021 }
Reid Spencer266e42b2006-12-23 06:05:41 +00004022 break;
4023 case ICmpInst::ICMP_SLT:
Chris Lattner623826c2004-09-28 21:48:02 +00004024 switch (RHSCC) {
4025 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00004026 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
4027 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Zhou Sheng75b871f2007-01-11 12:24:14 +00004028 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004029 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
4030 break;
4031 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
4032 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
Chris Lattner623826c2004-09-28 21:48:02 +00004033 return ReplaceInstUsesWith(I, LHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00004034 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
4035 break;
Chris Lattner623826c2004-09-28 21:48:02 +00004036 }
Reid Spencer266e42b2006-12-23 06:05:41 +00004037 break;
4038 case ICmpInst::ICMP_UGT:
4039 switch (RHSCC) {
4040 default: assert(0 && "Unknown integer condition code!");
4041 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X > 13
4042 return ReplaceInstUsesWith(I, LHS);
4043 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
4044 return ReplaceInstUsesWith(I, RHS);
4045 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
4046 break;
4047 case ICmpInst::ICMP_NE:
4048 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
4049 return new ICmpInst(LHSCC, LHSVal, RHSCst);
4050 break; // (X u> 13 & X != 15) -> no change
4051 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) ->(X-14) <u 1
4052 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false,
4053 true, I);
4054 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
4055 break;
4056 }
4057 break;
4058 case ICmpInst::ICMP_SGT:
4059 switch (RHSCC) {
4060 default: assert(0 && "Unknown integer condition code!");
Chris Lattnerc53b1832007-11-16 06:04:17 +00004061 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
Reid Spencer266e42b2006-12-23 06:05:41 +00004062 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
4063 return ReplaceInstUsesWith(I, RHS);
4064 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
4065 break;
4066 case ICmpInst::ICMP_NE:
4067 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
4068 return new ICmpInst(LHSCC, LHSVal, RHSCst);
4069 break; // (X s> 13 & X != 15) -> no change
4070 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) ->(X-14) s< 1
4071 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true,
4072 true, I);
4073 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
4074 break;
4075 }
4076 break;
Chris Lattner623826c2004-09-28 21:48:02 +00004077 }
4078 }
4079 }
4080
Chris Lattner3af10532006-05-05 06:39:07 +00004081 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer799b5bf2006-12-13 08:27:15 +00004082 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4083 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4084 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4085 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner03c49532007-01-15 02:27:26 +00004086 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer799b5bf2006-12-13 08:27:15 +00004087 // Only do this if the casts both really cause code to be generated.
Reid Spencer266e42b2006-12-23 06:05:41 +00004088 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4089 I.getType(), TD) &&
4090 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4091 I.getType(), TD)) {
Reid Spencer799b5bf2006-12-13 08:27:15 +00004092 Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
4093 Op1C->getOperand(0),
4094 I.getName());
4095 InsertNewInstBefore(NewOp, I);
4096 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4097 }
Chris Lattner3af10532006-05-05 06:39:07 +00004098 }
Chris Lattnerf05d69a2006-11-14 07:46:50 +00004099
4100 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer2341c222007-02-02 02:16:23 +00004101 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4102 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4103 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnerf05d69a2006-11-14 07:46:50 +00004104 SI0->getOperand(1) == SI1->getOperand(1) &&
4105 (SI0->hasOneUse() || SI1->hasOneUse())) {
4106 Instruction *NewOp =
4107 InsertNewInstBefore(BinaryOperator::createAnd(SI0->getOperand(0),
4108 SI1->getOperand(0),
4109 SI0->getName()), I);
Reid Spencer2341c222007-02-02 02:16:23 +00004110 return BinaryOperator::create(SI1->getOpcode(), NewOp,
4111 SI1->getOperand(1));
Chris Lattnerf05d69a2006-11-14 07:46:50 +00004112 }
Chris Lattner3af10532006-05-05 06:39:07 +00004113 }
4114
Chris Lattnerc62877e2007-10-24 05:38:08 +00004115 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
4116 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4117 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4118 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
4119 RHS->getPredicate() == FCmpInst::FCMP_ORD)
4120 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4121 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4122 // If either of the constants are nans, then the whole thing returns
4123 // false.
Chris Lattner55b83022007-10-24 18:54:45 +00004124 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattnerc62877e2007-10-24 05:38:08 +00004125 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4126 return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
4127 RHS->getOperand(0));
4128 }
4129 }
4130 }
4131
Chris Lattner113f4f42002-06-25 16:13:24 +00004132 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004133}
4134
Chris Lattnerc482a9e2006-06-15 19:07:26 +00004135/// CollectBSwapParts - Look to see if the specified value defines a single byte
4136/// in the result. If it does, and if the specified byte hasn't been filled in
4137/// yet, fill it in and return false.
Chris Lattner99c6cf62007-02-15 22:52:10 +00004138static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
Chris Lattnerc482a9e2006-06-15 19:07:26 +00004139 Instruction *I = dyn_cast<Instruction>(V);
4140 if (I == 0) return true;
4141
4142 // If this is an or instruction, it is an inner node of the bswap.
4143 if (I->getOpcode() == Instruction::Or)
4144 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
4145 CollectBSwapParts(I->getOperand(1), ByteValues);
4146
Zhou Shengb25806f2007-03-30 09:29:48 +00004147 uint32_t BitWidth = I->getType()->getPrimitiveSizeInBits();
Chris Lattnerc482a9e2006-06-15 19:07:26 +00004148 // If this is a shift by a constant int, and it is "24", then its operand
4149 // defines a byte. We only handle unsigned types here.
Reid Spencer2341c222007-02-02 02:16:23 +00004150 if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
Chris Lattnerc482a9e2006-06-15 19:07:26 +00004151 // Not shifting the entire input by N-1 bytes?
Zhou Shengb25806f2007-03-30 09:29:48 +00004152 if (cast<ConstantInt>(I->getOperand(1))->getLimitedValue(BitWidth) !=
Chris Lattnerc482a9e2006-06-15 19:07:26 +00004153 8*(ByteValues.size()-1))
4154 return true;
4155
4156 unsigned DestNo;
4157 if (I->getOpcode() == Instruction::Shl) {
4158 // X << 24 defines the top byte with the lowest of the input bytes.
4159 DestNo = ByteValues.size()-1;
4160 } else {
4161 // X >>u 24 defines the low byte with the highest of the input bytes.
4162 DestNo = 0;
4163 }
4164
4165 // If the destination byte value is already defined, the values are or'd
4166 // together, which isn't a bswap (unless it's an or of the same bits).
4167 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
4168 return true;
4169 ByteValues[DestNo] = I->getOperand(0);
4170 return false;
4171 }
4172
4173 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
4174 // don't have this.
4175 Value *Shift = 0, *ShiftLHS = 0;
4176 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
4177 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
4178 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
4179 return true;
4180 Instruction *SI = cast<Instruction>(Shift);
4181
4182 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
Zhou Shengb25806f2007-03-30 09:29:48 +00004183 if (ShiftAmt->getLimitedValue(BitWidth) & 7 ||
4184 ShiftAmt->getLimitedValue(BitWidth) > 8*ByteValues.size())
Chris Lattnerc482a9e2006-06-15 19:07:26 +00004185 return true;
4186
4187 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
4188 unsigned DestByte;
Zhou Shengb25806f2007-03-30 09:29:48 +00004189 if (AndAmt->getValue().getActiveBits() > 64)
4190 return true;
4191 uint64_t AndAmtVal = AndAmt->getZExtValue();
Chris Lattnerc482a9e2006-06-15 19:07:26 +00004192 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
Zhou Shengb25806f2007-03-30 09:29:48 +00004193 if (AndAmtVal == uint64_t(0xFF) << 8*DestByte)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00004194 break;
4195 // Unknown mask for bswap.
4196 if (DestByte == ByteValues.size()) return true;
4197
Reid Spencere0fc4df2006-10-20 07:07:24 +00004198 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
Chris Lattnerc482a9e2006-06-15 19:07:26 +00004199 unsigned SrcByte;
4200 if (SI->getOpcode() == Instruction::Shl)
4201 SrcByte = DestByte - ShiftBytes;
4202 else
4203 SrcByte = DestByte + ShiftBytes;
4204
4205 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
4206 if (SrcByte != ByteValues.size()-DestByte-1)
4207 return true;
4208
4209 // If the destination byte value is already defined, the values are or'd
4210 // together, which isn't a bswap (unless it's an or of the same bits).
4211 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
4212 return true;
4213 ByteValues[DestByte] = SI->getOperand(0);
4214 return false;
4215}
4216
4217/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4218/// If so, insert the new bswap intrinsic and return it.
4219Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattnerc3eeb422007-04-01 20:57:36 +00004220 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
4221 if (!ITy || ITy->getBitWidth() % 16)
4222 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerc482a9e2006-06-15 19:07:26 +00004223
4224 /// ByteValues - For each byte of the result, we keep track of which value
4225 /// defines each byte.
Chris Lattner99c6cf62007-02-15 22:52:10 +00004226 SmallVector<Value*, 8> ByteValues;
Chris Lattnerc3eeb422007-04-01 20:57:36 +00004227 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerc482a9e2006-06-15 19:07:26 +00004228
4229 // Try to find all the pieces corresponding to the bswap.
4230 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
4231 CollectBSwapParts(I.getOperand(1), ByteValues))
4232 return 0;
4233
4234 // Check to see if all of the bytes come from the same value.
4235 Value *V = ByteValues[0];
4236 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4237
4238 // Check to make sure that all of the bytes come from the same value.
4239 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4240 if (ByteValues[i] != V)
4241 return 0;
Chandler Carruth7132e002007-08-04 01:51:18 +00004242 const Type *Tys[] = { ITy };
Chris Lattnerc482a9e2006-06-15 19:07:26 +00004243 Module *M = I.getParent()->getParent()->getParent();
Chandler Carruth7132e002007-08-04 01:51:18 +00004244 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greife9ecc682008-04-06 20:25:17 +00004245 return CallInst::Create(F, V);
Chris Lattnerc482a9e2006-06-15 19:07:26 +00004246}
4247
4248
Chris Lattner113f4f42002-06-25 16:13:24 +00004249Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00004250 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00004251 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004252
Chris Lattner3a8248f2007-03-24 23:56:43 +00004253 if (isa<UndefValue>(Op1)) // X | undef -> -1
Chris Lattner37338922007-06-15 06:23:19 +00004254 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattner81a7a232004-10-16 18:11:37 +00004255
Chris Lattner5b2edb12006-02-12 08:02:11 +00004256 // or X, X = X
4257 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00004258 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004259
Chris Lattner5b2edb12006-02-12 08:02:11 +00004260 // See if we can simplify any instructions used by the instruction whose sole
4261 // purpose is to compute bits we don't care about.
Chris Lattner3a8248f2007-03-24 23:56:43 +00004262 if (!isa<VectorType>(I.getType())) {
4263 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4264 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4265 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4266 KnownZero, KnownOne))
4267 return &I;
Chris Lattnerf14e5172007-06-15 05:26:55 +00004268 } else if (isa<ConstantAggregateZero>(Op1)) {
4269 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4270 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4271 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4272 return ReplaceInstUsesWith(I, I.getOperand(1));
Chris Lattner3a8248f2007-03-24 23:56:43 +00004273 }
Chris Lattnerf14e5172007-06-15 05:26:55 +00004274
4275
Chris Lattner5b2edb12006-02-12 08:02:11 +00004276
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004277 // or X, -1 == -1
Zhou Sheng75b871f2007-01-11 12:24:14 +00004278 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner330628a2006-01-06 17:59:59 +00004279 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00004280 // (X & C1) | C2 --> (X | C2) & (C1|C2)
4281 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattner6e0123b2007-02-11 01:23:03 +00004282 Instruction *Or = BinaryOperator::createOr(X, RHS);
Chris Lattnerd4252a72004-07-30 07:50:03 +00004283 InsertNewInstBefore(Or, I);
Chris Lattner6e0123b2007-02-11 01:23:03 +00004284 Or->takeName(Op0);
Zhou Sheng9bc8ab12007-04-02 13:45:30 +00004285 return BinaryOperator::createAnd(Or,
4286 ConstantInt::get(RHS->getValue() | C1->getValue()));
Chris Lattnerd4252a72004-07-30 07:50:03 +00004287 }
Chris Lattner8f0d1562003-07-23 18:29:44 +00004288
Chris Lattnerd4252a72004-07-30 07:50:03 +00004289 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4290 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattner6e0123b2007-02-11 01:23:03 +00004291 Instruction *Or = BinaryOperator::createOr(X, RHS);
Chris Lattnerd4252a72004-07-30 07:50:03 +00004292 InsertNewInstBefore(Or, I);
Chris Lattner6e0123b2007-02-11 01:23:03 +00004293 Or->takeName(Op0);
Chris Lattnerd4252a72004-07-30 07:50:03 +00004294 return BinaryOperator::createXor(Or,
Zhou Sheng9bc8ab12007-04-02 13:45:30 +00004295 ConstantInt::get(C1->getValue() & ~RHS->getValue()));
Chris Lattner8f0d1562003-07-23 18:29:44 +00004296 }
Chris Lattner183b3362004-04-09 19:05:30 +00004297
4298 // Try to fold constant and into select arguments.
4299 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00004300 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00004301 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00004302 if (isa<PHINode>(Op0))
4303 if (Instruction *NV = FoldOpIntoPhi(I))
4304 return NV;
Chris Lattner8f0d1562003-07-23 18:29:44 +00004305 }
4306
Chris Lattner330628a2006-01-06 17:59:59 +00004307 Value *A = 0, *B = 0;
4308 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattner4294cec2005-05-07 23:49:08 +00004309
4310 if (match(Op0, m_And(m_Value(A), m_Value(B))))
4311 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4312 return ReplaceInstUsesWith(I, Op1);
4313 if (match(Op1, m_And(m_Value(A), m_Value(B))))
4314 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4315 return ReplaceInstUsesWith(I, Op0);
4316
Chris Lattnerb7845d62006-07-10 20:25:24 +00004317 // (A | B) | C and A | (B | C) -> bswap if possible.
4318 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Chris Lattnerc482a9e2006-06-15 19:07:26 +00004319 if (match(Op0, m_Or(m_Value(), m_Value())) ||
Chris Lattnerb7845d62006-07-10 20:25:24 +00004320 match(Op1, m_Or(m_Value(), m_Value())) ||
4321 (match(Op0, m_Shift(m_Value(), m_Value())) &&
4322 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerc482a9e2006-06-15 19:07:26 +00004323 if (Instruction *BSwap = MatchBSwap(I))
4324 return BSwap;
4325 }
4326
Chris Lattnerb62f5082005-05-09 04:58:36 +00004327 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4328 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencerb722f2b2007-03-22 22:19:58 +00004329 MaskedValueIsZero(Op1, C1->getValue())) {
Chris Lattner6e0123b2007-02-11 01:23:03 +00004330 Instruction *NOr = BinaryOperator::createOr(A, Op1);
4331 InsertNewInstBefore(NOr, I);
4332 NOr->takeName(Op0);
4333 return BinaryOperator::createXor(NOr, C1);
Chris Lattnerb62f5082005-05-09 04:58:36 +00004334 }
4335
4336 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4337 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencerb722f2b2007-03-22 22:19:58 +00004338 MaskedValueIsZero(Op0, C1->getValue())) {
Chris Lattner6e0123b2007-02-11 01:23:03 +00004339 Instruction *NOr = BinaryOperator::createOr(A, Op0);
4340 InsertNewInstBefore(NOr, I);
4341 NOr->takeName(Op0);
4342 return BinaryOperator::createXor(NOr, C1);
Chris Lattnerb62f5082005-05-09 04:58:36 +00004343 }
4344
Chris Lattner1150df92007-04-08 07:47:01 +00004345 // (A & C)|(B & D)
Chris Lattner09a33a42007-06-19 05:43:49 +00004346 Value *C = 0, *D = 0;
Chris Lattner1150df92007-04-08 07:47:01 +00004347 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4348 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Chris Lattner7621a032007-04-08 07:55:22 +00004349 Value *V1 = 0, *V2 = 0, *V3 = 0;
4350 C1 = dyn_cast<ConstantInt>(C);
4351 C2 = dyn_cast<ConstantInt>(D);
4352 if (C1 && C2) { // (A & C1)|(B & C2)
4353 // If we have: ((V + N) & C1) | (V & C2)
4354 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4355 // replace with V+N.
4356 if (C1->getValue() == ~C2->getValue()) {
4357 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4358 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4359 // Add commutes, try both ways.
4360 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4361 return ReplaceInstUsesWith(I, A);
4362 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4363 return ReplaceInstUsesWith(I, A);
4364 }
4365 // Or commutes, try both ways.
4366 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4367 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4368 // Add commutes, try both ways.
4369 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4370 return ReplaceInstUsesWith(I, B);
4371 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4372 return ReplaceInstUsesWith(I, B);
4373 }
4374 }
Chris Lattnerc8d37882007-04-08 08:01:49 +00004375 V1 = 0; V2 = 0; V3 = 0;
Chris Lattner7621a032007-04-08 07:55:22 +00004376 }
4377
Chris Lattner1150df92007-04-08 07:47:01 +00004378 // Check to see if we have any common things being and'ed. If so, find the
4379 // terms for V1 & (V2|V3).
Chris Lattner1150df92007-04-08 07:47:01 +00004380 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4381 if (A == B) // (A & C)|(A & D) == A & (C|D)
4382 V1 = A, V2 = C, V3 = D;
4383 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4384 V1 = A, V2 = B, V3 = C;
4385 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4386 V1 = C, V2 = A, V3 = D;
4387 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4388 V1 = C, V2 = A, V3 = B;
4389
4390 if (V1) {
4391 Value *Or =
4392 InsertNewInstBefore(BinaryOperator::createOr(V2, V3, "tmp"), I);
4393 return BinaryOperator::createAnd(V1, Or);
Chris Lattner01f56c62005-09-18 06:02:59 +00004394 }
Chris Lattner1150df92007-04-08 07:47:01 +00004395 }
Chris Lattner15212982005-09-18 03:42:07 +00004396 }
Chris Lattnerf05d69a2006-11-14 07:46:50 +00004397
4398 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer2341c222007-02-02 02:16:23 +00004399 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4400 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4401 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnerf05d69a2006-11-14 07:46:50 +00004402 SI0->getOperand(1) == SI1->getOperand(1) &&
4403 (SI0->hasOneUse() || SI1->hasOneUse())) {
4404 Instruction *NewOp =
4405 InsertNewInstBefore(BinaryOperator::createOr(SI0->getOperand(0),
4406 SI1->getOperand(0),
4407 SI0->getName()), I);
Reid Spencer2341c222007-02-02 02:16:23 +00004408 return BinaryOperator::create(SI1->getOpcode(), NewOp,
4409 SI1->getOperand(1));
Chris Lattnerf05d69a2006-11-14 07:46:50 +00004410 }
4411 }
Chris Lattner812aab72003-08-12 19:11:07 +00004412
Chris Lattnerd4252a72004-07-30 07:50:03 +00004413 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
4414 if (A == Op1) // ~A | A == -1
Chris Lattner37338922007-06-15 06:23:19 +00004415 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnerd4252a72004-07-30 07:50:03 +00004416 } else {
4417 A = 0;
4418 }
Chris Lattner4294cec2005-05-07 23:49:08 +00004419 // Note, A is still live here!
Chris Lattnerd4252a72004-07-30 07:50:03 +00004420 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
4421 if (Op0 == B)
Chris Lattner37338922007-06-15 06:23:19 +00004422 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattner3e327a42003-03-10 23:13:59 +00004423
Misha Brukman9c003d82004-07-30 12:50:08 +00004424 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattnerd4252a72004-07-30 07:50:03 +00004425 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4426 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
4427 I.getName()+".demorgan"), I);
4428 return BinaryOperator::createNot(And);
4429 }
Chris Lattner3e327a42003-03-10 23:13:59 +00004430 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00004431
Reid Spencer266e42b2006-12-23 06:05:41 +00004432 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4433 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4434 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattner3ac7c262003-08-13 20:16:26 +00004435 return R;
4436
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004437 Value *LHSVal, *RHSVal;
4438 ConstantInt *LHSCst, *RHSCst;
Reid Spencer266e42b2006-12-23 06:05:41 +00004439 ICmpInst::Predicate LHSCC, RHSCC;
4440 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
4441 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
4442 if (LHSVal == RHSVal && // Found (X icmp C1) | (X icmp C2)
4443 // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
4444 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
4445 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
4446 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
Chris Lattnerfe2b44d2007-05-11 05:55:56 +00004447 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
4448 // We can't fold (ugt x, C) | (sgt x, C2).
4449 PredicatesFoldable(LHSCC, RHSCC)) {
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004450 // Ensure that the larger constant is on the RHS.
Reid Spencer266e42b2006-12-23 06:05:41 +00004451 ICmpInst *LHS = cast<ICmpInst>(Op0);
Chris Lattnerfe2b44d2007-05-11 05:55:56 +00004452 bool NeedsSwap;
4453 if (ICmpInst::isSignedPredicate(LHSCC))
Chris Lattner600db3e2007-05-11 16:58:45 +00004454 NeedsSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattnerfe2b44d2007-05-11 05:55:56 +00004455 else
Chris Lattner600db3e2007-05-11 16:58:45 +00004456 NeedsSwap = LHSCst->getValue().ugt(RHSCst->getValue());
Chris Lattnerfe2b44d2007-05-11 05:55:56 +00004457
4458 if (NeedsSwap) {
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004459 std::swap(LHS, RHS);
4460 std::swap(LHSCst, RHSCst);
4461 std::swap(LHSCC, RHSCC);
4462 }
4463
Reid Spencer266e42b2006-12-23 06:05:41 +00004464 // At this point, we know we have have two icmp instructions
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004465 // comparing a value against two constants and or'ing the result
4466 // together. Because of the above check, we know that we only have
Reid Spencer266e42b2006-12-23 06:05:41 +00004467 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4468 // FoldICmpLogical check above), that the two constants are not
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004469 // equal.
4470 assert(LHSCst != RHSCst && "Compares not folded above?");
4471
4472 switch (LHSCC) {
4473 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00004474 case ICmpInst::ICMP_EQ:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004475 switch (RHSCC) {
4476 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00004477 case ICmpInst::ICMP_EQ:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004478 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
4479 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4480 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
4481 LHSVal->getName()+".off");
4482 InsertNewInstBefore(Add, I);
Zhou Sheng9bc8ab12007-04-02 13:45:30 +00004483 AddCST = Subtract(AddOne(RHSCst), LHSCst);
Reid Spencer266e42b2006-12-23 06:05:41 +00004484 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004485 }
Reid Spencer266e42b2006-12-23 06:05:41 +00004486 break; // (X == 13 | X == 15) -> no change
4487 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4488 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
Chris Lattner5c219462005-04-19 06:04:18 +00004489 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00004490 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4491 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4492 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004493 return ReplaceInstUsesWith(I, RHS);
4494 }
4495 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00004496 case ICmpInst::ICMP_NE:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004497 switch (RHSCC) {
4498 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00004499 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4500 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4501 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004502 return ReplaceInstUsesWith(I, LHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00004503 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4504 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4505 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Zhou Sheng75b871f2007-01-11 12:24:14 +00004506 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004507 }
4508 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00004509 case ICmpInst::ICMP_ULT:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004510 switch (RHSCC) {
4511 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00004512 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004513 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00004514 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) ->(X-13) u> 2
Chris Lattner74709472007-11-01 02:18:41 +00004515 // If RHSCst is [us]MAXINT, it is always false. Not handling
4516 // this can cause overflow.
4517 if (RHSCst->isMaxValue(false))
4518 return ReplaceInstUsesWith(I, LHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00004519 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false,
4520 false, I);
4521 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4522 break;
4523 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4524 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004525 return ReplaceInstUsesWith(I, RHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00004526 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4527 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004528 }
4529 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00004530 case ICmpInst::ICMP_SLT:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004531 switch (RHSCC) {
4532 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00004533 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4534 break;
4535 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) ->(X-13) s> 2
Chris Lattner74709472007-11-01 02:18:41 +00004536 // If RHSCst is [us]MAXINT, it is always false. Not handling
4537 // this can cause overflow.
4538 if (RHSCst->isMaxValue(true))
4539 return ReplaceInstUsesWith(I, LHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00004540 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true,
4541 false, I);
4542 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4543 break;
4544 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4545 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4546 return ReplaceInstUsesWith(I, RHS);
4547 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4548 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004549 }
Reid Spencer266e42b2006-12-23 06:05:41 +00004550 break;
4551 case ICmpInst::ICMP_UGT:
4552 switch (RHSCC) {
4553 default: assert(0 && "Unknown integer condition code!");
4554 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4555 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4556 return ReplaceInstUsesWith(I, LHS);
4557 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4558 break;
4559 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4560 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Zhou Sheng75b871f2007-01-11 12:24:14 +00004561 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004562 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4563 break;
4564 }
4565 break;
4566 case ICmpInst::ICMP_SGT:
4567 switch (RHSCC) {
4568 default: assert(0 && "Unknown integer condition code!");
4569 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4570 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4571 return ReplaceInstUsesWith(I, LHS);
4572 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4573 break;
4574 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4575 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Zhou Sheng75b871f2007-01-11 12:24:14 +00004576 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004577 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4578 break;
4579 }
4580 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004581 }
4582 }
4583 }
Chris Lattner3af10532006-05-05 06:39:07 +00004584
4585 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattnerc62877e2007-10-24 05:38:08 +00004586 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner3af10532006-05-05 06:39:07 +00004587 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer799b5bf2006-12-13 08:27:15 +00004588 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chengc3cf9f82008-03-24 00:21:34 +00004589 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4590 !isa<ICmpInst>(Op1C->getOperand(0))) {
4591 const Type *SrcTy = Op0C->getOperand(0)->getType();
4592 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4593 // Only do this if the casts both really cause code to be
4594 // generated.
4595 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4596 I.getType(), TD) &&
4597 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4598 I.getType(), TD)) {
4599 Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
4600 Op1C->getOperand(0),
4601 I.getName());
4602 InsertNewInstBefore(NewOp, I);
4603 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4604 }
Reid Spencer799b5bf2006-12-13 08:27:15 +00004605 }
Chris Lattner3af10532006-05-05 06:39:07 +00004606 }
Chris Lattnerc62877e2007-10-24 05:38:08 +00004607 }
4608
4609
4610 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4611 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4612 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4613 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
Chris Lattnerc6125712008-02-29 06:09:11 +00004614 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
4615 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType())
Chris Lattnerc62877e2007-10-24 05:38:08 +00004616 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4617 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4618 // If either of the constants are nans, then the whole thing returns
4619 // true.
Chris Lattner55b83022007-10-24 18:54:45 +00004620 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattnerc62877e2007-10-24 05:38:08 +00004621 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4622
4623 // Otherwise, no need to compare the two constants, compare the
4624 // rest.
4625 return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4626 RHS->getOperand(0));
4627 }
4628 }
4629 }
Chris Lattner15212982005-09-18 03:42:07 +00004630
Chris Lattner113f4f42002-06-25 16:13:24 +00004631 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004632}
4633
Chris Lattnerc2076352004-02-16 01:20:27 +00004634// XorSelf - Implements: X ^ X --> 0
4635struct XorSelf {
4636 Value *RHS;
4637 XorSelf(Value *rhs) : RHS(rhs) {}
4638 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4639 Instruction *apply(BinaryOperator &Xor) const {
4640 return &Xor;
4641 }
4642};
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004643
4644
Chris Lattner113f4f42002-06-25 16:13:24 +00004645Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00004646 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00004647 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004648
Evan Cheng2b72c052008-03-25 20:07:13 +00004649 if (isa<UndefValue>(Op1)) {
4650 if (isa<UndefValue>(Op0))
4651 // Handle undef ^ undef -> 0 special case. This is a common
4652 // idiom (misuse).
4653 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner81a7a232004-10-16 18:11:37 +00004654 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Cheng2b72c052008-03-25 20:07:13 +00004655 }
Chris Lattner81a7a232004-10-16 18:11:37 +00004656
Chris Lattnerc2076352004-02-16 01:20:27 +00004657 // xor X, X = 0, even if X is nested in a sequence of Xor's.
4658 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnerf0da7972007-08-05 08:47:58 +00004659 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Chris Lattnere6794492002-08-12 21:17:25 +00004660 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc2076352004-02-16 01:20:27 +00004661 }
Chris Lattner5b2edb12006-02-12 08:02:11 +00004662
4663 // See if we can simplify any instructions used by the instruction whose sole
4664 // purpose is to compute bits we don't care about.
Reid Spencerb722f2b2007-03-22 22:19:58 +00004665 if (!isa<VectorType>(I.getType())) {
4666 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4667 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4668 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4669 KnownZero, KnownOne))
4670 return &I;
Chris Lattnerf14e5172007-06-15 05:26:55 +00004671 } else if (isa<ConstantAggregateZero>(Op1)) {
4672 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Reid Spencerb722f2b2007-03-22 22:19:58 +00004673 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004674
Chris Lattner37338922007-06-15 06:23:19 +00004675 // Is this a ~ operation?
4676 if (Value *NotOp = dyn_castNotVal(&I)) {
4677 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4678 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4679 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4680 if (Op0I->getOpcode() == Instruction::And ||
4681 Op0I->getOpcode() == Instruction::Or) {
4682 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4683 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4684 Instruction *NotY =
4685 BinaryOperator::createNot(Op0I->getOperand(1),
4686 Op0I->getOperand(1)->getName()+".not");
4687 InsertNewInstBefore(NotY, I);
4688 if (Op0I->getOpcode() == Instruction::And)
4689 return BinaryOperator::createOr(Op0NotVal, NotY);
4690 else
4691 return BinaryOperator::createAnd(Op0NotVal, NotY);
4692 }
4693 }
4694 }
4695 }
4696
4697
Zhou Sheng75b871f2007-01-11 12:24:14 +00004698 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky80520192007-08-06 20:04:16 +00004699 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
4700 if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
4701 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Reid Spencer266e42b2006-12-23 06:05:41 +00004702 return new ICmpInst(ICI->getInversePredicate(),
4703 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnere5806662003-11-04 23:50:51 +00004704
Nick Lewycky80520192007-08-06 20:04:16 +00004705 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
4706 return new FCmpInst(FCI->getInversePredicate(),
4707 FCI->getOperand(0), FCI->getOperand(1));
4708 }
4709
Reid Spencer266e42b2006-12-23 06:05:41 +00004710 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner8f2f5982003-11-05 01:06:05 +00004711 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004712 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4713 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004714 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4715 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004716 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004717 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004718 }
Chris Lattnerb24acc72007-04-02 05:36:22 +00004719
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +00004720 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Chris Lattner5b2edb12006-02-12 08:02:11 +00004721 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner0f68fa62003-11-04 23:37:10 +00004722 // ~(X-c) --> (-c-1)-X
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004723 if (RHS->isAllOnesValue()) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004724 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
4725 return BinaryOperator::createSub(
4726 ConstantExpr::getSub(NegOp0CI,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004727 ConstantInt::get(I.getType(), 1)),
Chris Lattner0f68fa62003-11-04 23:37:10 +00004728 Op0I->getOperand(0));
Chris Lattner50490d52007-04-02 05:42:22 +00004729 } else if (RHS->getValue().isSignBit()) {
Chris Lattnerb24acc72007-04-02 05:36:22 +00004730 // (X + C) ^ signbit -> (X + C + signbit)
4731 Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
4732 return BinaryOperator::createAdd(Op0I->getOperand(0), C);
Chris Lattner9d5aace2007-04-02 05:48:58 +00004733
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004734 }
Chris Lattnerf78df7c2006-02-26 19:57:54 +00004735 } else if (Op0I->getOpcode() == Instruction::Or) {
4736 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencerb722f2b2007-03-22 22:19:58 +00004737 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Chris Lattnerf78df7c2006-02-26 19:57:54 +00004738 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4739 // Anything in both C1 and C2 is known to be zero, remove it from
4740 // NewRHS.
Zhou Sheng9bc8ab12007-04-02 13:45:30 +00004741 Constant *CommonBits = And(Op0CI, RHS);
Chris Lattnerf78df7c2006-02-26 19:57:54 +00004742 NewRHS = ConstantExpr::getAnd(NewRHS,
4743 ConstantExpr::getNot(CommonBits));
Chris Lattnerb15e2b12007-03-02 21:28:56 +00004744 AddToWorkList(Op0I);
Chris Lattnerf78df7c2006-02-26 19:57:54 +00004745 I.setOperand(0, Op0I->getOperand(0));
4746 I.setOperand(1, NewRHS);
4747 return &I;
4748 }
Chris Lattner97638592003-07-23 21:37:07 +00004749 }
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +00004750 }
Chris Lattnerb8d6e402002-08-20 18:24:26 +00004751 }
Chris Lattner183b3362004-04-09 19:05:30 +00004752
4753 // Try to fold constant and into select arguments.
4754 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00004755 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00004756 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00004757 if (isa<PHINode>(Op0))
4758 if (Instruction *NV = FoldOpIntoPhi(I))
4759 return NV;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004760 }
4761
Chris Lattnerbb74e222003-03-10 23:06:50 +00004762 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00004763 if (X == Op1)
Chris Lattner37338922007-06-15 06:23:19 +00004764 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattner3082c5a2003-02-18 19:28:33 +00004765
Chris Lattnerbb74e222003-03-10 23:06:50 +00004766 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00004767 if (X == Op0)
Chris Lattner37338922007-06-15 06:23:19 +00004768 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattner3082c5a2003-02-18 19:28:33 +00004769
Chris Lattner07418422007-03-18 22:51:34 +00004770
4771 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
4772 if (Op1I) {
4773 Value *A, *B;
4774 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
4775 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00004776 Op1I->swapOperands();
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004777 I.swapOperands();
4778 std::swap(Op0, Op1);
Chris Lattner07418422007-03-18 22:51:34 +00004779 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00004780 I.swapOperands(); // Simplified below.
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004781 std::swap(Op0, Op1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004782 }
Chris Lattner07418422007-03-18 22:51:34 +00004783 } else if (match(Op1I, m_Xor(m_Value(A), m_Value(B)))) {
4784 if (Op0 == A) // A^(A^B) == B
4785 return ReplaceInstUsesWith(I, B);
4786 else if (Op0 == B) // A^(B^A) == B
4787 return ReplaceInstUsesWith(I, A);
4788 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
Chris Lattner04277992007-04-01 05:36:37 +00004789 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattnerdcd07922006-04-01 08:03:55 +00004790 Op1I->swapOperands();
Chris Lattner04277992007-04-01 05:36:37 +00004791 std::swap(A, B);
4792 }
Chris Lattner07418422007-03-18 22:51:34 +00004793 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattnerdcd07922006-04-01 08:03:55 +00004794 I.swapOperands(); // Simplified below.
4795 std::swap(Op0, Op1);
4796 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00004797 }
Chris Lattner07418422007-03-18 22:51:34 +00004798 }
4799
4800 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
4801 if (Op0I) {
4802 Value *A, *B;
4803 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
4804 if (A == Op1) // (B|A)^B == (A|B)^B
4805 std::swap(A, B);
4806 if (B == Op1) { // (A|B)^B == A & ~B
4807 Instruction *NotB =
4808 InsertNewInstBefore(BinaryOperator::createNot(Op1, "tmp"), I);
4809 return BinaryOperator::createAnd(A, NotB);
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004810 }
Chris Lattner07418422007-03-18 22:51:34 +00004811 } else if (match(Op0I, m_Xor(m_Value(A), m_Value(B)))) {
4812 if (Op1 == A) // (A^B)^A == B
4813 return ReplaceInstUsesWith(I, B);
4814 else if (Op1 == B) // (B^A)^A == B
4815 return ReplaceInstUsesWith(I, A);
4816 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
4817 if (A == Op1) // (A&B)^A -> (B&A)^A
4818 std::swap(A, B);
4819 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattner6cf49142006-04-01 22:05:01 +00004820 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner07418422007-03-18 22:51:34 +00004821 Instruction *N =
4822 InsertNewInstBefore(BinaryOperator::createNot(A, "tmp"), I);
Chris Lattnerdcd07922006-04-01 08:03:55 +00004823 return BinaryOperator::createAnd(N, Op1);
4824 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004825 }
Chris Lattner07418422007-03-18 22:51:34 +00004826 }
4827
4828 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
4829 if (Op0I && Op1I && Op0I->isShift() &&
4830 Op0I->getOpcode() == Op1I->getOpcode() &&
4831 Op0I->getOperand(1) == Op1I->getOperand(1) &&
4832 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
4833 Instruction *NewOp =
4834 InsertNewInstBefore(BinaryOperator::createXor(Op0I->getOperand(0),
4835 Op1I->getOperand(0),
4836 Op0I->getName()), I);
4837 return BinaryOperator::create(Op1I->getOpcode(), NewOp,
4838 Op1I->getOperand(1));
4839 }
4840
4841 if (Op0I && Op1I) {
4842 Value *A, *B, *C, *D;
4843 // (A & B)^(A | B) -> A ^ B
4844 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4845 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
4846 if ((A == C && B == D) || (A == D && B == C))
4847 return BinaryOperator::createXor(A, B);
4848 }
4849 // (A | B)^(A & B) -> A ^ B
4850 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
4851 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4852 if ((A == C && B == D) || (A == D && B == C))
4853 return BinaryOperator::createXor(A, B);
4854 }
4855
4856 // (A & B)^(C & D)
4857 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
4858 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4859 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4860 // (X & Y)^(X & Y) -> (Y^Z) & X
4861 Value *X = 0, *Y = 0, *Z = 0;
4862 if (A == C)
4863 X = A, Y = B, Z = D;
4864 else if (A == D)
4865 X = A, Y = B, Z = C;
4866 else if (B == C)
4867 X = B, Y = A, Z = D;
4868 else if (B == D)
4869 X = B, Y = A, Z = C;
4870
4871 if (X) {
4872 Instruction *NewOp =
4873 InsertNewInstBefore(BinaryOperator::createXor(Y, Z, Op0->getName()), I);
4874 return BinaryOperator::createAnd(NewOp, X);
4875 }
4876 }
4877 }
4878
Reid Spencer266e42b2006-12-23 06:05:41 +00004879 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4880 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4881 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattner3ac7c262003-08-13 20:16:26 +00004882 return R;
4883
Chris Lattner3af10532006-05-05 06:39:07 +00004884 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattnerc62877e2007-10-24 05:38:08 +00004885 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner3af10532006-05-05 06:39:07 +00004886 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer799b5bf2006-12-13 08:27:15 +00004887 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4888 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner03c49532007-01-15 02:27:26 +00004889 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer799b5bf2006-12-13 08:27:15 +00004890 // Only do this if the casts both really cause code to be generated.
Reid Spencer266e42b2006-12-23 06:05:41 +00004891 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4892 I.getType(), TD) &&
4893 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4894 I.getType(), TD)) {
Reid Spencer799b5bf2006-12-13 08:27:15 +00004895 Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
4896 Op1C->getOperand(0),
4897 I.getName());
4898 InsertNewInstBefore(NewOp, I);
4899 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4900 }
Chris Lattner3af10532006-05-05 06:39:07 +00004901 }
Chris Lattnerc62877e2007-10-24 05:38:08 +00004902 }
Chris Lattner113f4f42002-06-25 16:13:24 +00004903 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004904}
4905
Chris Lattner6862fbd2004-09-29 17:40:11 +00004906/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4907/// overflowed for this type.
4908static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
Reid Spencerf4071162007-03-21 23:19:50 +00004909 ConstantInt *In2, bool IsSigned = false) {
Zhou Sheng9bc8ab12007-04-02 13:45:30 +00004910 Result = cast<ConstantInt>(Add(In1, In2));
Chris Lattner6862fbd2004-09-29 17:40:11 +00004911
Reid Spencerf4071162007-03-21 23:19:50 +00004912 if (IsSigned)
4913 if (In2->getValue().isNegative())
4914 return Result->getValue().sgt(In1->getValue());
4915 else
4916 return Result->getValue().slt(In1->getValue());
4917 else
4918 return Result->getValue().ult(In1->getValue());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004919}
4920
Chris Lattner0798af32005-01-13 20:14:25 +00004921/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4922/// code necessary to compute the offset from the base pointer (without adding
4923/// in the base pointer). Return the result as a signed integer of intptr size.
4924static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4925 TargetData &TD = IC.getTargetData();
4926 gep_type_iterator GTI = gep_type_begin(GEP);
Reid Spencer266e42b2006-12-23 06:05:41 +00004927 const Type *IntPtrTy = TD.getIntPtrType();
4928 Value *Result = Constant::getNullValue(IntPtrTy);
Chris Lattner0798af32005-01-13 20:14:25 +00004929
4930 // Build a mask for high order bits.
Chris Lattnerc3a43932008-04-22 02:53:33 +00004931 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Chris Lattner6e880872007-04-28 04:52:43 +00004932 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Chris Lattner0798af32005-01-13 20:14:25 +00004933
Chris Lattner0798af32005-01-13 20:14:25 +00004934 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
4935 Value *Op = GEP->getOperand(i);
Duncan Sands44b87212007-11-01 20:53:16 +00004936 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattner6e880872007-04-28 04:52:43 +00004937 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
4938 if (OpC->isZero()) continue;
4939
4940 // Handle a struct index, which adds its field offset to the pointer.
4941 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4942 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
4943
4944 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
4945 Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
Chris Lattneracbf6a42007-04-28 00:57:34 +00004946 else
Chris Lattner6e880872007-04-28 04:52:43 +00004947 Result = IC.InsertNewInstBefore(
4948 BinaryOperator::createAdd(Result,
4949 ConstantInt::get(IntPtrTy, Size),
4950 GEP->getName()+".offs"), I);
4951 continue;
Chris Lattneracbf6a42007-04-28 00:57:34 +00004952 }
Chris Lattner6e880872007-04-28 04:52:43 +00004953
4954 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4955 Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
4956 Scale = ConstantExpr::getMul(OC, Scale);
4957 if (Constant *RC = dyn_cast<Constant>(Result))
4958 Result = ConstantExpr::getAdd(RC, Scale);
4959 else {
4960 // Emit an add instruction.
4961 Result = IC.InsertNewInstBefore(
4962 BinaryOperator::createAdd(Result, Scale,
4963 GEP->getName()+".offs"), I);
Chris Lattneracbf6a42007-04-28 00:57:34 +00004964 }
Chris Lattner6e880872007-04-28 04:52:43 +00004965 continue;
Chris Lattner0798af32005-01-13 20:14:25 +00004966 }
Chris Lattner6e880872007-04-28 04:52:43 +00004967 // Convert to correct type.
4968 if (Op->getType() != IntPtrTy) {
4969 if (Constant *OpC = dyn_cast<Constant>(Op))
4970 Op = ConstantExpr::getSExt(OpC, IntPtrTy);
4971 else
4972 Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
4973 Op->getName()+".c"), I);
4974 }
4975 if (Size != 1) {
4976 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4977 if (Constant *OpC = dyn_cast<Constant>(Op))
4978 Op = ConstantExpr::getMul(OpC, Scale);
4979 else // We'll let instcombine(mul) convert this to a shl if possible.
4980 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
4981 GEP->getName()+".idx"), I);
4982 }
4983
4984 // Emit an add instruction.
4985 if (isa<Constant>(Op) && isa<Constant>(Result))
4986 Result = ConstantExpr::getAdd(cast<Constant>(Op),
4987 cast<Constant>(Result));
4988 else
4989 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
4990 GEP->getName()+".offs"), I);
Chris Lattner0798af32005-01-13 20:14:25 +00004991 }
4992 return Result;
4993}
4994
Chris Lattnerc3a43932008-04-22 02:53:33 +00004995
4996/// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
4997/// the *offset* implied by GEP to zero. For example, if we have &A[i], we want
4998/// to return 'i' for "icmp ne i, 0". Note that, in general, indices can be
4999/// complex, and scales are involved. The above expression would also be legal
5000/// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32). This
5001/// later form is less amenable to optimization though, and we are allowed to
5002/// generate the first by knowing that pointer arithmetic doesn't overflow.
5003///
5004/// If we can't emit an optimized form for this expression, this returns null.
5005///
5006static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5007 InstCombiner &IC) {
Chris Lattnerc3a43932008-04-22 02:53:33 +00005008 TargetData &TD = IC.getTargetData();
5009 gep_type_iterator GTI = gep_type_begin(GEP);
5010
5011 // Check to see if this gep only has a single variable index. If so, and if
5012 // any constant indices are a multiple of its scale, then we can compute this
5013 // in terms of the scale of the variable index. For example, if the GEP
5014 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5015 // because the expression will cross zero at the same point.
5016 unsigned i, e = GEP->getNumOperands();
5017 int64_t Offset = 0;
5018 for (i = 1; i != e; ++i, ++GTI) {
5019 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5020 // Compute the aggregate offset of constant indices.
5021 if (CI->isZero()) continue;
5022
5023 // Handle a struct index, which adds its field offset to the pointer.
5024 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5025 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5026 } else {
5027 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
5028 Offset += Size*CI->getSExtValue();
5029 }
5030 } else {
5031 // Found our variable index.
5032 break;
5033 }
5034 }
5035
5036 // If there are no variable indices, we must have a constant offset, just
5037 // evaluate it the general way.
5038 if (i == e) return 0;
5039
5040 Value *VariableIdx = GEP->getOperand(i);
5041 // Determine the scale factor of the variable element. For example, this is
5042 // 4 if the variable index is into an array of i32.
5043 uint64_t VariableScale = TD.getABITypeSize(GTI.getIndexedType());
5044
5045 // Verify that there are no other variable indices. If so, emit the hard way.
5046 for (++i, ++GTI; i != e; ++i, ++GTI) {
5047 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5048 if (!CI) return 0;
5049
5050 // Compute the aggregate offset of constant indices.
5051 if (CI->isZero()) continue;
5052
5053 // Handle a struct index, which adds its field offset to the pointer.
5054 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5055 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5056 } else {
5057 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
5058 Offset += Size*CI->getSExtValue();
5059 }
5060 }
5061
5062 // Okay, we know we have a single variable index, which must be a
5063 // pointer/array/vector index. If there is no offset, life is simple, return
5064 // the index.
5065 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5066 if (Offset == 0) {
5067 // Cast to intptrty in case a truncation occurs. If an extension is needed,
5068 // we don't need to bother extending: the extension won't affect where the
5069 // computation crosses zero.
5070 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5071 VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
5072 VariableIdx->getNameStart(), &I);
5073 return VariableIdx;
5074 }
5075
5076 // Otherwise, there is an index. The computation we will do will be modulo
5077 // the pointer size, so get it.
5078 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5079
5080 Offset &= PtrSizeMask;
5081 VariableScale &= PtrSizeMask;
5082
5083 // To do this transformation, any constant index must be a multiple of the
5084 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
5085 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
5086 // multiple of the variable scale.
5087 int64_t NewOffs = Offset / (int64_t)VariableScale;
5088 if (Offset != NewOffs*(int64_t)VariableScale)
5089 return 0;
5090
5091 // Okay, we can do this evaluation. Start by converting the index to intptr.
5092 const Type *IntPtrTy = TD.getIntPtrType();
5093 if (VariableIdx->getType() != IntPtrTy)
5094 VariableIdx = CastInst::createIntegerCast(VariableIdx, IntPtrTy,
5095 true /*SExt*/,
5096 VariableIdx->getNameStart(), &I);
5097 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
5098 return BinaryOperator::createAdd(VariableIdx, OffsetVal, "offset", &I);
5099}
5100
5101
Reid Spencer266e42b2006-12-23 06:05:41 +00005102/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner0798af32005-01-13 20:14:25 +00005103/// else. At this point we know that the GEP is on the LHS of the comparison.
Reid Spencer266e42b2006-12-23 06:05:41 +00005104Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
5105 ICmpInst::Predicate Cond,
5106 Instruction &I) {
Chris Lattner0798af32005-01-13 20:14:25 +00005107 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattner81e84172005-01-13 22:25:21 +00005108
Chris Lattnerc3a43932008-04-22 02:53:33 +00005109 // Look through bitcasts.
5110 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5111 RHS = BCI->getOperand(0);
Chris Lattner81e84172005-01-13 22:25:21 +00005112
Chris Lattner0798af32005-01-13 20:14:25 +00005113 Value *PtrBase = GEPLHS->getOperand(0);
5114 if (PtrBase == RHS) {
Chris Lattner682a7dc2008-02-05 04:45:32 +00005115 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattnerc3a43932008-04-22 02:53:33 +00005116 // This transformation (ignoring the base and scales) is valid because we
5117 // know pointers can't overflow. See if we can output an optimized form.
5118 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5119
5120 // If not, synthesize the offset the hard way.
5121 if (Offset == 0)
5122 Offset = EmitGEPOffset(GEPLHS, I, *this);
Chris Lattner682a7dc2008-02-05 04:45:32 +00005123 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
5124 Constant::getNullValue(Offset->getType()));
Chris Lattner0798af32005-01-13 20:14:25 +00005125 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera21bf8d2005-04-25 20:17:30 +00005126 // If the base pointers are different, but the indices are the same, just
5127 // compare the base pointer.
5128 if (PtrBase != GEPRHS->getOperand(0)) {
5129 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00005130 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattnerbd43b9d2005-04-26 14:40:41 +00005131 GEPRHS->getOperand(0)->getType();
Chris Lattnera21bf8d2005-04-25 20:17:30 +00005132 if (IndicesTheSame)
5133 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5134 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5135 IndicesTheSame = false;
5136 break;
5137 }
5138
5139 // If all indices are the same, just compare the base pointers.
5140 if (IndicesTheSame)
Reid Spencer266e42b2006-12-23 06:05:41 +00005141 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
5142 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera21bf8d2005-04-25 20:17:30 +00005143
5144 // Otherwise, the base pointers are different and the indices are
5145 // different, bail out.
Chris Lattner0798af32005-01-13 20:14:25 +00005146 return 0;
Chris Lattnera21bf8d2005-04-25 20:17:30 +00005147 }
Chris Lattner0798af32005-01-13 20:14:25 +00005148
Chris Lattner81e84172005-01-13 22:25:21 +00005149 // If one of the GEPs has all zero indices, recurse.
5150 bool AllZeros = true;
5151 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5152 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5153 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5154 AllZeros = false;
5155 break;
5156 }
5157 if (AllZeros)
Reid Spencer266e42b2006-12-23 06:05:41 +00005158 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5159 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4fa89822005-01-14 00:20:05 +00005160
5161 // If the other GEP has all zero indices, recurse.
Chris Lattner81e84172005-01-13 22:25:21 +00005162 AllZeros = true;
5163 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5164 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5165 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5166 AllZeros = false;
5167 break;
5168 }
5169 if (AllZeros)
Reid Spencer266e42b2006-12-23 06:05:41 +00005170 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattner81e84172005-01-13 22:25:21 +00005171
Chris Lattner4fa89822005-01-14 00:20:05 +00005172 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5173 // If the GEPs only differ by one index, compare it.
5174 unsigned NumDifferences = 0; // Keep track of # differences.
5175 unsigned DiffOperand = 0; // The operand that differs.
5176 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5177 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005178 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5179 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00005180 // Irreconcilable differences.
Chris Lattner4fa89822005-01-14 00:20:05 +00005181 NumDifferences = 2;
5182 break;
5183 } else {
5184 if (NumDifferences++) break;
5185 DiffOperand = i;
5186 }
5187 }
5188
5189 if (NumDifferences == 0) // SAME GEP?
5190 return ReplaceInstUsesWith(I, // No comparison is needed here.
Nick Lewycky0c5c4792007-09-06 02:40:25 +00005191 ConstantInt::get(Type::Int1Ty,
5192 isTrueWhenEqual(Cond)));
5193
Chris Lattner4fa89822005-01-14 00:20:05 +00005194 else if (NumDifferences == 1) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00005195 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5196 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencer266e42b2006-12-23 06:05:41 +00005197 // Make sure we do a signed comparison here.
5198 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4fa89822005-01-14 00:20:05 +00005199 }
5200 }
5201
Reid Spencer266e42b2006-12-23 06:05:41 +00005202 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner0798af32005-01-13 20:14:25 +00005203 // the result to fold to a constant!
5204 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5205 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5206 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
5207 Value *L = EmitGEPOffset(GEPLHS, I, *this);
5208 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Reid Spencer266e42b2006-12-23 06:05:41 +00005209 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner0798af32005-01-13 20:14:25 +00005210 }
5211 }
5212 return 0;
5213}
5214
Reid Spencer266e42b2006-12-23 06:05:41 +00005215Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5216 bool Changed = SimplifyCompare(I);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00005217 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005218
Chris Lattner6ee923f2007-01-14 19:42:17 +00005219 // Fold trivial predicates.
5220 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5221 return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
5222 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5223 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5224
5225 // Simplify 'fcmp pred X, X'
5226 if (Op0 == Op1) {
5227 switch (I.getPredicate()) {
5228 default: assert(0 && "Unknown predicate!");
5229 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5230 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5231 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
5232 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5233 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5234 case FCmpInst::FCMP_OLT: // True if ordered and less than
5235 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
5236 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5237
5238 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5239 case FCmpInst::FCMP_ULT: // True if unordered or less than
5240 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5241 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5242 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5243 I.setPredicate(FCmpInst::FCMP_UNO);
5244 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5245 return &I;
5246
5247 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5248 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5249 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5250 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5251 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5252 I.setPredicate(FCmpInst::FCMP_ORD);
5253 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5254 return &I;
5255 }
5256 }
5257
Reid Spencer266e42b2006-12-23 06:05:41 +00005258 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Reid Spencer542964f2007-01-11 18:21:29 +00005259 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Chris Lattner81a7a232004-10-16 18:11:37 +00005260
Reid Spencer266e42b2006-12-23 06:05:41 +00005261 // Handle fcmp with constant RHS
5262 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5263 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5264 switch (LHSI->getOpcode()) {
5265 case Instruction::PHI:
5266 if (Instruction *NV = FoldOpIntoPhi(I))
5267 return NV;
5268 break;
5269 case Instruction::Select:
5270 // If either operand of the select is a constant, we can fold the
5271 // comparison into the select arms, which will cause one to be
5272 // constant folded and the select turned into a bitwise or.
5273 Value *Op1 = 0, *Op2 = 0;
5274 if (LHSI->hasOneUse()) {
5275 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5276 // Fold the known value into the constant operand.
5277 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5278 // Insert a new FCmp of the other select operand.
5279 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5280 LHSI->getOperand(2), RHSC,
5281 I.getName()), I);
5282 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5283 // Fold the known value into the constant operand.
5284 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5285 // Insert a new FCmp of the other select operand.
5286 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5287 LHSI->getOperand(1), RHSC,
5288 I.getName()), I);
5289 }
5290 }
5291
5292 if (Op1)
Gabor Greife9ecc682008-04-06 20:25:17 +00005293 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Reid Spencer266e42b2006-12-23 06:05:41 +00005294 break;
5295 }
5296 }
5297
5298 return Changed ? &I : 0;
5299}
5300
5301Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5302 bool Changed = SimplifyCompare(I);
5303 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5304 const Type *Ty = Op0->getType();
5305
5306 // icmp X, X
5307 if (Op0 == Op1)
Reid Spencercddc9df2007-01-12 04:24:46 +00005308 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5309 isTrueWhenEqual(I)));
Reid Spencer266e42b2006-12-23 06:05:41 +00005310
5311 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Reid Spencer542964f2007-01-11 18:21:29 +00005312 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Christopher Lambf00ac6d2007-12-18 21:32:20 +00005313
Reid Spencer266e42b2006-12-23 06:05:41 +00005314 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner15ff1e12004-11-14 07:33:16 +00005315 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanb1c93172005-04-21 23:48:37 +00005316 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5317 isa<ConstantPointerNull>(Op0)) &&
5318 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner15ff1e12004-11-14 07:33:16 +00005319 isa<ConstantPointerNull>(Op1)))
Reid Spencercddc9df2007-01-12 04:24:46 +00005320 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5321 !isTrueWhenEqual(I)));
Chris Lattner6d14f2a2002-08-09 23:47:40 +00005322
Reid Spencer266e42b2006-12-23 06:05:41 +00005323 // icmp's with boolean values can always be turned into bitwise operations
Reid Spencer542964f2007-01-11 18:21:29 +00005324 if (Ty == Type::Int1Ty) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005325 switch (I.getPredicate()) {
5326 default: assert(0 && "Invalid icmp instruction!");
5327 case ICmpInst::ICMP_EQ: { // icmp eq bool %A, %B -> ~(A^B)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00005328 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +00005329 InsertNewInstBefore(Xor, I);
Chris Lattner16930792003-11-03 04:25:02 +00005330 return BinaryOperator::createNot(Xor);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00005331 }
Reid Spencer266e42b2006-12-23 06:05:41 +00005332 case ICmpInst::ICMP_NE: // icmp eq bool %A, %B -> A^B
Chris Lattner4456da62004-08-11 00:50:51 +00005333 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00005334
Reid Spencer266e42b2006-12-23 06:05:41 +00005335 case ICmpInst::ICMP_UGT:
5336 case ICmpInst::ICMP_SGT:
5337 std::swap(Op0, Op1); // Change icmp gt -> icmp lt
Chris Lattner4456da62004-08-11 00:50:51 +00005338 // FALL THROUGH
Reid Spencer266e42b2006-12-23 06:05:41 +00005339 case ICmpInst::ICMP_ULT:
5340 case ICmpInst::ICMP_SLT: { // icmp lt bool A, B -> ~X & Y
Chris Lattner4456da62004-08-11 00:50:51 +00005341 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
5342 InsertNewInstBefore(Not, I);
5343 return BinaryOperator::createAnd(Not, Op1);
5344 }
Reid Spencer266e42b2006-12-23 06:05:41 +00005345 case ICmpInst::ICMP_UGE:
5346 case ICmpInst::ICMP_SGE:
5347 std::swap(Op0, Op1); // Change icmp ge -> icmp le
Chris Lattner4456da62004-08-11 00:50:51 +00005348 // FALL THROUGH
Reid Spencer266e42b2006-12-23 06:05:41 +00005349 case ICmpInst::ICMP_ULE:
5350 case ICmpInst::ICMP_SLE: { // icmp le bool %A, %B -> ~A | B
Chris Lattner4456da62004-08-11 00:50:51 +00005351 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
5352 InsertNewInstBefore(Not, I);
5353 return BinaryOperator::createOr(Not, Op1);
5354 }
5355 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +00005356 }
5357
Chris Lattner2dd01742004-06-09 04:24:29 +00005358 // See if we are doing a comparison between a constant and an instruction that
5359 // can be folded into the comparison.
Chris Lattner6d14f2a2002-08-09 23:47:40 +00005360 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Christopher Lamb7d82bc42007-12-20 07:21:11 +00005361 Value *A, *B;
5362
Chris Lattnerdb026d72008-01-05 01:18:20 +00005363 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5364 if (I.isEquality() && CI->isNullValue() &&
5365 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
5366 // (icmp cond A B) if cond is equality
5367 return new ICmpInst(I.getPredicate(), A, B);
Owen Anderson73639142007-12-28 07:42:12 +00005368 }
Christopher Lamb7d82bc42007-12-20 07:21:11 +00005369
Reid Spencer266e42b2006-12-23 06:05:41 +00005370 switch (I.getPredicate()) {
5371 default: break;
5372 case ICmpInst::ICMP_ULT: // A <u MIN -> FALSE
5373 if (CI->isMinValue(false))
Zhou Sheng75b871f2007-01-11 12:24:14 +00005374 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00005375 if (CI->isMaxValue(false)) // A <u MAX -> A != MAX
5376 return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
5377 if (isMinValuePlusOne(CI,false)) // A <u MIN+1 -> A == MIN
5378 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
Chris Lattner20f23722007-04-11 06:12:58 +00005379 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
5380 if (CI->isMinValue(true))
5381 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
5382 ConstantInt::getAllOnesValue(Op0->getType()));
5383
Reid Spencer266e42b2006-12-23 06:05:41 +00005384 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00005385
Reid Spencer266e42b2006-12-23 06:05:41 +00005386 case ICmpInst::ICMP_SLT:
5387 if (CI->isMinValue(true)) // A <s MIN -> FALSE
Zhou Sheng75b871f2007-01-11 12:24:14 +00005388 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00005389 if (CI->isMaxValue(true)) // A <s MAX -> A != MAX
5390 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5391 if (isMinValuePlusOne(CI,true)) // A <s MIN+1 -> A == MIN
5392 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5393 break;
5394
5395 case ICmpInst::ICMP_UGT:
5396 if (CI->isMaxValue(false)) // A >u MAX -> FALSE
Zhou Sheng75b871f2007-01-11 12:24:14 +00005397 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00005398 if (CI->isMinValue(false)) // A >u MIN -> A != MIN
5399 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5400 if (isMaxValueMinusOne(CI, false)) // A >u MAX-1 -> A == MAX
5401 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
Chris Lattner20f23722007-04-11 06:12:58 +00005402
5403 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
5404 if (CI->isMaxValue(true))
5405 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
5406 ConstantInt::getNullValue(Op0->getType()));
Reid Spencer266e42b2006-12-23 06:05:41 +00005407 break;
5408
5409 case ICmpInst::ICMP_SGT:
5410 if (CI->isMaxValue(true)) // A >s MAX -> FALSE
Zhou Sheng75b871f2007-01-11 12:24:14 +00005411 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00005412 if (CI->isMinValue(true)) // A >s MIN -> A != MIN
5413 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5414 if (isMaxValueMinusOne(CI, true)) // A >s MAX-1 -> A == MAX
5415 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5416 break;
5417
5418 case ICmpInst::ICMP_ULE:
5419 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Zhou Sheng75b871f2007-01-11 12:24:14 +00005420 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00005421 if (CI->isMinValue(false)) // A <=u MIN -> A == MIN
5422 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5423 if (isMaxValueMinusOne(CI,false)) // A <=u MAX-1 -> A != MAX
5424 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5425 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00005426
Reid Spencer266e42b2006-12-23 06:05:41 +00005427 case ICmpInst::ICMP_SLE:
5428 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Zhou Sheng75b871f2007-01-11 12:24:14 +00005429 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00005430 if (CI->isMinValue(true)) // A <=s MIN -> A == MIN
5431 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5432 if (isMaxValueMinusOne(CI,true)) // A <=s MAX-1 -> A != MAX
5433 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5434 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00005435
Reid Spencer266e42b2006-12-23 06:05:41 +00005436 case ICmpInst::ICMP_UGE:
5437 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
Zhou Sheng75b871f2007-01-11 12:24:14 +00005438 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00005439 if (CI->isMaxValue(false)) // A >=u MAX -> A == MAX
5440 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5441 if (isMinValuePlusOne(CI,false)) // A >=u MIN-1 -> A != MIN
5442 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5443 break;
5444
5445 case ICmpInst::ICMP_SGE:
5446 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Zhou Sheng75b871f2007-01-11 12:24:14 +00005447 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00005448 if (CI->isMaxValue(true)) // A >=s MAX -> A == MAX
5449 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5450 if (isMinValuePlusOne(CI,true)) // A >=s MIN-1 -> A != MIN
5451 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5452 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00005453 }
5454
Reid Spencer266e42b2006-12-23 06:05:41 +00005455 // If we still have a icmp le or icmp ge instruction, turn it into the
5456 // appropriate icmp lt or icmp gt instruction. Since the border cases have
Chris Lattner6862fbd2004-09-29 17:40:11 +00005457 // already been handled above, this requires little checking.
5458 //
Reid Spencer624766f2007-03-25 19:55:33 +00005459 switch (I.getPredicate()) {
Chris Lattnerd4fef8d2007-07-15 20:54:51 +00005460 default: break;
5461 case ICmpInst::ICMP_ULE:
5462 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5463 case ICmpInst::ICMP_SLE:
5464 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5465 case ICmpInst::ICMP_UGE:
5466 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5467 case ICmpInst::ICMP_SGE:
5468 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
Reid Spencer624766f2007-03-25 19:55:33 +00005469 }
Chris Lattneree0f2802006-02-12 02:07:56 +00005470
5471 // See if we can fold the comparison based on bits known to be zero or one
Chris Lattnerd4fef8d2007-07-15 20:54:51 +00005472 // in the input. If this comparison is a normal comparison, it demands all
5473 // bits, if it is a sign bit comparison, it only demands the sign bit.
5474
5475 bool UnusedBit;
5476 bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5477
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00005478 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
5479 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
Chris Lattnerd4fef8d2007-07-15 20:54:51 +00005480 if (SimplifyDemandedBits(Op0,
5481 isSignBit ? APInt::getSignBit(BitWidth)
5482 : APInt::getAllOnesValue(BitWidth),
Chris Lattneree0f2802006-02-12 02:07:56 +00005483 KnownZero, KnownOne, 0))
5484 return &I;
5485
5486 // Given the known and unknown bits, compute a range that the LHS could be
5487 // in.
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00005488 if ((KnownOne | KnownZero) != 0) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005489 // Compute the Min, Max and RHS values based on the known bits. For the
5490 // EQ and NE we use unsigned values.
Zhou Sheng150f3bb2007-04-01 17:13:37 +00005491 APInt Min(BitWidth, 0), Max(BitWidth, 0);
5492 const APInt& RHSVal = CI->getValue();
Reid Spencer266e42b2006-12-23 06:05:41 +00005493 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00005494 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
5495 Max);
Reid Spencer266e42b2006-12-23 06:05:41 +00005496 } else {
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00005497 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
5498 Max);
Reid Spencer266e42b2006-12-23 06:05:41 +00005499 }
5500 switch (I.getPredicate()) { // LE/GE have been folded already.
5501 default: assert(0 && "Unknown icmp opcode!");
5502 case ICmpInst::ICMP_EQ:
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00005503 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00005504 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00005505 break;
5506 case ICmpInst::ICMP_NE:
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00005507 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00005508 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00005509 break;
5510 case ICmpInst::ICMP_ULT:
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00005511 if (Max.ult(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00005512 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner467b69c2007-04-09 23:52:13 +00005513 if (Min.uge(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00005514 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00005515 break;
5516 case ICmpInst::ICMP_UGT:
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00005517 if (Min.ugt(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00005518 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner467b69c2007-04-09 23:52:13 +00005519 if (Max.ule(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00005520 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00005521 break;
5522 case ICmpInst::ICMP_SLT:
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00005523 if (Max.slt(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00005524 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00005525 if (Min.sgt(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00005526 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00005527 break;
5528 case ICmpInst::ICMP_SGT:
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00005529 if (Min.sgt(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00005530 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner467b69c2007-04-09 23:52:13 +00005531 if (Max.sle(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00005532 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00005533 break;
Chris Lattneree0f2802006-02-12 02:07:56 +00005534 }
5535 }
5536
Reid Spencer266e42b2006-12-23 06:05:41 +00005537 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer7e80b0b2006-10-26 06:15:43 +00005538 // instruction, see if that instruction also has constants so that the
Reid Spencer266e42b2006-12-23 06:05:41 +00005539 // instruction can be folded into the icmp
Chris Lattnere1e10e12004-05-25 06:32:08 +00005540 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattnera74deaf2007-04-03 17:43:25 +00005541 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
5542 return Res;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005543 }
5544
Chris Lattnera74deaf2007-04-03 17:43:25 +00005545 // Handle icmp with constant (but not simple integer constant) RHS
Chris Lattner77c32c32005-04-23 15:31:55 +00005546 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5547 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5548 switch (LHSI->getOpcode()) {
Chris Lattnera816eee2005-05-01 04:42:15 +00005549 case Instruction::GetElementPtr:
5550 if (RHSC->isNullValue()) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005551 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattnera816eee2005-05-01 04:42:15 +00005552 bool isAllZeros = true;
5553 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5554 if (!isa<Constant>(LHSI->getOperand(i)) ||
5555 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5556 isAllZeros = false;
5557 break;
5558 }
5559 if (isAllZeros)
Reid Spencer266e42b2006-12-23 06:05:41 +00005560 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Chris Lattnera816eee2005-05-01 04:42:15 +00005561 Constant::getNullValue(LHSI->getOperand(0)->getType()));
5562 }
5563 break;
5564
Chris Lattner77c32c32005-04-23 15:31:55 +00005565 case Instruction::PHI:
5566 if (Instruction *NV = FoldOpIntoPhi(I))
5567 return NV;
5568 break;
Chris Lattner3dbe65f2007-04-06 18:57:34 +00005569 case Instruction::Select: {
Chris Lattner77c32c32005-04-23 15:31:55 +00005570 // If either operand of the select is a constant, we can fold the
5571 // comparison into the select arms, which will cause one to be
5572 // constant folded and the select turned into a bitwise or.
5573 Value *Op1 = 0, *Op2 = 0;
5574 if (LHSI->hasOneUse()) {
5575 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5576 // Fold the known value into the constant operand.
Reid Spencer266e42b2006-12-23 06:05:41 +00005577 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5578 // Insert a new ICmp of the other select operand.
5579 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5580 LHSI->getOperand(2), RHSC,
5581 I.getName()), I);
Chris Lattner77c32c32005-04-23 15:31:55 +00005582 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5583 // Fold the known value into the constant operand.
Reid Spencer266e42b2006-12-23 06:05:41 +00005584 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5585 // Insert a new ICmp of the other select operand.
5586 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5587 LHSI->getOperand(1), RHSC,
5588 I.getName()), I);
Chris Lattner77c32c32005-04-23 15:31:55 +00005589 }
5590 }
Jeff Cohen82639852005-04-23 21:38:35 +00005591
Chris Lattner77c32c32005-04-23 15:31:55 +00005592 if (Op1)
Gabor Greife9ecc682008-04-06 20:25:17 +00005593 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Chris Lattner77c32c32005-04-23 15:31:55 +00005594 break;
5595 }
Chris Lattner3dbe65f2007-04-06 18:57:34 +00005596 case Instruction::Malloc:
5597 // If we have (malloc != null), and if the malloc has a single use, we
5598 // can assume it is successful and remove the malloc.
5599 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
5600 AddToWorkList(LHSI);
5601 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5602 !isTrueWhenEqual(I)));
5603 }
5604 break;
5605 }
Chris Lattner77c32c32005-04-23 15:31:55 +00005606 }
5607
Reid Spencer266e42b2006-12-23 06:05:41 +00005608 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Chris Lattner0798af32005-01-13 20:14:25 +00005609 if (User *GEP = dyn_castGetElementPtr(Op0))
Reid Spencer266e42b2006-12-23 06:05:41 +00005610 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner0798af32005-01-13 20:14:25 +00005611 return NI;
5612 if (User *GEP = dyn_castGetElementPtr(Op1))
Reid Spencer266e42b2006-12-23 06:05:41 +00005613 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5614 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner0798af32005-01-13 20:14:25 +00005615 return NI;
5616
Reid Spencer266e42b2006-12-23 06:05:41 +00005617 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner64d87b02007-01-06 01:45:59 +00005618 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
5619 // now.
5620 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5621 if (isa<PointerType>(Op0->getType()) &&
5622 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattner16930792003-11-03 04:25:02 +00005623 // We keep moving the cast from the left operand over to the right
5624 // operand, where it can often be eliminated completely.
Chris Lattner64d87b02007-01-06 01:45:59 +00005625 Op0 = CI->getOperand(0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005626
Chris Lattner64d87b02007-01-06 01:45:59 +00005627 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5628 // so eliminate it as well.
5629 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5630 Op1 = CI2->getOperand(0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005631
Chris Lattner16930792003-11-03 04:25:02 +00005632 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +00005633 if (Op0->getType() != Op1->getType()) {
Chris Lattner16930792003-11-03 04:25:02 +00005634 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Reid Spencerbb65ebf2006-12-12 23:36:14 +00005635 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattner16930792003-11-03 04:25:02 +00005636 } else {
Reid Spencer266e42b2006-12-23 06:05:41 +00005637 // Otherwise, cast the RHS right before the icmp
Chris Lattner5a866122008-01-13 22:23:22 +00005638 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
Chris Lattner16930792003-11-03 04:25:02 +00005639 }
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +00005640 }
Reid Spencer266e42b2006-12-23 06:05:41 +00005641 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattner16930792003-11-03 04:25:02 +00005642 }
Chris Lattner64d87b02007-01-06 01:45:59 +00005643 }
5644
5645 if (isa<CastInst>(Op0)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005646 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner6444c372003-11-03 05:17:03 +00005647 // This comes up when you have code like
5648 // int X = A < B;
5649 // if (X) ...
5650 // For generality, we handle any zero-extension of any operand comparison
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005651 // with a constant or another cast from the same type.
5652 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencer266e42b2006-12-23 06:05:41 +00005653 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005654 return R;
Chris Lattner6444c372003-11-03 05:17:03 +00005655 }
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005656
Chris Lattnerb3f24c92006-09-18 04:22:48 +00005657 if (I.isEquality()) {
Chris Lattner17c7c032007-01-05 03:04:57 +00005658 Value *A, *B, *C, *D;
5659 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
5660 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
5661 Value *OtherVal = A == Op1 ? B : A;
5662 return new ICmpInst(I.getPredicate(), OtherVal,
5663 Constant::getNullValue(A->getType()));
5664 }
5665
5666 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5667 // A^c1 == C^c2 --> A == C^(c1^c2)
5668 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
5669 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
5670 if (Op1->hasOneUse()) {
Zhou Sheng9bc8ab12007-04-02 13:45:30 +00005671 Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
Chris Lattner17c7c032007-01-05 03:04:57 +00005672 Instruction *Xor = BinaryOperator::createXor(C, NC, "tmp");
5673 return new ICmpInst(I.getPredicate(), A,
5674 InsertNewInstBefore(Xor, I));
5675 }
5676
5677 // A^B == A^D -> B == D
5678 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
5679 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
5680 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
5681 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
5682 }
5683 }
5684
5685 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5686 (A == Op0 || B == Op0)) {
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005687 // A == (A^B) -> B == 0
5688 Value *OtherVal = A == Op0 ? B : A;
Reid Spencer266e42b2006-12-23 06:05:41 +00005689 return new ICmpInst(I.getPredicate(), OtherVal,
5690 Constant::getNullValue(A->getType()));
Chris Lattner17c7c032007-01-05 03:04:57 +00005691 }
5692 if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005693 // (A-B) == A -> B == 0
Reid Spencer266e42b2006-12-23 06:05:41 +00005694 return new ICmpInst(I.getPredicate(), B,
5695 Constant::getNullValue(B->getType()));
Chris Lattner17c7c032007-01-05 03:04:57 +00005696 }
5697 if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005698 // A == (A-B) -> B == 0
Reid Spencer266e42b2006-12-23 06:05:41 +00005699 return new ICmpInst(I.getPredicate(), B,
5700 Constant::getNullValue(B->getType()));
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005701 }
Chris Lattnerd12a4bf2006-11-14 06:06:06 +00005702
Chris Lattnerd12a4bf2006-11-14 06:06:06 +00005703 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5704 if (Op0->hasOneUse() && Op1->hasOneUse() &&
5705 match(Op0, m_And(m_Value(A), m_Value(B))) &&
5706 match(Op1, m_And(m_Value(C), m_Value(D)))) {
5707 Value *X = 0, *Y = 0, *Z = 0;
5708
5709 if (A == C) {
5710 X = B; Y = D; Z = A;
5711 } else if (A == D) {
5712 X = B; Y = C; Z = A;
5713 } else if (B == C) {
5714 X = A; Y = D; Z = B;
5715 } else if (B == D) {
5716 X = A; Y = C; Z = B;
5717 }
5718
5719 if (X) { // Build (X^Y) & Z
5720 Op1 = InsertNewInstBefore(BinaryOperator::createXor(X, Y, "tmp"), I);
5721 Op1 = InsertNewInstBefore(BinaryOperator::createAnd(Op1, Z, "tmp"), I);
5722 I.setOperand(0, Op1);
5723 I.setOperand(1, Constant::getNullValue(Op1->getType()));
5724 return &I;
5725 }
5726 }
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005727 }
Chris Lattner113f4f42002-06-25 16:13:24 +00005728 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005729}
5730
Chris Lattner3bbec592007-06-20 23:46:26 +00005731
5732/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
5733/// and CmpRHS are both known to be integer constants.
5734Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
5735 ConstantInt *DivRHS) {
5736 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
5737 const APInt &CmpRHSV = CmpRHS->getValue();
5738
5739 // FIXME: If the operand types don't match the type of the divide
5740 // then don't attempt this transform. The code below doesn't have the
5741 // logic to deal with a signed divide and an unsigned compare (and
5742 // vice versa). This is because (x /s C1) <s C2 produces different
5743 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
5744 // (x /u C1) <u C2. Simply casting the operands and result won't
5745 // work. :( The if statement below tests that condition and bails
5746 // if it finds it.
5747 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
5748 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
5749 return 0;
5750 if (DivRHS->isZero())
Chris Lattnerfb032b12007-06-21 18:11:19 +00005751 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattner3bbec592007-06-20 23:46:26 +00005752
5753 // Compute Prod = CI * DivRHS. We are essentially solving an equation
5754 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
5755 // C2 (CI). By solving for X we can turn this into a range check
5756 // instead of computing a divide.
5757 ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
5758
5759 // Determine if the product overflows by seeing if the product is
5760 // not equal to the divide. Make sure we do the same kind of divide
5761 // as in the LHS instruction that we're folding.
5762 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
5763 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
5764
5765 // Get the ICmp opcode
Chris Lattnerfb032b12007-06-21 18:11:19 +00005766 ICmpInst::Predicate Pred = ICI.getPredicate();
Chris Lattner3bbec592007-06-20 23:46:26 +00005767
Chris Lattnerfb032b12007-06-21 18:11:19 +00005768 // Figure out the interval that is being checked. For example, a comparison
5769 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
5770 // Compute this interval based on the constants involved and the signedness of
5771 // the compare/divide. This computes a half-open interval, keeping track of
5772 // whether either value in the interval overflows. After analysis each
5773 // overflow variable is set to 0 if it's corresponding bound variable is valid
5774 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
5775 int LoOverflow = 0, HiOverflow = 0;
5776 ConstantInt *LoBound = 0, *HiBound = 0;
5777
5778
Chris Lattner3bbec592007-06-20 23:46:26 +00005779 if (!DivIsSigned) { // udiv
Chris Lattnerfb032b12007-06-21 18:11:19 +00005780 // e.g. X/5 op 3 --> [15, 20)
Chris Lattner3bbec592007-06-20 23:46:26 +00005781 LoBound = Prod;
Chris Lattnerfb032b12007-06-21 18:11:19 +00005782 HiOverflow = LoOverflow = ProdOV;
5783 if (!HiOverflow)
5784 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
Dan Gohman1ee8dc92008-02-13 22:09:18 +00005785 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Chris Lattner3bbec592007-06-20 23:46:26 +00005786 if (CmpRHSV == 0) { // (X / pos) op 0
Chris Lattnerfb032b12007-06-21 18:11:19 +00005787 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Chris Lattner3bbec592007-06-20 23:46:26 +00005788 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
5789 HiBound = DivRHS;
Dan Gohman1ee8dc92008-02-13 22:09:18 +00005790 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Chris Lattnerfb032b12007-06-21 18:11:19 +00005791 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
5792 HiOverflow = LoOverflow = ProdOV;
5793 if (!HiOverflow)
5794 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
Chris Lattner3bbec592007-06-20 23:46:26 +00005795 } else { // (X / pos) op neg
Chris Lattnerfb032b12007-06-21 18:11:19 +00005796 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Chris Lattner3bbec592007-06-20 23:46:26 +00005797 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
5798 LoOverflow = AddWithOverflow(LoBound, Prod,
Chris Lattnerfb032b12007-06-21 18:11:19 +00005799 cast<ConstantInt>(DivRHSH), true) ? -1 : 0;
Chris Lattner3bbec592007-06-20 23:46:26 +00005800 HiBound = AddOne(Prod);
Chris Lattnerfb032b12007-06-21 18:11:19 +00005801 HiOverflow = ProdOV ? -1 : 0;
Chris Lattner3bbec592007-06-20 23:46:26 +00005802 }
Dan Gohman1ee8dc92008-02-13 22:09:18 +00005803 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Chris Lattner3bbec592007-06-20 23:46:26 +00005804 if (CmpRHSV == 0) { // (X / neg) op 0
Chris Lattnerfb032b12007-06-21 18:11:19 +00005805 // e.g. X/-5 op 0 --> [-4, 5)
Chris Lattner3bbec592007-06-20 23:46:26 +00005806 LoBound = AddOne(DivRHS);
5807 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattnerfb032b12007-06-21 18:11:19 +00005808 if (HiBound == DivRHS) { // -INTMIN = INTMIN
5809 HiOverflow = 1; // [INTMIN+1, overflow)
5810 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
5811 }
Dan Gohman1ee8dc92008-02-13 22:09:18 +00005812 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Chris Lattnerfb032b12007-06-21 18:11:19 +00005813 // e.g. X/-5 op 3 --> [-19, -14)
5814 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
Chris Lattner3bbec592007-06-20 23:46:26 +00005815 if (!LoOverflow)
Chris Lattnerfb032b12007-06-21 18:11:19 +00005816 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS), true) ?-1:0;
Chris Lattner3bbec592007-06-20 23:46:26 +00005817 HiBound = AddOne(Prod);
5818 } else { // (X / neg) op neg
Chris Lattnerfb032b12007-06-21 18:11:19 +00005819 // e.g. X/-5 op -3 --> [15, 20)
Chris Lattner3bbec592007-06-20 23:46:26 +00005820 LoBound = Prod;
Chris Lattnerfb032b12007-06-21 18:11:19 +00005821 LoOverflow = HiOverflow = ProdOV ? 1 : 0;
Chris Lattner3bbec592007-06-20 23:46:26 +00005822 HiBound = Subtract(Prod, DivRHS);
5823 }
5824
Chris Lattnerfb032b12007-06-21 18:11:19 +00005825 // Dividing by a negative swaps the condition. LT <-> GT
5826 Pred = ICmpInst::getSwappedPredicate(Pred);
Chris Lattner3bbec592007-06-20 23:46:26 +00005827 }
5828
5829 Value *X = DivI->getOperand(0);
Chris Lattnerfb032b12007-06-21 18:11:19 +00005830 switch (Pred) {
Chris Lattner3bbec592007-06-20 23:46:26 +00005831 default: assert(0 && "Unhandled icmp opcode!");
5832 case ICmpInst::ICMP_EQ:
5833 if (LoOverflow && HiOverflow)
5834 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5835 else if (HiOverflow)
Chris Lattnerfb032b12007-06-21 18:11:19 +00005836 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner3bbec592007-06-20 23:46:26 +00005837 ICmpInst::ICMP_UGE, X, LoBound);
5838 else if (LoOverflow)
5839 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
5840 ICmpInst::ICMP_ULT, X, HiBound);
5841 else
Chris Lattnerfb032b12007-06-21 18:11:19 +00005842 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
Chris Lattner3bbec592007-06-20 23:46:26 +00005843 case ICmpInst::ICMP_NE:
5844 if (LoOverflow && HiOverflow)
5845 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5846 else if (HiOverflow)
Chris Lattnerfb032b12007-06-21 18:11:19 +00005847 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner3bbec592007-06-20 23:46:26 +00005848 ICmpInst::ICMP_ULT, X, LoBound);
5849 else if (LoOverflow)
5850 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
5851 ICmpInst::ICMP_UGE, X, HiBound);
5852 else
Chris Lattnerfb032b12007-06-21 18:11:19 +00005853 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
Chris Lattner3bbec592007-06-20 23:46:26 +00005854 case ICmpInst::ICMP_ULT:
5855 case ICmpInst::ICMP_SLT:
Chris Lattnerfb032b12007-06-21 18:11:19 +00005856 if (LoOverflow == +1) // Low bound is greater than input range.
5857 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5858 if (LoOverflow == -1) // Low bound is less than input range.
Chris Lattner3bbec592007-06-20 23:46:26 +00005859 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Chris Lattnerfb032b12007-06-21 18:11:19 +00005860 return new ICmpInst(Pred, X, LoBound);
Chris Lattner3bbec592007-06-20 23:46:26 +00005861 case ICmpInst::ICMP_UGT:
5862 case ICmpInst::ICMP_SGT:
Chris Lattnerfb032b12007-06-21 18:11:19 +00005863 if (HiOverflow == +1) // High bound greater than input range.
Chris Lattner3bbec592007-06-20 23:46:26 +00005864 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Chris Lattnerfb032b12007-06-21 18:11:19 +00005865 else if (HiOverflow == -1) // High bound less than input range.
5866 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5867 if (Pred == ICmpInst::ICMP_UGT)
Chris Lattner3bbec592007-06-20 23:46:26 +00005868 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
5869 else
5870 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
5871 }
5872}
5873
5874
Chris Lattnera74deaf2007-04-03 17:43:25 +00005875/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
5876///
5877Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
5878 Instruction *LHSI,
5879 ConstantInt *RHS) {
5880 const APInt &RHSV = RHS->getValue();
5881
5882 switch (LHSI->getOpcode()) {
Duncan Sandsf01a47c2007-04-04 06:42:45 +00005883 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
Chris Lattnera74deaf2007-04-03 17:43:25 +00005884 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
5885 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
5886 // fold the xor.
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +00005887 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
5888 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Chris Lattnera74deaf2007-04-03 17:43:25 +00005889 Value *CompareVal = LHSI->getOperand(0);
5890
5891 // If the sign bit of the XorCST is not set, there is no change to
5892 // the operation, just stop using the Xor.
5893 if (!XorCST->getValue().isNegative()) {
5894 ICI.setOperand(0, CompareVal);
5895 AddToWorkList(LHSI);
5896 return &ICI;
5897 }
5898
5899 // Was the old condition true if the operand is positive?
5900 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
5901
5902 // If so, the new one isn't.
5903 isTrueIfPositive ^= true;
5904
5905 if (isTrueIfPositive)
5906 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
5907 else
5908 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
5909 }
5910 }
5911 break;
5912 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
5913 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
5914 LHSI->getOperand(0)->hasOneUse()) {
5915 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
5916
5917 // If the LHS is an AND of a truncating cast, we can widen the
5918 // and/compare to be the input width without changing the value
5919 // produced, eliminating a cast.
5920 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
5921 // We can do this transformation if either the AND constant does not
5922 // have its sign bit set or if it is an equality comparison.
5923 // Extending a relational comparison when we're checking the sign
5924 // bit would not work.
5925 if (Cast->hasOneUse() &&
Anton Korobeynikov18991d72008-02-20 12:07:57 +00005926 (ICI.isEquality() ||
5927 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Chris Lattnera74deaf2007-04-03 17:43:25 +00005928 uint32_t BitWidth =
5929 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
5930 APInt NewCST = AndCST->getValue();
5931 NewCST.zext(BitWidth);
5932 APInt NewCI = RHSV;
5933 NewCI.zext(BitWidth);
5934 Instruction *NewAnd =
5935 BinaryOperator::createAnd(Cast->getOperand(0),
5936 ConstantInt::get(NewCST),LHSI->getName());
5937 InsertNewInstBefore(NewAnd, ICI);
5938 return new ICmpInst(ICI.getPredicate(), NewAnd,
5939 ConstantInt::get(NewCI));
5940 }
5941 }
5942
5943 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
5944 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
5945 // happens a LOT in code produced by the C front-end, for bitfield
5946 // access.
5947 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
5948 if (Shift && !Shift->isShift())
5949 Shift = 0;
5950
5951 ConstantInt *ShAmt;
5952 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
5953 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
5954 const Type *AndTy = AndCST->getType(); // Type of the and.
5955
5956 // We can fold this as long as we can't shift unknown bits
5957 // into the mask. This can only happen with signed shift
5958 // rights, as they sign-extend.
5959 if (ShAmt) {
5960 bool CanFold = Shift->isLogicalShift();
5961 if (!CanFold) {
5962 // To test for the bad case of the signed shr, see if any
5963 // of the bits shifted in could be tested after the mask.
5964 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
5965 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
5966
5967 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
5968 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
5969 AndCST->getValue()) == 0)
5970 CanFold = true;
5971 }
5972
5973 if (CanFold) {
5974 Constant *NewCst;
5975 if (Shift->getOpcode() == Instruction::Shl)
5976 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
5977 else
5978 NewCst = ConstantExpr::getShl(RHS, ShAmt);
5979
5980 // Check to see if we are shifting out any of the bits being
5981 // compared.
5982 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
5983 // If we shifted bits out, the fold is not going to work out.
5984 // As a special case, check to see if this means that the
5985 // result is always true or false now.
5986 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
5987 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5988 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
5989 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5990 } else {
5991 ICI.setOperand(1, NewCst);
5992 Constant *NewAndCST;
5993 if (Shift->getOpcode() == Instruction::Shl)
5994 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
5995 else
5996 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
5997 LHSI->setOperand(1, NewAndCST);
5998 LHSI->setOperand(0, Shift->getOperand(0));
5999 AddToWorkList(Shift); // Shift is dead.
6000 AddUsesToWorkList(ICI);
6001 return &ICI;
6002 }
6003 }
6004 }
6005
6006 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
6007 // preferable because it allows the C<<Y expression to be hoisted out
6008 // of a loop if Y is invariant and X is not.
6009 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
6010 ICI.isEquality() && !Shift->isArithmeticShift() &&
6011 isa<Instruction>(Shift->getOperand(0))) {
6012 // Compute C << Y.
6013 Value *NS;
6014 if (Shift->getOpcode() == Instruction::LShr) {
6015 NS = BinaryOperator::createShl(AndCST,
6016 Shift->getOperand(1), "tmp");
6017 } else {
6018 // Insert a logical shift.
6019 NS = BinaryOperator::createLShr(AndCST,
6020 Shift->getOperand(1), "tmp");
6021 }
6022 InsertNewInstBefore(cast<Instruction>(NS), ICI);
6023
6024 // Compute X & (C << Y).
6025 Instruction *NewAnd =
6026 BinaryOperator::createAnd(Shift->getOperand(0), NS, LHSI->getName());
6027 InsertNewInstBefore(NewAnd, ICI);
6028
6029 ICI.setOperand(0, NewAnd);
6030 return &ICI;
6031 }
6032 }
6033 break;
6034
Chris Lattner06205d52007-07-15 20:42:37 +00006035 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6036 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6037 if (!ShAmt) break;
6038
6039 uint32_t TypeBits = RHSV.getBitWidth();
6040
6041 // Check that the shift amount is in range. If not, don't perform
6042 // undefined shifts. When the shift is visited it will be
6043 // simplified.
6044 if (ShAmt->uge(TypeBits))
6045 break;
6046
6047 if (ICI.isEquality()) {
6048 // If we are comparing against bits always shifted out, the
6049 // comparison cannot succeed.
6050 Constant *Comp =
6051 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
6052 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6053 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6054 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6055 return ReplaceInstUsesWith(ICI, Cst);
6056 }
6057
6058 if (LHSI->hasOneUse()) {
6059 // Otherwise strength reduce the shift into an and.
6060 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6061 Constant *Mask =
6062 ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
Chris Lattnera74deaf2007-04-03 17:43:25 +00006063
Chris Lattner06205d52007-07-15 20:42:37 +00006064 Instruction *AndI =
6065 BinaryOperator::createAnd(LHSI->getOperand(0),
6066 Mask, LHSI->getName()+".mask");
6067 Value *And = InsertNewInstBefore(AndI, ICI);
6068 return new ICmpInst(ICI.getPredicate(), And,
6069 ConstantInt::get(RHSV.lshr(ShAmtVal)));
Chris Lattnera74deaf2007-04-03 17:43:25 +00006070 }
6071 }
Chris Lattner06205d52007-07-15 20:42:37 +00006072
6073 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6074 bool TrueIfSigned = false;
6075 if (LHSI->hasOneUse() &&
6076 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6077 // (X << 31) <s 0 --> (X&1) != 0
6078 Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
6079 (TypeBits-ShAmt->getZExtValue()-1));
6080 Instruction *AndI =
6081 BinaryOperator::createAnd(LHSI->getOperand(0),
6082 Mask, LHSI->getName()+".mask");
6083 Value *And = InsertNewInstBefore(AndI, ICI);
6084
6085 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6086 And, Constant::getNullValue(And->getType()));
6087 }
Chris Lattnera74deaf2007-04-03 17:43:25 +00006088 break;
Chris Lattner06205d52007-07-15 20:42:37 +00006089 }
Chris Lattnera74deaf2007-04-03 17:43:25 +00006090
6091 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Chris Lattner06205d52007-07-15 20:42:37 +00006092 case Instruction::AShr: {
Chris Lattnerc44160c2008-03-21 05:19:58 +00006093 // Only handle equality comparisons of shift-by-constant.
Chris Lattner06205d52007-07-15 20:42:37 +00006094 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattnerc44160c2008-03-21 05:19:58 +00006095 if (!ShAmt || !ICI.isEquality()) break;
Chris Lattner06205d52007-07-15 20:42:37 +00006096
Chris Lattnerc44160c2008-03-21 05:19:58 +00006097 // Check that the shift amount is in range. If not, don't perform
6098 // undefined shifts. When the shift is visited it will be
6099 // simplified.
6100 uint32_t TypeBits = RHSV.getBitWidth();
6101 if (ShAmt->uge(TypeBits))
6102 break;
6103
6104 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattner06205d52007-07-15 20:42:37 +00006105
Chris Lattnerc44160c2008-03-21 05:19:58 +00006106 // If we are comparing against bits always shifted out, the
6107 // comparison cannot succeed.
6108 APInt Comp = RHSV << ShAmtVal;
6109 if (LHSI->getOpcode() == Instruction::LShr)
6110 Comp = Comp.lshr(ShAmtVal);
6111 else
6112 Comp = Comp.ashr(ShAmtVal);
6113
6114 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6115 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6116 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6117 return ReplaceInstUsesWith(ICI, Cst);
6118 }
6119
6120 // Otherwise, check to see if the bits shifted out are known to be zero.
6121 // If so, we can compare against the unshifted value:
6122 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Cheng1c89ca72008-04-23 00:38:06 +00006123 if (LHSI->hasOneUse() &&
6124 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattnerc44160c2008-03-21 05:19:58 +00006125 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
6126 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6127 ConstantExpr::getShl(RHS, ShAmt));
6128 }
Chris Lattner06205d52007-07-15 20:42:37 +00006129
Evan Cheng1c89ca72008-04-23 00:38:06 +00006130 if (LHSI->hasOneUse()) {
Chris Lattnerc44160c2008-03-21 05:19:58 +00006131 // Otherwise strength reduce the shift into an and.
6132 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
6133 Constant *Mask = ConstantInt::get(Val);
Chris Lattner06205d52007-07-15 20:42:37 +00006134
Chris Lattnerc44160c2008-03-21 05:19:58 +00006135 Instruction *AndI =
6136 BinaryOperator::createAnd(LHSI->getOperand(0),
6137 Mask, LHSI->getName()+".mask");
6138 Value *And = InsertNewInstBefore(AndI, ICI);
6139 return new ICmpInst(ICI.getPredicate(), And,
6140 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattnera74deaf2007-04-03 17:43:25 +00006141 }
6142 break;
Chris Lattner06205d52007-07-15 20:42:37 +00006143 }
Chris Lattnera74deaf2007-04-03 17:43:25 +00006144
6145 case Instruction::SDiv:
6146 case Instruction::UDiv:
6147 // Fold: icmp pred ([us]div X, C1), C2 -> range test
6148 // Fold this div into the comparison, producing a range check.
6149 // Determine, based on the divide type, what the range is being
6150 // checked. If there is an overflow on the low or high side, remember
6151 // it, otherwise compute the range [low, hi) bounding the new value.
6152 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner3bbec592007-06-20 23:46:26 +00006153 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6154 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6155 DivRHS))
6156 return R;
Chris Lattnera74deaf2007-04-03 17:43:25 +00006157 break;
Nick Lewycky3b592142008-02-03 16:33:09 +00006158
6159 case Instruction::Add:
6160 // Fold: icmp pred (add, X, C1), C2
6161
6162 if (!ICI.isEquality()) {
6163 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6164 if (!LHSC) break;
6165 const APInt &LHSV = LHSC->getValue();
6166
6167 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6168 .subtract(LHSV);
6169
6170 if (ICI.isSignedPredicate()) {
6171 if (CR.getLower().isSignBit()) {
6172 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
6173 ConstantInt::get(CR.getUpper()));
6174 } else if (CR.getUpper().isSignBit()) {
6175 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
6176 ConstantInt::get(CR.getLower()));
6177 }
6178 } else {
6179 if (CR.getLower().isMinValue()) {
6180 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
6181 ConstantInt::get(CR.getUpper()));
6182 } else if (CR.getUpper().isMinValue()) {
6183 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
6184 ConstantInt::get(CR.getLower()));
6185 }
6186 }
6187 }
6188 break;
Chris Lattnera74deaf2007-04-03 17:43:25 +00006189 }
6190
6191 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6192 if (ICI.isEquality()) {
6193 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6194
6195 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
6196 // the second operand is a constant, simplify a bit.
6197 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6198 switch (BO->getOpcode()) {
6199 case Instruction::SRem:
6200 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6201 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6202 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6203 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
6204 Instruction *NewRem =
6205 BinaryOperator::createURem(BO->getOperand(0), BO->getOperand(1),
6206 BO->getName());
6207 InsertNewInstBefore(NewRem, ICI);
6208 return new ICmpInst(ICI.getPredicate(), NewRem,
6209 Constant::getNullValue(BO->getType()));
6210 }
6211 }
6212 break;
6213 case Instruction::Add:
6214 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
6215 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6216 if (BO->hasOneUse())
6217 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6218 Subtract(RHS, BOp1C));
6219 } else if (RHSV == 0) {
6220 // Replace ((add A, B) != 0) with (A != -B) if A or B is
6221 // efficiently invertible, or if the add has just this one use.
6222 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
6223
6224 if (Value *NegVal = dyn_castNegVal(BOp1))
6225 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
6226 else if (Value *NegVal = dyn_castNegVal(BOp0))
6227 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
6228 else if (BO->hasOneUse()) {
6229 Instruction *Neg = BinaryOperator::createNeg(BOp1);
6230 InsertNewInstBefore(Neg, ICI);
6231 Neg->takeName(BO);
6232 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
6233 }
6234 }
6235 break;
6236 case Instruction::Xor:
6237 // For the xor case, we can xor two constants together, eliminating
6238 // the explicit xor.
6239 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
6240 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6241 ConstantExpr::getXor(RHS, BOC));
6242
6243 // FALLTHROUGH
6244 case Instruction::Sub:
6245 // Replace (([sub|xor] A, B) != 0) with (A != B)
6246 if (RHSV == 0)
6247 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6248 BO->getOperand(1));
6249 break;
6250
6251 case Instruction::Or:
6252 // If bits are being or'd in that are not present in the constant we
6253 // are comparing against, then the comparison could never succeed!
6254 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
6255 Constant *NotCI = ConstantExpr::getNot(RHS);
6256 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
6257 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6258 isICMP_NE));
6259 }
6260 break;
6261
6262 case Instruction::And:
6263 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6264 // If bits are being compared against that are and'd out, then the
6265 // comparison can never succeed!
6266 if ((RHSV & ~BOC->getValue()) != 0)
6267 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6268 isICMP_NE));
6269
6270 // If we have ((X & C) == C), turn it into ((X & C) != 0).
6271 if (RHS == BOC && RHSV.isPowerOf2())
6272 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
6273 ICmpInst::ICMP_NE, LHSI,
6274 Constant::getNullValue(RHS->getType()));
6275
6276 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
6277 if (isSignBit(BOC)) {
6278 Value *X = BO->getOperand(0);
6279 Constant *Zero = Constant::getNullValue(X->getType());
6280 ICmpInst::Predicate pred = isICMP_NE ?
6281 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
6282 return new ICmpInst(pred, X, Zero);
6283 }
6284
6285 // ((X & ~7) == 0) --> X < 8
6286 if (RHSV == 0 && isHighOnes(BOC)) {
6287 Value *X = BO->getOperand(0);
6288 Constant *NegX = ConstantExpr::getNeg(BOC);
6289 ICmpInst::Predicate pred = isICMP_NE ?
6290 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
6291 return new ICmpInst(pred, X, NegX);
6292 }
6293 }
6294 default: break;
6295 }
6296 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
6297 // Handle icmp {eq|ne} <intrinsic>, intcst.
6298 if (II->getIntrinsicID() == Intrinsic::bswap) {
6299 AddToWorkList(II);
6300 ICI.setOperand(0, II->getOperand(1));
6301 ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
6302 return &ICI;
6303 }
6304 }
6305 } else { // Not a ICMP_EQ/ICMP_NE
Chris Lattner28d921d2007-04-14 23:32:02 +00006306 // If the LHS is a cast from an integral value of the same size,
6307 // then since we know the RHS is a constant, try to simlify.
Chris Lattnera74deaf2007-04-03 17:43:25 +00006308 if (CastInst *Cast = dyn_cast<CastInst>(LHSI)) {
6309 Value *CastOp = Cast->getOperand(0);
6310 const Type *SrcTy = CastOp->getType();
6311 uint32_t SrcTySize = SrcTy->getPrimitiveSizeInBits();
6312 if (SrcTy->isInteger() &&
6313 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
6314 // If this is an unsigned comparison, try to make the comparison use
6315 // smaller constant values.
6316 if (ICI.getPredicate() == ICmpInst::ICMP_ULT && RHSV.isSignBit()) {
6317 // X u< 128 => X s> -1
6318 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp,
6319 ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
6320 } else if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
6321 RHSV == APInt::getSignedMaxValue(SrcTySize)) {
6322 // X u> 127 => X s< 0
6323 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp,
6324 Constant::getNullValue(SrcTy));
6325 }
6326 }
6327 }
6328 }
6329 return 0;
6330}
6331
6332/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
6333/// We only handle extending casts so far.
6334///
Reid Spencer266e42b2006-12-23 06:05:41 +00006335Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
6336 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006337 Value *LHSCIOp = LHSCI->getOperand(0);
6338 const Type *SrcTy = LHSCIOp->getType();
Reid Spencer266e42b2006-12-23 06:05:41 +00006339 const Type *DestTy = LHSCI->getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00006340 Value *RHSCIOp;
6341
Chris Lattner5aa73fe2007-05-05 22:41:33 +00006342 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
6343 // integer type is the same size as the pointer type.
6344 if (LHSCI->getOpcode() == Instruction::PtrToInt &&
6345 getTargetData().getPointerSizeInBits() ==
6346 cast<IntegerType>(DestTy)->getBitWidth()) {
6347 Value *RHSOp = 0;
6348 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Chris Lattner9b35b3e2007-05-06 07:24:03 +00006349 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Chris Lattner5aa73fe2007-05-05 22:41:33 +00006350 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
6351 RHSOp = RHSC->getOperand(0);
6352 // If the pointer types don't match, insert a bitcast.
6353 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner5a866122008-01-13 22:23:22 +00006354 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
Chris Lattner5aa73fe2007-05-05 22:41:33 +00006355 }
6356
6357 if (RHSOp)
6358 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
6359 }
6360
6361 // The code below only handles extension cast instructions, so far.
6362 // Enforce this.
Reid Spencer266e42b2006-12-23 06:05:41 +00006363 if (LHSCI->getOpcode() != Instruction::ZExt &&
6364 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattner03f06f12005-01-17 03:20:02 +00006365 return 0;
6366
Reid Spencer266e42b2006-12-23 06:05:41 +00006367 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
6368 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00006369
Reid Spencer266e42b2006-12-23 06:05:41 +00006370 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00006371 // Not an extension from the same type?
6372 RHSCIOp = CI->getOperand(0);
Reid Spencer266e42b2006-12-23 06:05:41 +00006373 if (RHSCIOp->getType() != LHSCIOp->getType())
6374 return 0;
Chris Lattner387bf3f2007-01-13 23:11:38 +00006375
Nick Lewycky8ea81e82008-01-28 03:48:02 +00006376 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Chris Lattner387bf3f2007-01-13 23:11:38 +00006377 // and the other is a zext), then we can't handle this.
6378 if (CI->getOpcode() != LHSCI->getOpcode())
6379 return 0;
6380
Nick Lewycky8ea81e82008-01-28 03:48:02 +00006381 // Deal with equality cases early.
6382 if (ICI.isEquality())
6383 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6384
6385 // A signed comparison of sign extended values simplifies into a
6386 // signed comparison.
6387 if (isSignedCmp && isSignedExt)
6388 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6389
6390 // The other three cases all fold into an unsigned comparison.
6391 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer279fa252004-11-28 21:31:15 +00006392 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00006393
Reid Spencer266e42b2006-12-23 06:05:41 +00006394 // If we aren't dealing with a constant on the RHS, exit early
6395 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
6396 if (!CI)
6397 return 0;
6398
6399 // Compute the constant that would happen if we truncated to SrcTy then
6400 // reextended to DestTy.
6401 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
6402 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
6403
6404 // If the re-extended constant didn't change...
6405 if (Res2 == CI) {
6406 // Make sure that sign of the Cmp and the sign of the Cast are the same.
6407 // For example, we might have:
6408 // %A = sext short %X to uint
6409 // %B = icmp ugt uint %A, 1330
6410 // It is incorrect to transform this into
6411 // %B = icmp ugt short %X, 1330
6412 // because %A may have negative value.
6413 //
6414 // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
6415 // OR operation is EQ/NE.
Reid Spencer542964f2007-01-11 18:21:29 +00006416 if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
Reid Spencer266e42b2006-12-23 06:05:41 +00006417 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
6418 else
6419 return 0;
6420 }
6421
6422 // The re-extended constant changed so the constant cannot be represented
6423 // in the shorter type. Consequently, we cannot emit a simple comparison.
6424
6425 // First, handle some easy cases. We know the result cannot be equal at this
6426 // point so handle the ICI.isEquality() cases
6427 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Zhou Sheng75b871f2007-01-11 12:24:14 +00006428 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00006429 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Zhou Sheng75b871f2007-01-11 12:24:14 +00006430 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00006431
6432 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
6433 // should have been folded away previously and not enter in here.
6434 Value *Result;
6435 if (isSignedCmp) {
6436 // We're performing a signed comparison.
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00006437 if (cast<ConstantInt>(CI)->getValue().isNegative())
Zhou Sheng75b871f2007-01-11 12:24:14 +00006438 Result = ConstantInt::getFalse(); // X < (small) --> false
Reid Spencer266e42b2006-12-23 06:05:41 +00006439 else
Zhou Sheng75b871f2007-01-11 12:24:14 +00006440 Result = ConstantInt::getTrue(); // X < (large) --> true
Reid Spencer266e42b2006-12-23 06:05:41 +00006441 } else {
6442 // We're performing an unsigned comparison.
6443 if (isSignedExt) {
6444 // We're performing an unsigned comp with a sign extended value.
6445 // This is true if the input is >= 0. [aka >s -1]
Zhou Sheng75b871f2007-01-11 12:24:14 +00006446 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
Reid Spencer266e42b2006-12-23 06:05:41 +00006447 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
6448 NegOne, ICI.getName()), ICI);
6449 } else {
6450 // Unsigned extend & unsigned compare -> always true.
Zhou Sheng75b871f2007-01-11 12:24:14 +00006451 Result = ConstantInt::getTrue();
Reid Spencer266e42b2006-12-23 06:05:41 +00006452 }
6453 }
6454
6455 // Finally, return the value computed.
6456 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
6457 ICI.getPredicate() == ICmpInst::ICMP_SLT) {
6458 return ReplaceInstUsesWith(ICI, Result);
6459 } else {
6460 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
6461 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
6462 "ICmp should be folded!");
6463 if (Constant *CI = dyn_cast<Constant>(Result))
6464 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
6465 else
6466 return BinaryOperator::createNot(Result);
6467 }
Chris Lattnerd1f46d32005-04-24 06:59:08 +00006468}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00006469
Reid Spencer2341c222007-02-02 02:16:23 +00006470Instruction *InstCombiner::visitShl(BinaryOperator &I) {
6471 return commonShiftTransforms(I);
6472}
6473
6474Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
6475 return commonShiftTransforms(I);
6476}
6477
6478Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner0ccb6632007-12-06 01:59:46 +00006479 if (Instruction *R = commonShiftTransforms(I))
6480 return R;
6481
6482 Value *Op0 = I.getOperand(0);
6483
6484 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
6485 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
6486 if (CSI->isAllOnesValue())
6487 return ReplaceInstUsesWith(I, CSI);
6488
6489 // See if we can turn a signed shr into an unsigned shr.
6490 if (MaskedValueIsZero(Op0,
6491 APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
6492 return BinaryOperator::createLShr(Op0, I.getOperand(1));
6493
6494 return 0;
Reid Spencer2341c222007-02-02 02:16:23 +00006495}
6496
6497Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
6498 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner113f4f42002-06-25 16:13:24 +00006499 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00006500
6501 // shl X, 0 == X and shr X, 0 == X
6502 // shl 0, X == 0 and shr 0, X == 0
Reid Spencer2341c222007-02-02 02:16:23 +00006503 if (Op1 == Constant::getNullValue(Op1->getType()) ||
Chris Lattnere6794492002-08-12 21:17:25 +00006504 Op0 == Constant::getNullValue(Op0->getType()))
6505 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00006506
Reid Spencer266e42b2006-12-23 06:05:41 +00006507 if (isa<UndefValue>(Op0)) {
6508 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner67f05452004-10-16 23:28:04 +00006509 return ReplaceInstUsesWith(I, Op0);
Reid Spencer266e42b2006-12-23 06:05:41 +00006510 else // undef << X -> 0, undef >>u X -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00006511 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6512 }
6513 if (isa<UndefValue>(Op1)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00006514 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
6515 return ReplaceInstUsesWith(I, Op0);
6516 else // X << undef, X >>u undef -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00006517 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner81a7a232004-10-16 18:11:37 +00006518 }
6519
Chris Lattner183b3362004-04-09 19:05:30 +00006520 // Try to fold constant and into select arguments.
6521 if (isa<Constant>(Op0))
6522 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00006523 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00006524 return R;
6525
Reid Spencere0fc4df2006-10-20 07:07:24 +00006526 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc635f472006-12-31 05:48:39 +00006527 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
6528 return Res;
Chris Lattner14553932006-01-06 07:12:35 +00006529 return 0;
6530}
6531
Reid Spencere0fc4df2006-10-20 07:07:24 +00006532Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer2341c222007-02-02 02:16:23 +00006533 BinaryOperator &I) {
Reid Spencer266e42b2006-12-23 06:05:41 +00006534 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner14553932006-01-06 07:12:35 +00006535
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00006536 // See if we can simplify any instructions used by the instruction whose sole
6537 // purpose is to compute bits we don't care about.
Reid Spencer6274c722007-03-23 18:46:34 +00006538 uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
6539 APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
6540 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00006541 KnownZero, KnownOne))
6542 return &I;
6543
Chris Lattner14553932006-01-06 07:12:35 +00006544 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
6545 // of a signed value.
6546 //
Zhou Shengb25806f2007-03-30 09:29:48 +00006547 if (Op1->uge(TypeBits)) {
Chris Lattnerd5fea612007-02-02 05:29:55 +00006548 if (I.getOpcode() != Instruction::AShr)
Chris Lattner14553932006-01-06 07:12:35 +00006549 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
6550 else {
Chris Lattnerd5fea612007-02-02 05:29:55 +00006551 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner14553932006-01-06 07:12:35 +00006552 return &I;
Chris Lattnerf5ce2542004-02-23 20:30:06 +00006553 }
Chris Lattner14553932006-01-06 07:12:35 +00006554 }
6555
6556 // ((X*C1) << C2) == (X * (C1 << C2))
6557 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
6558 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
6559 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
6560 return BinaryOperator::createMul(BO->getOperand(0),
6561 ConstantExpr::getShl(BOOp, Op1));
6562
6563 // Try to fold constant and into select arguments.
6564 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
6565 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6566 return R;
6567 if (isa<PHINode>(Op0))
6568 if (Instruction *NV = FoldOpIntoPhi(I))
6569 return NV;
6570
Chris Lattner74b2ab52007-12-22 09:07:47 +00006571 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
6572 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
6573 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
6574 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
6575 // place. Don't try to do this transformation in this case. Also, we
6576 // require that the input operand is a shift-by-constant so that we have
6577 // confidence that the shifts will get folded together. We could do this
6578 // xform in more cases, but it is unlikely to be profitable.
6579 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
6580 isa<ConstantInt>(TrOp->getOperand(1))) {
6581 // Okay, we'll do this xform. Make the shift of shift.
6582 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
6583 Instruction *NSh = BinaryOperator::create(I.getOpcode(), TrOp, ShAmt,
6584 I.getName());
6585 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
6586
6587 // For logical shifts, the truncation has the effect of making the high
6588 // part of the register be zeros. Emulate this by inserting an AND to
6589 // clear the top bits as needed. This 'and' will usually be zapped by
6590 // other xforms later if dead.
6591 unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
6592 unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
6593 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
6594
6595 // The mask we constructed says what the trunc would do if occurring
6596 // between the shifts. We want to know the effect *after* the second
6597 // shift. We know that it is a logical shift by a constant, so adjust the
6598 // mask as appropriate.
6599 if (I.getOpcode() == Instruction::Shl)
6600 MaskV <<= Op1->getZExtValue();
6601 else {
6602 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
6603 MaskV = MaskV.lshr(Op1->getZExtValue());
6604 }
6605
6606 Instruction *And = BinaryOperator::createAnd(NSh, ConstantInt::get(MaskV),
6607 TI->getName());
6608 InsertNewInstBefore(And, I); // shift1 & 0x00FF
6609
6610 // Return the value truncated to the interesting size.
6611 return new TruncInst(And, I.getType());
6612 }
6613 }
6614
Chris Lattner14553932006-01-06 07:12:35 +00006615 if (Op0->hasOneUse()) {
Chris Lattner14553932006-01-06 07:12:35 +00006616 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
6617 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
6618 Value *V1, *V2;
6619 ConstantInt *CC;
6620 switch (Op0BO->getOpcode()) {
Chris Lattner27cb9db2005-09-18 05:12:10 +00006621 default: break;
6622 case Instruction::Add:
6623 case Instruction::And:
6624 case Instruction::Or:
Reid Spencer2f34b982007-02-02 14:41:37 +00006625 case Instruction::Xor: {
Chris Lattner27cb9db2005-09-18 05:12:10 +00006626 // These operators commute.
6627 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00006628 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
6629 match(Op0BO->getOperand(1),
Chris Lattner14553932006-01-06 07:12:35 +00006630 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Reid Spencer0d5f9232007-02-02 14:08:20 +00006631 Instruction *YS = BinaryOperator::createShl(
Chris Lattner14553932006-01-06 07:12:35 +00006632 Op0BO->getOperand(0), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00006633 Op0BO->getName());
6634 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00006635 Instruction *X =
6636 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
6637 Op0BO->getOperand(1)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00006638 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Shengfd28a332007-03-30 17:20:39 +00006639 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Zhou Sheng5e60a4a2007-03-30 05:45:18 +00006640 return BinaryOperator::createAnd(X, ConstantInt::get(
6641 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner797dee72005-09-18 06:30:59 +00006642 }
Chris Lattner14553932006-01-06 07:12:35 +00006643
Chris Lattner797dee72005-09-18 06:30:59 +00006644 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencer2f34b982007-02-02 14:41:37 +00006645 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattnerfe53cf22007-03-05 00:11:19 +00006646 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencer2f34b982007-02-02 14:41:37 +00006647 match(Op0BOOp1,
6648 m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
Chris Lattnerfe53cf22007-03-05 00:11:19 +00006649 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
6650 V2 == Op1) {
Reid Spencer0d5f9232007-02-02 14:08:20 +00006651 Instruction *YS = BinaryOperator::createShl(
Reid Spencer2341c222007-02-02 02:16:23 +00006652 Op0BO->getOperand(0), Op1,
6653 Op0BO->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00006654 InsertNewInstBefore(YS, I); // (Y << C)
6655 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00006656 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00006657 V1->getName()+".mask");
6658 InsertNewInstBefore(XM, I); // X & (CC << C)
6659
6660 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
6661 }
Reid Spencer2f34b982007-02-02 14:41:37 +00006662 }
Chris Lattner14553932006-01-06 07:12:35 +00006663
Reid Spencer2f34b982007-02-02 14:41:37 +00006664 // FALL THROUGH.
6665 case Instruction::Sub: {
Chris Lattner27cb9db2005-09-18 05:12:10 +00006666 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00006667 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6668 match(Op0BO->getOperand(0),
Chris Lattner14553932006-01-06 07:12:35 +00006669 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Reid Spencer0d5f9232007-02-02 14:08:20 +00006670 Instruction *YS = BinaryOperator::createShl(
Reid Spencer2341c222007-02-02 02:16:23 +00006671 Op0BO->getOperand(1), Op1,
6672 Op0BO->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00006673 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00006674 Instruction *X =
Chris Lattner1df0e982006-05-31 21:14:00 +00006675 BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
Chris Lattner24cd2fa2006-02-09 07:41:14 +00006676 Op0BO->getOperand(0)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00006677 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Shengfd28a332007-03-30 17:20:39 +00006678 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Zhou Sheng5e60a4a2007-03-30 05:45:18 +00006679 return BinaryOperator::createAnd(X, ConstantInt::get(
6680 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner797dee72005-09-18 06:30:59 +00006681 }
Chris Lattner14553932006-01-06 07:12:35 +00006682
Chris Lattner1df0e982006-05-31 21:14:00 +00006683 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner797dee72005-09-18 06:30:59 +00006684 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6685 match(Op0BO->getOperand(0),
6686 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner14553932006-01-06 07:12:35 +00006687 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner24cd2fa2006-02-09 07:41:14 +00006688 cast<BinaryOperator>(Op0BO->getOperand(0))
6689 ->getOperand(0)->hasOneUse()) {
Reid Spencer0d5f9232007-02-02 14:08:20 +00006690 Instruction *YS = BinaryOperator::createShl(
Reid Spencer2341c222007-02-02 02:16:23 +00006691 Op0BO->getOperand(1), Op1,
6692 Op0BO->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00006693 InsertNewInstBefore(YS, I); // (Y << C)
6694 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00006695 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00006696 V1->getName()+".mask");
6697 InsertNewInstBefore(XM, I); // X & (CC << C)
6698
Chris Lattner1df0e982006-05-31 21:14:00 +00006699 return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
Chris Lattner797dee72005-09-18 06:30:59 +00006700 }
Chris Lattner14553932006-01-06 07:12:35 +00006701
Chris Lattner27cb9db2005-09-18 05:12:10 +00006702 break;
Reid Spencer2f34b982007-02-02 14:41:37 +00006703 }
Chris Lattner14553932006-01-06 07:12:35 +00006704 }
6705
6706
6707 // If the operand is an bitwise operator with a constant RHS, and the
6708 // shift is the only use, we can pull it out of the shift.
6709 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
6710 bool isValid = true; // Valid only for And, Or, Xor
6711 bool highBitSet = false; // Transform if high bit of constant set?
6712
6713 switch (Op0BO->getOpcode()) {
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00006714 default: isValid = false; break; // Do not perform transform!
Chris Lattner44bd3922004-10-08 03:46:20 +00006715 case Instruction::Add:
6716 isValid = isLeftShift;
6717 break;
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00006718 case Instruction::Or:
6719 case Instruction::Xor:
6720 highBitSet = false;
6721 break;
6722 case Instruction::And:
6723 highBitSet = true;
6724 break;
Chris Lattner14553932006-01-06 07:12:35 +00006725 }
6726
6727 // If this is a signed shift right, and the high bit is modified
6728 // by the logical operation, do not perform the transformation.
6729 // The highBitSet boolean indicates the value of the high bit of
6730 // the constant which would cause it to be modified for this
6731 // operation.
6732 //
Chris Lattnerd2bbbab2007-12-06 06:25:04 +00006733 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Sheng23f7a1c2007-03-28 15:02:20 +00006734 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner14553932006-01-06 07:12:35 +00006735
6736 if (isValid) {
6737 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
6738
6739 Instruction *NewShift =
Chris Lattner6e0123b2007-02-11 01:23:03 +00006740 BinaryOperator::create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner14553932006-01-06 07:12:35 +00006741 InsertNewInstBefore(NewShift, I);
Chris Lattner6e0123b2007-02-11 01:23:03 +00006742 NewShift->takeName(Op0BO);
Chris Lattner14553932006-01-06 07:12:35 +00006743
6744 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
6745 NewRHS);
6746 }
6747 }
6748 }
6749 }
6750
Chris Lattnereb372a02006-01-06 07:52:12 +00006751 // Find out if this is a shift of a shift by a constant.
Reid Spencer2341c222007-02-02 02:16:23 +00006752 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
6753 if (ShiftOp && !ShiftOp->isShift())
6754 ShiftOp = 0;
Chris Lattnereb372a02006-01-06 07:52:12 +00006755
Reid Spencere0fc4df2006-10-20 07:07:24 +00006756 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00006757 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Shengb25806f2007-03-30 09:29:48 +00006758 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
6759 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattner3e009e82007-02-05 00:57:54 +00006760 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
6761 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
6762 Value *X = ShiftOp->getOperand(0);
Chris Lattnereb372a02006-01-06 07:52:12 +00006763
Zhou Sheng56cda952007-04-02 08:20:41 +00006764 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Reid Spencer6274c722007-03-23 18:46:34 +00006765 if (AmtSum > TypeBits)
6766 AmtSum = TypeBits;
Chris Lattner3e009e82007-02-05 00:57:54 +00006767
6768 const IntegerType *Ty = cast<IntegerType>(I.getType());
6769
6770 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner6c344e52007-02-03 23:28:07 +00006771 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattner3e009e82007-02-05 00:57:54 +00006772 return BinaryOperator::create(I.getOpcode(), X,
6773 ConstantInt::get(Ty, AmtSum));
6774 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
6775 I.getOpcode() == Instruction::AShr) {
6776 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
6777 return BinaryOperator::createLShr(X, ConstantInt::get(Ty, AmtSum));
6778 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
6779 I.getOpcode() == Instruction::LShr) {
6780 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
6781 Instruction *Shift =
6782 BinaryOperator::createAShr(X, ConstantInt::get(Ty, AmtSum));
6783 InsertNewInstBefore(Shift, I);
6784
Zhou Sheng23f7a1c2007-03-28 15:02:20 +00006785 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Reid Spencer6274c722007-03-23 18:46:34 +00006786 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattnereb372a02006-01-06 07:52:12 +00006787 }
6788
Chris Lattner3e009e82007-02-05 00:57:54 +00006789 // Okay, if we get here, one shift must be left, and the other shift must be
6790 // right. See if the amounts are equal.
6791 if (ShiftAmt1 == ShiftAmt2) {
6792 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
6793 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer52830322007-03-25 21:11:44 +00006794 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Reid Spencer6274c722007-03-23 18:46:34 +00006795 return BinaryOperator::createAnd(X, ConstantInt::get(Mask));
Chris Lattner3e009e82007-02-05 00:57:54 +00006796 }
6797 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
6798 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng150f3bb2007-04-01 17:13:37 +00006799 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Reid Spencer6274c722007-03-23 18:46:34 +00006800 return BinaryOperator::createAnd(X, ConstantInt::get(Mask));
Chris Lattner3e009e82007-02-05 00:57:54 +00006801 }
6802 // We can simplify ((X << C) >>s C) into a trunc + sext.
6803 // NOTE: we could do this for any C, but that would make 'unusual' integer
6804 // types. For now, just stick to ones well-supported by the code
6805 // generators.
6806 const Type *SExtType = 0;
6807 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Sheng23f7a1c2007-03-28 15:02:20 +00006808 case 1 :
6809 case 8 :
6810 case 16 :
6811 case 32 :
6812 case 64 :
6813 case 128:
6814 SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
6815 break;
Chris Lattner3e009e82007-02-05 00:57:54 +00006816 default: break;
6817 }
6818 if (SExtType) {
6819 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
6820 InsertNewInstBefore(NewTrunc, I);
6821 return new SExtInst(NewTrunc, Ty);
6822 }
6823 // Otherwise, we can't handle it yet.
6824 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng56cda952007-04-02 08:20:41 +00006825 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnereb372a02006-01-06 07:52:12 +00006826
Chris Lattner83ac5ae92007-02-05 05:57:49 +00006827 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattner3e009e82007-02-05 00:57:54 +00006828 if (I.getOpcode() == Instruction::Shl) {
6829 assert(ShiftOp->getOpcode() == Instruction::LShr ||
6830 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattner9cbfbc22006-01-07 01:32:28 +00006831 Instruction *Shift =
Chris Lattner3e009e82007-02-05 00:57:54 +00006832 BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00006833 InsertNewInstBefore(Shift, I);
6834
Reid Spencer52830322007-03-25 21:11:44 +00006835 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
6836 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattnereb372a02006-01-06 07:52:12 +00006837 }
Chris Lattner3e009e82007-02-05 00:57:54 +00006838
Chris Lattner83ac5ae92007-02-05 05:57:49 +00006839 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattner3e009e82007-02-05 00:57:54 +00006840 if (I.getOpcode() == Instruction::LShr) {
6841 assert(ShiftOp->getOpcode() == Instruction::Shl);
6842 Instruction *Shift =
6843 BinaryOperator::createLShr(X, ConstantInt::get(Ty, ShiftDiff));
6844 InsertNewInstBefore(Shift, I);
Chris Lattnereb372a02006-01-06 07:52:12 +00006845
Reid Spencer769a5a82007-03-26 17:18:58 +00006846 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Reid Spencer6274c722007-03-23 18:46:34 +00006847 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattner27cb9db2005-09-18 05:12:10 +00006848 }
Chris Lattner3e009e82007-02-05 00:57:54 +00006849
6850 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
6851 } else {
6852 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng56cda952007-04-02 08:20:41 +00006853 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattner3e009e82007-02-05 00:57:54 +00006854
Chris Lattner83ac5ae92007-02-05 05:57:49 +00006855 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattner3e009e82007-02-05 00:57:54 +00006856 if (I.getOpcode() == Instruction::Shl) {
6857 assert(ShiftOp->getOpcode() == Instruction::LShr ||
6858 ShiftOp->getOpcode() == Instruction::AShr);
6859 Instruction *Shift =
6860 BinaryOperator::create(ShiftOp->getOpcode(), X,
6861 ConstantInt::get(Ty, ShiftDiff));
6862 InsertNewInstBefore(Shift, I);
6863
Reid Spencer52830322007-03-25 21:11:44 +00006864 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Reid Spencer6274c722007-03-23 18:46:34 +00006865 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattner3e009e82007-02-05 00:57:54 +00006866 }
6867
Chris Lattner83ac5ae92007-02-05 05:57:49 +00006868 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattner3e009e82007-02-05 00:57:54 +00006869 if (I.getOpcode() == Instruction::LShr) {
6870 assert(ShiftOp->getOpcode() == Instruction::Shl);
6871 Instruction *Shift =
6872 BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
6873 InsertNewInstBefore(Shift, I);
6874
Reid Spencer441486c2007-03-26 23:45:51 +00006875 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Reid Spencer6274c722007-03-23 18:46:34 +00006876 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattner3e009e82007-02-05 00:57:54 +00006877 }
6878
6879 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner86102b82005-01-01 16:22:27 +00006880 }
Chris Lattnereb372a02006-01-06 07:52:12 +00006881 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00006882 return 0;
6883}
6884
Chris Lattner48a44f72002-05-02 17:06:02 +00006885
Chris Lattner8f663e82005-10-29 04:36:15 +00006886/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
6887/// expression. If so, decompose it, returning some value X, such that Val is
6888/// X*Scale+Offset.
6889///
6890static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Jeff Cohen5a1c7502007-04-04 16:58:57 +00006891 int &Offset) {
Reid Spencerc635f472006-12-31 05:48:39 +00006892 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
Reid Spencere0fc4df2006-10-20 07:07:24 +00006893 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc635f472006-12-31 05:48:39 +00006894 Offset = CI->getZExtValue();
Chris Lattnerd8675e42007-10-12 05:30:59 +00006895 Scale = 0;
Reid Spencerc635f472006-12-31 05:48:39 +00006896 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattnerd8675e42007-10-12 05:30:59 +00006897 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
6898 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
6899 if (I->getOpcode() == Instruction::Shl) {
6900 // This is a value scaled by '1 << the shift amt'.
6901 Scale = 1U << RHS->getZExtValue();
6902 Offset = 0;
6903 return I->getOperand(0);
6904 } else if (I->getOpcode() == Instruction::Mul) {
6905 // This value is scaled by 'RHS'.
6906 Scale = RHS->getZExtValue();
6907 Offset = 0;
6908 return I->getOperand(0);
6909 } else if (I->getOpcode() == Instruction::Add) {
6910 // We have X+C. Check to see if we really have (X*C2)+C1,
6911 // where C1 is divisible by C2.
6912 unsigned SubScale;
6913 Value *SubVal =
6914 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
6915 Offset += RHS->getZExtValue();
6916 Scale = SubScale;
6917 return SubVal;
Chris Lattner8f663e82005-10-29 04:36:15 +00006918 }
6919 }
6920 }
6921
6922 // Otherwise, we can't look past this.
6923 Scale = 1;
6924 Offset = 0;
6925 return Val;
6926}
6927
6928
Chris Lattner216be912005-10-24 06:03:58 +00006929/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
6930/// try to eliminate the cast by moving the type information into the alloc.
Chris Lattner1db224d2007-04-27 17:44:50 +00006931Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Chris Lattner216be912005-10-24 06:03:58 +00006932 AllocationInst &AI) {
Chris Lattner1db224d2007-04-27 17:44:50 +00006933 const PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattner216be912005-10-24 06:03:58 +00006934
Chris Lattnerac87beb2005-10-24 06:22:12 +00006935 // Remove any uses of AI that are dead.
6936 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner99c6cf62007-02-15 22:52:10 +00006937
Chris Lattnerac87beb2005-10-24 06:22:12 +00006938 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
6939 Instruction *User = cast<Instruction>(*UI++);
6940 if (isInstructionTriviallyDead(User)) {
6941 while (UI != E && *UI == User)
6942 ++UI; // If this instruction uses AI more than once, don't break UI.
6943
Chris Lattnerac87beb2005-10-24 06:22:12 +00006944 ++NumDeadInst;
Bill Wendling5dbf43c2006-11-26 09:46:52 +00006945 DOUT << "IC: DCE: " << *User;
Chris Lattner51f54572007-03-02 19:59:19 +00006946 EraseInstFromFunction(*User);
Chris Lattnerac87beb2005-10-24 06:22:12 +00006947 }
6948 }
6949
Chris Lattner216be912005-10-24 06:03:58 +00006950 // Get the type really allocated and the type casted to.
6951 const Type *AllocElTy = AI.getAllocatedType();
6952 const Type *CastElTy = PTy->getElementType();
6953 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00006954
Chris Lattner945e4372007-02-14 05:52:17 +00006955 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
6956 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner355ecc02005-10-24 06:26:18 +00006957 if (CastElTyAlign < AllocElTyAlign) return 0;
6958
Chris Lattner46705b22005-10-24 06:35:18 +00006959 // If the allocation has multiple uses, only promote it if we are strictly
6960 // increasing the alignment of the resultant allocation. If we keep it the
6961 // same, we open the door to infinite loops of various kinds.
6962 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
6963
Duncan Sands44b87212007-11-01 20:53:16 +00006964 uint64_t AllocElTySize = TD->getABITypeSize(AllocElTy);
6965 uint64_t CastElTySize = TD->getABITypeSize(CastElTy);
Chris Lattnerbb171802005-10-27 05:53:56 +00006966 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00006967
Chris Lattner8270c332005-10-29 03:19:53 +00006968 // See if we can satisfy the modulus by pulling a scale out of the array
6969 // size argument.
Jeff Cohen5a1c7502007-04-04 16:58:57 +00006970 unsigned ArraySizeScale;
6971 int ArrayOffset;
Chris Lattner8f663e82005-10-29 04:36:15 +00006972 Value *NumElements = // See if the array size is a decomposable linear expr.
6973 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
6974
Chris Lattner8270c332005-10-29 03:19:53 +00006975 // If we can now satisfy the modulus, by using a non-1 scale, we really can
6976 // do the xform.
Chris Lattner8f663e82005-10-29 04:36:15 +00006977 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
6978 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattnerb3ecf962005-10-27 06:12:00 +00006979
Chris Lattner8270c332005-10-29 03:19:53 +00006980 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
6981 Value *Amt = 0;
6982 if (Scale == 1) {
6983 Amt = NumElements;
6984 } else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00006985 // If the allocation size is constant, form a constant mul expression
Reid Spencerc635f472006-12-31 05:48:39 +00006986 Amt = ConstantInt::get(Type::Int32Ty, Scale);
6987 if (isa<ConstantInt>(NumElements))
Zhou Sheng9bc8ab12007-04-02 13:45:30 +00006988 Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
Reid Spencere0fc4df2006-10-20 07:07:24 +00006989 // otherwise multiply the amount and the number of elements
Chris Lattner8270c332005-10-29 03:19:53 +00006990 else if (Scale != 1) {
6991 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
6992 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattnerb3ecf962005-10-27 06:12:00 +00006993 }
Chris Lattnerbb171802005-10-27 05:53:56 +00006994 }
6995
Jeff Cohen5a1c7502007-04-04 16:58:57 +00006996 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
6997 Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
Chris Lattner8f663e82005-10-29 04:36:15 +00006998 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
6999 Amt = InsertNewInstBefore(Tmp, AI);
7000 }
7001
Chris Lattner216be912005-10-24 06:03:58 +00007002 AllocationInst *New;
7003 if (isa<MallocInst>(AI))
Chris Lattner6e0123b2007-02-11 01:23:03 +00007004 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
Chris Lattner216be912005-10-24 06:03:58 +00007005 else
Chris Lattner6e0123b2007-02-11 01:23:03 +00007006 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
Chris Lattner216be912005-10-24 06:03:58 +00007007 InsertNewInstBefore(New, AI);
Chris Lattner6e0123b2007-02-11 01:23:03 +00007008 New->takeName(&AI);
Chris Lattner46705b22005-10-24 06:35:18 +00007009
7010 // If the allocation has multiple uses, insert a cast and change all things
7011 // that used it to use the new cast. This will also hack on CI, but it will
7012 // die soon.
7013 if (!AI.hasOneUse()) {
7014 AddUsesToWorkList(AI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007015 // New is the allocation instruction, pointer typed. AI is the original
7016 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7017 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner46705b22005-10-24 06:35:18 +00007018 InsertNewInstBefore(NewCast, AI);
7019 AI.replaceAllUsesWith(NewCast);
7020 }
Chris Lattner216be912005-10-24 06:03:58 +00007021 return ReplaceInstUsesWith(CI, New);
7022}
7023
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00007024/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerda1d04a2007-03-03 05:27:34 +00007025/// and return it as type Ty without inserting any new casts and without
7026/// changing the computed value. This is used by code that tries to decide
7027/// whether promoting or shrinking integer operations to wider or smaller types
7028/// will allow us to eliminate a truncate or extend.
7029///
7030/// This is a truncation operation if Ty is smaller than V->getType(), or an
7031/// extension operation if Ty is larger.
Dan Gohman99b7b3f2008-04-10 18:43:06 +00007032bool InstCombiner::CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
7033 unsigned CastOpc,
7034 int &NumCastsRemoved) {
Chris Lattnerda1d04a2007-03-03 05:27:34 +00007035 // We can always evaluate constants in another type.
7036 if (isa<ConstantInt>(V))
7037 return true;
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00007038
7039 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerda1d04a2007-03-03 05:27:34 +00007040 if (!I) return false;
7041
7042 const IntegerType *OrigTy = cast<IntegerType>(V->getType());
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00007043
Chris Lattnerb0418fc2007-08-02 06:11:14 +00007044 // If this is an extension or truncate, we can often eliminate it.
7045 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7046 // If this is a cast from the destination type, we can trivially eliminate
7047 // it, and this will remove a cast overall.
7048 if (I->getOperand(0)->getType() == Ty) {
7049 // If the first operand is itself a cast, and is eliminable, do not count
7050 // this as an eliminable cast. We would prefer to eliminate those two
7051 // casts first.
7052 if (!isa<CastInst>(I->getOperand(0)))
7053 ++NumCastsRemoved;
7054 return true;
7055 }
7056 }
7057
7058 // We can't extend or shrink something that has multiple uses: doing so would
7059 // require duplicating the instruction in general, which isn't profitable.
7060 if (!I->hasOneUse()) return false;
7061
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00007062 switch (I->getOpcode()) {
Chris Lattnerda1d04a2007-03-03 05:27:34 +00007063 case Instruction::Add:
7064 case Instruction::Sub:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00007065 case Instruction::And:
7066 case Instruction::Or:
7067 case Instruction::Xor:
7068 // These operators can all arbitrarily be extended or truncated.
Chris Lattnerb0418fc2007-08-02 06:11:14 +00007069 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7070 NumCastsRemoved) &&
7071 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7072 NumCastsRemoved);
Chris Lattnerda1d04a2007-03-03 05:27:34 +00007073
Nick Lewycky78712e52008-01-22 05:08:48 +00007074 case Instruction::Mul:
Nick Lewycky78712e52008-01-22 05:08:48 +00007075 // A multiply can be truncated by truncating its operands.
7076 return Ty->getBitWidth() < OrigTy->getBitWidth() &&
7077 CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7078 NumCastsRemoved) &&
7079 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7080 NumCastsRemoved);
7081
Chris Lattner960acb02006-11-29 07:18:39 +00007082 case Instruction::Shl:
Chris Lattnerda1d04a2007-03-03 05:27:34 +00007083 // If we are truncating the result of this SHL, and if it's a shift of a
7084 // constant amount, we can always perform a SHL in a smaller type.
7085 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Shengfd28a332007-03-30 17:20:39 +00007086 uint32_t BitWidth = Ty->getBitWidth();
7087 if (BitWidth < OrigTy->getBitWidth() &&
7088 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattnerb0418fc2007-08-02 06:11:14 +00007089 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7090 NumCastsRemoved);
Chris Lattnerda1d04a2007-03-03 05:27:34 +00007091 }
7092 break;
7093 case Instruction::LShr:
Chris Lattnerda1d04a2007-03-03 05:27:34 +00007094 // If this is a truncate of a logical shr, we can truncate it to a smaller
7095 // lshr iff we know that the bits we would otherwise be shifting in are
7096 // already zeros.
7097 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Shengfd28a332007-03-30 17:20:39 +00007098 uint32_t OrigBitWidth = OrigTy->getBitWidth();
7099 uint32_t BitWidth = Ty->getBitWidth();
7100 if (BitWidth < OrigBitWidth &&
Chris Lattnerda1d04a2007-03-03 05:27:34 +00007101 MaskedValueIsZero(I->getOperand(0),
Zhou Shengfd28a332007-03-30 17:20:39 +00007102 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7103 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattnerb0418fc2007-08-02 06:11:14 +00007104 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7105 NumCastsRemoved);
Chris Lattnerda1d04a2007-03-03 05:27:34 +00007106 }
7107 }
Chris Lattner960acb02006-11-29 07:18:39 +00007108 break;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007109 case Instruction::ZExt:
7110 case Instruction::SExt:
Chris Lattnerb0418fc2007-08-02 06:11:14 +00007111 case Instruction::Trunc:
7112 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattnerdc2cf222007-08-02 17:23:38 +00007113 // can safely replace it. Note that replacing it does not reduce the number
7114 // of casts in the input.
7115 if (I->getOpcode() == CastOpc)
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00007116 return true;
Chris Lattnere8045672007-09-10 23:46:29 +00007117
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007118 break;
7119 default:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00007120 // TODO: Can handle more cases here.
7121 break;
7122 }
7123
7124 return false;
7125}
7126
7127/// EvaluateInDifferentType - Given an expression that
7128/// CanEvaluateInDifferentType returns true for, actually insert the code to
7129/// evaluate the expression.
Reid Spencer74a528b2006-12-13 18:21:21 +00007130Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerda1d04a2007-03-03 05:27:34 +00007131 bool isSigned) {
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00007132 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencer74a528b2006-12-13 18:21:21 +00007133 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00007134
7135 // Otherwise, it must be an instruction.
7136 Instruction *I = cast<Instruction>(V);
Chris Lattnerd0622b62006-05-20 23:14:03 +00007137 Instruction *Res = 0;
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00007138 switch (I->getOpcode()) {
Chris Lattnerda1d04a2007-03-03 05:27:34 +00007139 case Instruction::Add:
7140 case Instruction::Sub:
Nick Lewycky78712e52008-01-22 05:08:48 +00007141 case Instruction::Mul:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00007142 case Instruction::And:
7143 case Instruction::Or:
Chris Lattnerda1d04a2007-03-03 05:27:34 +00007144 case Instruction::Xor:
Chris Lattner960acb02006-11-29 07:18:39 +00007145 case Instruction::AShr:
7146 case Instruction::LShr:
7147 case Instruction::Shl: {
Reid Spencer74a528b2006-12-13 18:21:21 +00007148 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerda1d04a2007-03-03 05:27:34 +00007149 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7150 Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
7151 LHS, RHS, I->getName());
Chris Lattner960acb02006-11-29 07:18:39 +00007152 break;
7153 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007154 case Instruction::Trunc:
7155 case Instruction::ZExt:
7156 case Instruction::SExt:
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007157 // If the source type of the cast is the type we're trying for then we can
Chris Lattnerb0418fc2007-08-02 06:11:14 +00007158 // just return the source. There's no need to insert it because it is not
7159 // new.
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00007160 if (I->getOperand(0)->getType() == Ty)
7161 return I->getOperand(0);
7162
Chris Lattnerb0418fc2007-08-02 06:11:14 +00007163 // Otherwise, must be the same type of case, so just reinsert a new one.
7164 Res = CastInst::create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
7165 Ty, I->getName());
7166 break;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007167 default:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00007168 // TODO: Can handle more cases here.
7169 assert(0 && "Unreachable!");
7170 break;
7171 }
7172
7173 return InsertNewInstBefore(Res, *I);
7174}
7175
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007176/// @brief Implement the transforms common to all CastInst visitors.
7177Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner55d4bda2003-06-23 21:59:52 +00007178 Value *Src = CI.getOperand(0);
7179
Dan Gohmanb5650eb2007-05-11 21:10:54 +00007180 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007181 // eliminate it now.
Chris Lattner86102b82005-01-01 16:22:27 +00007182 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007183 if (Instruction::CastOps opc =
7184 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
7185 // The first cast (CSrc) is eliminable so we need to fix up or replace
7186 // the second cast (CI). CSrc will then have a good chance of being dead.
7187 return CastInst::create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner650b6da2002-08-02 20:00:25 +00007188 }
7189 }
Chris Lattner03841652004-05-25 04:29:21 +00007190
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007191 // If we are casting a select then fold the cast into the select
Chris Lattner86102b82005-01-01 16:22:27 +00007192 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
7193 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
7194 return NV;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007195
7196 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner6a4adcd2004-09-29 05:07:12 +00007197 if (isa<PHINode>(Src))
7198 if (Instruction *NV = FoldOpIntoPhi(CI))
7199 return NV;
Chris Lattnerb19a5c62006-04-12 18:09:35 +00007200
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007201 return 0;
7202}
7203
Chris Lattner1db224d2007-04-27 17:44:50 +00007204/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
7205Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
7206 Value *Src = CI.getOperand(0);
7207
Chris Lattner1db224d2007-04-27 17:44:50 +00007208 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattneracbf6a42007-04-28 00:57:34 +00007209 // If casting the result of a getelementptr instruction with no offset, turn
7210 // this into a cast of the original pointer!
Chris Lattner1db224d2007-04-27 17:44:50 +00007211 if (GEP->hasAllZeroIndices()) {
7212 // Changing the cast operand is usually not a good idea but it is safe
7213 // here because the pointer operand is being replaced with another
7214 // pointer operand so the opcode doesn't need to change.
Chris Lattneracbf6a42007-04-28 00:57:34 +00007215 AddToWorkList(GEP);
Chris Lattner1db224d2007-04-27 17:44:50 +00007216 CI.setOperand(0, GEP->getOperand(0));
7217 return &CI;
7218 }
Chris Lattneracbf6a42007-04-28 00:57:34 +00007219
7220 // If the GEP has a single use, and the base pointer is a bitcast, and the
7221 // GEP computes a constant offset, see if we can convert these three
7222 // instructions into fewer. This typically happens with unions and other
7223 // non-type-safe code.
7224 if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
7225 if (GEP->hasAllConstantIndices()) {
7226 // We are guaranteed to get a constant from EmitGEPOffset.
7227 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
7228 int64_t Offset = OffsetV->getSExtValue();
7229
7230 // Get the base pointer input of the bitcast, and the type it points to.
7231 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
7232 const Type *GEPIdxTy =
7233 cast<PointerType>(OrigBase->getType())->getElementType();
7234 if (GEPIdxTy->isSized()) {
7235 SmallVector<Value*, 8> NewIndices;
7236
Chris Lattner5c827bd2007-05-05 01:59:31 +00007237 // Start with the index over the outer type. Note that the type size
7238 // might be zero (even if the offset isn't zero) if the indexed type
7239 // is something like [0 x {int, int}]
Chris Lattneracbf6a42007-04-28 00:57:34 +00007240 const Type *IntPtrTy = TD->getIntPtrType();
Chris Lattner5c827bd2007-05-05 01:59:31 +00007241 int64_t FirstIdx = 0;
Duncan Sands44b87212007-11-01 20:53:16 +00007242 if (int64_t TySize = TD->getABITypeSize(GEPIdxTy)) {
Chris Lattner5c827bd2007-05-05 01:59:31 +00007243 FirstIdx = Offset/TySize;
7244 Offset %= TySize;
Chris Lattneracbf6a42007-04-28 00:57:34 +00007245
Chris Lattner5c827bd2007-05-05 01:59:31 +00007246 // Handle silly modulus not returning values values [0..TySize).
7247 if (Offset < 0) {
7248 --FirstIdx;
7249 Offset += TySize;
7250 assert(Offset >= 0);
7251 }
Chris Lattner361e9812007-05-05 22:32:24 +00007252 assert((uint64_t)Offset < (uint64_t)TySize &&"Out of range offset");
Chris Lattneracbf6a42007-04-28 00:57:34 +00007253 }
7254
7255 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattneracbf6a42007-04-28 00:57:34 +00007256
7257 // Index into the types. If we fail, set OrigBase to null.
7258 while (Offset) {
7259 if (const StructType *STy = dyn_cast<StructType>(GEPIdxTy)) {
7260 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattner234f96d2007-05-15 00:16:00 +00007261 if (Offset < (int64_t)SL->getSizeInBytes()) {
7262 unsigned Elt = SL->getElementContainingOffset(Offset);
7263 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
Chris Lattneracbf6a42007-04-28 00:57:34 +00007264
Chris Lattner234f96d2007-05-15 00:16:00 +00007265 Offset -= SL->getElementOffset(Elt);
7266 GEPIdxTy = STy->getElementType(Elt);
7267 } else {
7268 // Otherwise, we can't index into this, bail out.
7269 Offset = 0;
7270 OrigBase = 0;
7271 }
Chris Lattneracbf6a42007-04-28 00:57:34 +00007272 } else if (isa<ArrayType>(GEPIdxTy) || isa<VectorType>(GEPIdxTy)) {
7273 const SequentialType *STy = cast<SequentialType>(GEPIdxTy);
Duncan Sands44b87212007-11-01 20:53:16 +00007274 if (uint64_t EltSize = TD->getABITypeSize(STy->getElementType())){
Chris Lattner234f96d2007-05-15 00:16:00 +00007275 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
7276 Offset %= EltSize;
7277 } else {
7278 NewIndices.push_back(ConstantInt::get(IntPtrTy, 0));
7279 }
Chris Lattneracbf6a42007-04-28 00:57:34 +00007280 GEPIdxTy = STy->getElementType();
7281 } else {
7282 // Otherwise, we can't index into this, bail out.
7283 Offset = 0;
7284 OrigBase = 0;
7285 }
7286 }
7287 if (OrigBase) {
7288 // If we were able to index down into an element, create the GEP
7289 // and bitcast the result. This eliminates one bitcast, potentially
7290 // two.
Gabor Greife9ecc682008-04-06 20:25:17 +00007291 Instruction *NGEP = GetElementPtrInst::Create(OrigBase,
7292 NewIndices.begin(),
7293 NewIndices.end(), "");
Chris Lattneracbf6a42007-04-28 00:57:34 +00007294 InsertNewInstBefore(NGEP, CI);
7295 NGEP->takeName(GEP);
7296
Chris Lattneracbf6a42007-04-28 00:57:34 +00007297 if (isa<BitCastInst>(CI))
7298 return new BitCastInst(NGEP, CI.getType());
7299 assert(isa<PtrToIntInst>(CI));
7300 return new PtrToIntInst(NGEP, CI.getType());
7301 }
7302 }
7303 }
7304 }
Chris Lattner1db224d2007-04-27 17:44:50 +00007305 }
7306
7307 return commonCastTransforms(CI);
7308}
7309
7310
7311
Chris Lattnerda1d04a2007-03-03 05:27:34 +00007312/// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
7313/// integer types. This function implements the common transforms for all those
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007314/// cases.
7315/// @brief Implement the transforms common to CastInst with integer operands
7316Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
7317 if (Instruction *Result = commonCastTransforms(CI))
7318 return Result;
7319
7320 Value *Src = CI.getOperand(0);
7321 const Type *SrcTy = Src->getType();
7322 const Type *DestTy = CI.getType();
Zhou Sheng56cda952007-04-02 08:20:41 +00007323 uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
7324 uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007325
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007326 // See if we can simplify any instructions used by the LHS whose sole
7327 // purpose is to compute bits we don't care about.
Reid Spencer4154e732007-03-22 20:56:53 +00007328 APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
7329 if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007330 KnownZero, KnownOne))
7331 return &CI;
7332
7333 // If the source isn't an instruction or has more than one use then we
7334 // can't do anything more.
Reid Spencer266e42b2006-12-23 06:05:41 +00007335 Instruction *SrcI = dyn_cast<Instruction>(Src);
7336 if (!SrcI || !Src->hasOneUse())
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007337 return 0;
7338
Chris Lattnerda1d04a2007-03-03 05:27:34 +00007339 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007340 int NumCastsRemoved = 0;
Chris Lattnerda1d04a2007-03-03 05:27:34 +00007341 if (!isa<BitCastInst>(CI) &&
7342 CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
Chris Lattnerb0418fc2007-08-02 06:11:14 +00007343 CI.getOpcode(), NumCastsRemoved)) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007344 // If this cast is a truncate, evaluting in a different type always
Chris Lattnerb0418fc2007-08-02 06:11:14 +00007345 // eliminates the cast, so it is always a win. If this is a zero-extension,
7346 // we need to do an AND to maintain the clear top-part of the computation,
7347 // so we require that the input have eliminated at least one cast. If this
7348 // is a sign extension, we insert two new casts (to do the extension) so we
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007349 // require that two casts have been eliminated.
Chris Lattnerda1d04a2007-03-03 05:27:34 +00007350 bool DoXForm;
7351 switch (CI.getOpcode()) {
7352 default:
7353 // All the others use floating point so we shouldn't actually
7354 // get here because of the check above.
7355 assert(0 && "Unknown cast type");
7356 case Instruction::Trunc:
7357 DoXForm = true;
7358 break;
7359 case Instruction::ZExt:
7360 DoXForm = NumCastsRemoved >= 1;
7361 break;
7362 case Instruction::SExt:
7363 DoXForm = NumCastsRemoved >= 2;
7364 break;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007365 }
7366
7367 if (DoXForm) {
Reid Spencer74a528b2006-12-13 18:21:21 +00007368 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
7369 CI.getOpcode() == Instruction::SExt);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007370 assert(Res->getType() == DestTy);
7371 switch (CI.getOpcode()) {
7372 default: assert(0 && "Unknown cast type!");
7373 case Instruction::Trunc:
7374 case Instruction::BitCast:
7375 // Just replace this cast with the result.
7376 return ReplaceInstUsesWith(CI, Res);
7377 case Instruction::ZExt: {
7378 // We need to emit an AND to clear the high bits.
7379 assert(SrcBitSize < DestBitSize && "Not a zext?");
Chris Lattner9d5aace2007-04-02 05:48:58 +00007380 Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
7381 SrcBitSize));
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007382 return BinaryOperator::createAnd(Res, C);
7383 }
7384 case Instruction::SExt:
7385 // We need to emit a cast to truncate, then a cast to sext.
7386 return CastInst::create(Instruction::SExt,
Reid Spencer13bc5d72006-12-12 09:18:51 +00007387 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
7388 CI), DestTy);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007389 }
7390 }
7391 }
7392
7393 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
7394 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
7395
7396 switch (SrcI->getOpcode()) {
7397 case Instruction::Add:
7398 case Instruction::Mul:
7399 case Instruction::And:
7400 case Instruction::Or:
7401 case Instruction::Xor:
Chris Lattnera74deaf2007-04-03 17:43:25 +00007402 // If we are discarding information, rewrite.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007403 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
7404 // Don't insert two casts if they cannot be eliminated. We allow
7405 // two casts to be inserted if the sizes are the same. This could
7406 // only be converting signedness, which is a noop.
7407 if (DestBitSize == SrcBitSize ||
Reid Spencer266e42b2006-12-23 06:05:41 +00007408 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
7409 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer2a499b02006-12-13 17:19:09 +00007410 Instruction::CastOps opcode = CI.getOpcode();
Reid Spencer13bc5d72006-12-12 09:18:51 +00007411 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7412 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
7413 return BinaryOperator::create(
7414 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007415 }
7416 }
7417
7418 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
7419 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
7420 SrcI->getOpcode() == Instruction::Xor &&
Zhou Sheng75b871f2007-01-11 12:24:14 +00007421 Op1 == ConstantInt::getTrue() &&
Reid Spencer266e42b2006-12-23 06:05:41 +00007422 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007423 Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007424 return BinaryOperator::createXor(New, ConstantInt::get(CI.getType(), 1));
7425 }
7426 break;
7427 case Instruction::SDiv:
7428 case Instruction::UDiv:
7429 case Instruction::SRem:
7430 case Instruction::URem:
7431 // If we are just changing the sign, rewrite.
7432 if (DestBitSize == SrcBitSize) {
7433 // Don't insert two casts if they cannot be eliminated. We allow
7434 // two casts to be inserted if the sizes are the same. This could
7435 // only be converting signedness, which is a noop.
Reid Spencer266e42b2006-12-23 06:05:41 +00007436 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
7437 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007438 Value *Op0c = InsertOperandCastBefore(Instruction::BitCast,
7439 Op0, DestTy, SrcI);
7440 Value *Op1c = InsertOperandCastBefore(Instruction::BitCast,
7441 Op1, DestTy, SrcI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007442 return BinaryOperator::create(
7443 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7444 }
7445 }
7446 break;
7447
7448 case Instruction::Shl:
7449 // Allow changing the sign of the source operand. Do not allow
7450 // changing the size of the shift, UNLESS the shift amount is a
7451 // constant. We must not change variable sized shifts to a smaller
7452 // size, because it is undefined to shift more bits out than exist
7453 // in the value.
7454 if (DestBitSize == SrcBitSize ||
7455 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007456 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
7457 Instruction::BitCast : Instruction::Trunc);
7458 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
Reid Spencer2341c222007-02-02 02:16:23 +00007459 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
Reid Spencer0d5f9232007-02-02 14:08:20 +00007460 return BinaryOperator::createShl(Op0c, Op1c);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007461 }
7462 break;
7463 case Instruction::AShr:
7464 // If this is a signed shr, and if all bits shifted in are about to be
7465 // truncated off, turn it into an unsigned shr to allow greater
7466 // simplifications.
7467 if (DestBitSize < SrcBitSize &&
7468 isa<ConstantInt>(Op1)) {
Zhou Shengfd28a332007-03-30 17:20:39 +00007469 uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007470 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
7471 // Insert the new logical shift right.
Reid Spencer0d5f9232007-02-02 14:08:20 +00007472 return BinaryOperator::createLShr(Op0, Op1);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007473 }
7474 }
7475 break;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007476 }
7477 return 0;
7478}
7479
Chris Lattner74ff60f2007-04-11 06:57:46 +00007480Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattnerd747f012006-11-29 07:04:07 +00007481 if (Instruction *Result = commonIntCastTransforms(CI))
7482 return Result;
7483
7484 Value *Src = CI.getOperand(0);
7485 const Type *Ty = CI.getType();
Zhou Sheng56cda952007-04-02 08:20:41 +00007486 uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
7487 uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
Chris Lattnerd747f012006-11-29 07:04:07 +00007488
7489 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
7490 switch (SrcI->getOpcode()) {
7491 default: break;
7492 case Instruction::LShr:
7493 // We can shrink lshr to something smaller if we know the bits shifted in
7494 // are already zeros.
7495 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
Zhou Shengfd28a332007-03-30 17:20:39 +00007496 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
Chris Lattnerd747f012006-11-29 07:04:07 +00007497
7498 // Get a mask for the bits shifting in.
Zhou Sheng2777a312007-03-28 09:19:01 +00007499 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
Reid Spencer13bc5d72006-12-12 09:18:51 +00007500 Value* SrcIOp0 = SrcI->getOperand(0);
7501 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
Chris Lattnerd747f012006-11-29 07:04:07 +00007502 if (ShAmt >= DestBitWidth) // All zeros.
7503 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
7504
7505 // Okay, we can shrink this. Truncate the input, then return a new
7506 // shift.
Reid Spencer2341c222007-02-02 02:16:23 +00007507 Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
7508 Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
7509 Ty, CI);
Reid Spencer0d5f9232007-02-02 14:08:20 +00007510 return BinaryOperator::createLShr(V1, V2);
Chris Lattnerd747f012006-11-29 07:04:07 +00007511 }
Chris Lattnerc209b582006-12-05 01:26:29 +00007512 } else { // This is a variable shr.
7513
7514 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
7515 // more LLVM instructions, but allows '1 << Y' to be hoisted if
7516 // loop-invariant and CSE'd.
Reid Spencer542964f2007-01-11 18:21:29 +00007517 if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
Chris Lattnerc209b582006-12-05 01:26:29 +00007518 Value *One = ConstantInt::get(SrcI->getType(), 1);
7519
Reid Spencer2341c222007-02-02 02:16:23 +00007520 Value *V = InsertNewInstBefore(
Reid Spencer0d5f9232007-02-02 14:08:20 +00007521 BinaryOperator::createShl(One, SrcI->getOperand(1),
Reid Spencer2341c222007-02-02 02:16:23 +00007522 "tmp"), CI);
Chris Lattnerc209b582006-12-05 01:26:29 +00007523 V = InsertNewInstBefore(BinaryOperator::createAnd(V,
7524 SrcI->getOperand(0),
7525 "tmp"), CI);
7526 Value *Zero = Constant::getNullValue(V->getType());
Reid Spencer266e42b2006-12-23 06:05:41 +00007527 return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
Chris Lattnerc209b582006-12-05 01:26:29 +00007528 }
Chris Lattnerd747f012006-11-29 07:04:07 +00007529 }
7530 break;
7531 }
7532 }
7533
7534 return 0;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007535}
7536
Evan Chengc3cf9f82008-03-24 00:21:34 +00007537/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
7538/// in order to eliminate the icmp.
7539Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
7540 bool DoXform) {
7541 // If we are just checking for a icmp eq of a single bit and zext'ing it
7542 // to an integer, then shift the bit to the appropriate place and then
7543 // cast to integer to avoid the comparison.
7544 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7545 const APInt &Op1CV = Op1C->getValue();
7546
7547 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
7548 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
7549 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7550 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
7551 if (!DoXform) return ICI;
7552
7553 Value *In = ICI->getOperand(0);
7554 Value *Sh = ConstantInt::get(In->getType(),
7555 In->getType()->getPrimitiveSizeInBits()-1);
7556 In = InsertNewInstBefore(BinaryOperator::createLShr(In, Sh,
7557 In->getName()+".lobit"),
7558 CI);
7559 if (In->getType() != CI.getType())
7560 In = CastInst::createIntegerCast(In, CI.getType(),
7561 false/*ZExt*/, "tmp", &CI);
7562
7563 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
7564 Constant *One = ConstantInt::get(In->getType(), 1);
7565 In = InsertNewInstBefore(BinaryOperator::createXor(In, One,
7566 In->getName()+".not"),
7567 CI);
7568 }
7569
7570 return ReplaceInstUsesWith(CI, In);
7571 }
7572
7573
7574
7575 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
7576 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7577 // zext (X == 1) to i32 --> X iff X has only the low bit set.
7578 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
7579 // zext (X != 0) to i32 --> X iff X has only the low bit set.
7580 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
7581 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
7582 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7583 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
7584 // This only works for EQ and NE
7585 ICI->isEquality()) {
7586 // If Op1C some other power of two, convert:
7587 uint32_t BitWidth = Op1C->getType()->getBitWidth();
7588 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
7589 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
7590 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
7591
7592 APInt KnownZeroMask(~KnownZero);
7593 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
7594 if (!DoXform) return ICI;
7595
7596 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
7597 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
7598 // (X&4) == 2 --> false
7599 // (X&4) != 2 --> true
7600 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
7601 Res = ConstantExpr::getZExt(Res, CI.getType());
7602 return ReplaceInstUsesWith(CI, Res);
7603 }
7604
7605 uint32_t ShiftAmt = KnownZeroMask.logBase2();
7606 Value *In = ICI->getOperand(0);
7607 if (ShiftAmt) {
7608 // Perform a logical shr by shiftamt.
7609 // Insert the shift to put the result in the low bit.
7610 In = InsertNewInstBefore(BinaryOperator::createLShr(In,
7611 ConstantInt::get(In->getType(), ShiftAmt),
7612 In->getName()+".lobit"), CI);
7613 }
7614
7615 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
7616 Constant *One = ConstantInt::get(In->getType(), 1);
7617 In = BinaryOperator::createXor(In, One, "tmp");
7618 InsertNewInstBefore(cast<Instruction>(In), CI);
7619 }
7620
7621 if (CI.getType() == In->getType())
7622 return ReplaceInstUsesWith(CI, In);
7623 else
7624 return CastInst::createIntegerCast(In, CI.getType(), false/*ZExt*/);
7625 }
7626 }
7627 }
7628
7629 return 0;
7630}
7631
Chris Lattner74ff60f2007-04-11 06:57:46 +00007632Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007633 // If one of the common conversion will work ..
7634 if (Instruction *Result = commonIntCastTransforms(CI))
7635 return Result;
7636
7637 Value *Src = CI.getOperand(0);
7638
7639 // If this is a cast of a cast
7640 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007641 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
7642 // types and if the sizes are just right we can convert this into a logical
7643 // 'and' which will be much cheaper than the pair of casts.
7644 if (isa<TruncInst>(CSrc)) {
7645 // Get the sizes of the types involved
7646 Value *A = CSrc->getOperand(0);
Zhou Sheng56cda952007-04-02 08:20:41 +00007647 uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
7648 uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
7649 uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007650 // If we're actually extending zero bits and the trunc is a no-op
7651 if (MidSize < DstSize && SrcSize == DstSize) {
7652 // Replace both of the casts with an And of the type mask.
Zhou Sheng2777a312007-03-28 09:19:01 +00007653 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Reid Spencer4154e732007-03-22 20:56:53 +00007654 Constant *AndConst = ConstantInt::get(AndValue);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007655 Instruction *And =
7656 BinaryOperator::createAnd(CSrc->getOperand(0), AndConst);
7657 // Unfortunately, if the type changed, we need to cast it back.
7658 if (And->getType() != CI.getType()) {
7659 And->setName(CSrc->getName()+".mask");
7660 InsertNewInstBefore(And, CI);
Reid Spencerbb65ebf2006-12-12 23:36:14 +00007661 And = CastInst::createIntegerCast(And, CI.getType(), false/*ZExt*/);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007662 }
7663 return And;
7664 }
7665 }
7666 }
7667
Evan Chengc3cf9f82008-03-24 00:21:34 +00007668 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
7669 return transformZExtICmp(ICI, CI);
Chris Lattnerd0f79422007-04-11 06:53:04 +00007670
Evan Chengc3cf9f82008-03-24 00:21:34 +00007671 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
7672 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
7673 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
7674 // of the (zext icmp) will be transformed.
7675 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
7676 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
7677 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
7678 (transformZExtICmp(LHS, CI, false) ||
7679 transformZExtICmp(RHS, CI, false))) {
7680 Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
7681 Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
7682 return BinaryOperator::create(Instruction::Or, LCast, RCast);
Chris Lattner7ddbff02007-04-11 05:45:39 +00007683 }
Evan Chengc3cf9f82008-03-24 00:21:34 +00007684 }
7685
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007686 return 0;
7687}
7688
Chris Lattner74ff60f2007-04-11 06:57:46 +00007689Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattner20f23722007-04-11 06:12:58 +00007690 if (Instruction *I = commonIntCastTransforms(CI))
7691 return I;
7692
Chris Lattner74ff60f2007-04-11 06:57:46 +00007693 Value *Src = CI.getOperand(0);
7694
7695 // sext (x <s 0) -> ashr x, 31 -> all ones if signed
7696 // sext (x >s -1) -> ashr x, 31 -> all ones if not signed
7697 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
7698 // If we are just checking for a icmp eq of a single bit and zext'ing it
7699 // to an integer, then shift the bit to the appropriate place and then
7700 // cast to integer to avoid the comparison.
7701 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7702 const APInt &Op1CV = Op1C->getValue();
7703
7704 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
7705 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
7706 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7707 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
7708 Value *In = ICI->getOperand(0);
7709 Value *Sh = ConstantInt::get(In->getType(),
7710 In->getType()->getPrimitiveSizeInBits()-1);
7711 In = InsertNewInstBefore(BinaryOperator::createAShr(In, Sh,
Chris Lattner28d921d2007-04-14 23:32:02 +00007712 In->getName()+".lobit"),
Chris Lattner74ff60f2007-04-11 06:57:46 +00007713 CI);
7714 if (In->getType() != CI.getType())
7715 In = CastInst::createIntegerCast(In, CI.getType(),
7716 true/*SExt*/, "tmp", &CI);
7717
7718 if (ICI->getPredicate() == ICmpInst::ICMP_SGT)
7719 In = InsertNewInstBefore(BinaryOperator::createNot(In,
7720 In->getName()+".not"), CI);
7721
7722 return ReplaceInstUsesWith(CI, In);
7723 }
7724 }
7725 }
7726
Chris Lattner20f23722007-04-11 06:12:58 +00007727 return 0;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007728}
7729
Chris Lattnerfa1e7ee2008-01-27 05:29:54 +00007730/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
7731/// in the specified FP type without changing its value.
Chris Lattner3b187622008-04-20 00:41:09 +00007732static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
Chris Lattnerfa1e7ee2008-01-27 05:29:54 +00007733 APFloat F = CFP->getValueAPF();
7734 if (F.convert(Sem, APFloat::rmNearestTiesToEven) == APFloat::opOK)
Chris Lattner3b187622008-04-20 00:41:09 +00007735 return ConstantFP::get(F);
Chris Lattnerfa1e7ee2008-01-27 05:29:54 +00007736 return 0;
7737}
7738
7739/// LookThroughFPExtensions - If this is an fp extension instruction, look
7740/// through it until we get the source value.
7741static Value *LookThroughFPExtensions(Value *V) {
7742 if (Instruction *I = dyn_cast<Instruction>(V))
7743 if (I->getOpcode() == Instruction::FPExt)
7744 return LookThroughFPExtensions(I->getOperand(0));
7745
7746 // If this value is a constant, return the constant in the smallest FP type
7747 // that can accurately represent it. This allows us to turn
7748 // (float)((double)X+2.0) into x+2.0f.
7749 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
7750 if (CFP->getType() == Type::PPC_FP128Ty)
7751 return V; // No constant folding of this.
7752 // See if the value can be truncated to float and then reextended.
Chris Lattner3b187622008-04-20 00:41:09 +00007753 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
Chris Lattnerfa1e7ee2008-01-27 05:29:54 +00007754 return V;
7755 if (CFP->getType() == Type::DoubleTy)
7756 return V; // Won't shrink.
Chris Lattner3b187622008-04-20 00:41:09 +00007757 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
Chris Lattnerfa1e7ee2008-01-27 05:29:54 +00007758 return V;
7759 // Don't try to shrink to various long double types.
7760 }
7761
7762 return V;
7763}
7764
7765Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
7766 if (Instruction *I = commonCastTransforms(CI))
7767 return I;
7768
7769 // If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are
7770 // smaller than the destination type, we can eliminate the truncate by doing
7771 // the add as the smaller type. This applies to add/sub/mul/div as well as
7772 // many builtins (sqrt, etc).
7773 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
7774 if (OpI && OpI->hasOneUse()) {
7775 switch (OpI->getOpcode()) {
7776 default: break;
7777 case Instruction::Add:
7778 case Instruction::Sub:
7779 case Instruction::Mul:
7780 case Instruction::FDiv:
7781 case Instruction::FRem:
7782 const Type *SrcTy = OpI->getType();
7783 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
7784 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
7785 if (LHSTrunc->getType() != SrcTy &&
7786 RHSTrunc->getType() != SrcTy) {
7787 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
7788 // If the source types were both smaller than the destination type of
7789 // the cast, do this xform.
7790 if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
7791 RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
7792 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
7793 CI.getType(), CI);
7794 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
7795 CI.getType(), CI);
7796 return BinaryOperator::create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
7797 }
7798 }
7799 break;
7800 }
7801 }
7802 return 0;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007803}
7804
7805Instruction *InstCombiner::visitFPExt(CastInst &CI) {
7806 return commonCastTransforms(CI);
7807}
7808
7809Instruction *InstCombiner::visitFPToUI(CastInst &CI) {
Reid Spencerad05ee92006-11-30 23:13:36 +00007810 return commonCastTransforms(CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007811}
7812
7813Instruction *InstCombiner::visitFPToSI(CastInst &CI) {
Reid Spencerad05ee92006-11-30 23:13:36 +00007814 return commonCastTransforms(CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007815}
7816
7817Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
7818 return commonCastTransforms(CI);
7819}
7820
7821Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
7822 return commonCastTransforms(CI);
7823}
7824
7825Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
Chris Lattner1db224d2007-04-27 17:44:50 +00007826 return commonPointerCastTransforms(CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007827}
7828
Chris Lattner2940c5c2008-01-08 07:23:51 +00007829Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
7830 if (Instruction *I = commonCastTransforms(CI))
7831 return I;
7832
7833 const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
7834 if (!DestPointee->isSized()) return 0;
7835
7836 // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
7837 ConstantInt *Cst;
7838 Value *X;
7839 if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
7840 m_ConstantInt(Cst)))) {
7841 // If the source and destination operands have the same type, see if this
7842 // is a single-index GEP.
7843 if (X->getType() == CI.getType()) {
7844 // Get the size of the pointee type.
Bill Wendling68a930b2008-03-14 05:12:19 +00007845 uint64_t Size = TD->getABITypeSize(DestPointee);
Chris Lattner2940c5c2008-01-08 07:23:51 +00007846
7847 // Convert the constant to intptr type.
7848 APInt Offset = Cst->getValue();
7849 Offset.sextOrTrunc(TD->getPointerSizeInBits());
7850
7851 // If Offset is evenly divisible by Size, we can do this xform.
7852 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7853 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
Gabor Greife9ecc682008-04-06 20:25:17 +00007854 return GetElementPtrInst::Create(X, ConstantInt::get(Offset));
Chris Lattner2940c5c2008-01-08 07:23:51 +00007855 }
7856 }
7857 // TODO: Could handle other cases, e.g. where add is indexing into field of
7858 // struct etc.
7859 } else if (CI.getOperand(0)->hasOneUse() &&
7860 match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
7861 // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
7862 // "inttoptr+GEP" instead of "add+intptr".
7863
7864 // Get the size of the pointee type.
7865 uint64_t Size = TD->getABITypeSize(DestPointee);
7866
7867 // Convert the constant to intptr type.
7868 APInt Offset = Cst->getValue();
7869 Offset.sextOrTrunc(TD->getPointerSizeInBits());
7870
7871 // If Offset is evenly divisible by Size, we can do this xform.
7872 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7873 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
7874
7875 Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
7876 "tmp"), CI);
Gabor Greife9ecc682008-04-06 20:25:17 +00007877 return GetElementPtrInst::Create(P, ConstantInt::get(Offset), "tmp");
Chris Lattner2940c5c2008-01-08 07:23:51 +00007878 }
7879 }
7880 return 0;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007881}
7882
Chris Lattner1db224d2007-04-27 17:44:50 +00007883Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007884 // If the operands are integer typed then apply the integer transforms,
7885 // otherwise just apply the common ones.
7886 Value *Src = CI.getOperand(0);
7887 const Type *SrcTy = Src->getType();
7888 const Type *DestTy = CI.getType();
7889
Chris Lattner03c49532007-01-15 02:27:26 +00007890 if (SrcTy->isInteger() && DestTy->isInteger()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007891 if (Instruction *Result = commonIntCastTransforms(CI))
7892 return Result;
Chris Lattner1db224d2007-04-27 17:44:50 +00007893 } else if (isa<PointerType>(SrcTy)) {
7894 if (Instruction *I = commonPointerCastTransforms(CI))
7895 return I;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007896 } else {
7897 if (Instruction *Result = commonCastTransforms(CI))
7898 return Result;
7899 }
7900
7901
7902 // Get rid of casts from one type to the same type. These are useless and can
7903 // be replaced by the operand.
7904 if (DestTy == Src->getType())
7905 return ReplaceInstUsesWith(CI, Src);
7906
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007907 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattner1db224d2007-04-27 17:44:50 +00007908 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
7909 const Type *DstElTy = DstPTy->getElementType();
7910 const Type *SrcElTy = SrcPTy->getElementType();
7911
Nate Begemanf2b0b0e2008-03-31 00:22:16 +00007912 // If the address spaces don't match, don't eliminate the bitcast, which is
7913 // required for changing types.
7914 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
7915 return 0;
7916
Chris Lattner1db224d2007-04-27 17:44:50 +00007917 // If we are casting a malloc or alloca to a pointer to a type of the same
7918 // size, rewrite the allocation instruction to allocate the "right" type.
7919 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
7920 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
7921 return V;
7922
Chris Lattner361e9812007-05-05 22:32:24 +00007923 // If the source and destination are pointers, and this cast is equivalent
7924 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
Chris Lattner1db224d2007-04-27 17:44:50 +00007925 // This can enhance SROA and other transforms that want type-safe pointers.
7926 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
7927 unsigned NumZeros = 0;
7928 while (SrcElTy != DstElTy &&
7929 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
7930 SrcElTy->getNumContainedTypes() /* not "{}" */) {
7931 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
7932 ++NumZeros;
7933 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00007934
Chris Lattner1db224d2007-04-27 17:44:50 +00007935 // If we found a path from the src to dest, create the getelementptr now.
7936 if (SrcElTy == DstElTy) {
7937 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Gabor Greife9ecc682008-04-06 20:25:17 +00007938 return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "",
7939 ((Instruction*) NULL));
Chris Lattnerb19a5c62006-04-12 18:09:35 +00007940 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007941 }
Chris Lattnerdfae8be2003-07-24 17:35:25 +00007942
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007943 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
7944 if (SVI->hasOneUse()) {
7945 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
7946 // a bitconvert to a vector with the same # elts.
Reid Spencerd84d35b2007-02-15 02:26:10 +00007947 if (isa<VectorType>(DestTy) &&
7948 cast<VectorType>(DestTy)->getNumElements() ==
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007949 SVI->getType()->getNumElements()) {
7950 CastInst *Tmp;
7951 // If either of the operands is a cast from CI.getType(), then
7952 // evaluating the shuffle in the casted destination's type will allow
7953 // us to eliminate at least one cast.
7954 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
7955 Tmp->getOperand(0)->getType() == DestTy) ||
7956 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
7957 Tmp->getOperand(0)->getType() == DestTy)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007958 Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
7959 SVI->getOperand(0), DestTy, &CI);
7960 Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
7961 SVI->getOperand(1), DestTy, &CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007962 // Return a new shuffle vector. Use the same element ID's, as we
7963 // know the vector types match #elts.
7964 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner99155be2006-05-25 23:24:33 +00007965 }
7966 }
7967 }
7968 }
Chris Lattner260ab202002-04-18 17:39:14 +00007969 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +00007970}
7971
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007972/// GetSelectFoldableOperands - We want to turn code that looks like this:
7973/// %C = or %A, %B
7974/// %D = select %cond, %C, %A
7975/// into:
7976/// %C = select %cond, %B, 0
7977/// %D = or %A, %C
7978///
7979/// Assuming that the specified instruction is an operand to the select, return
7980/// a bitmask indicating which operands of this instruction are foldable if they
7981/// equal the other incoming value of the select.
7982///
7983static unsigned GetSelectFoldableOperands(Instruction *I) {
7984 switch (I->getOpcode()) {
7985 case Instruction::Add:
7986 case Instruction::Mul:
7987 case Instruction::And:
7988 case Instruction::Or:
7989 case Instruction::Xor:
7990 return 3; // Can fold through either operand.
7991 case Instruction::Sub: // Can only fold on the amount subtracted.
7992 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencerfdff9382006-11-08 06:47:33 +00007993 case Instruction::LShr:
7994 case Instruction::AShr:
Misha Brukmanb1c93172005-04-21 23:48:37 +00007995 return 1;
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007996 default:
7997 return 0; // Cannot fold
7998 }
7999}
8000
8001/// GetSelectFoldableConstant - For the same transformation as the previous
8002/// function, return the identity constant that goes into the select.
8003static Constant *GetSelectFoldableConstant(Instruction *I) {
8004 switch (I->getOpcode()) {
8005 default: assert(0 && "This cannot happen!"); abort();
8006 case Instruction::Add:
8007 case Instruction::Sub:
8008 case Instruction::Or:
8009 case Instruction::Xor:
Chris Lattner56e4d3d2004-04-09 23:46:01 +00008010 case Instruction::Shl:
Reid Spencerfdff9382006-11-08 06:47:33 +00008011 case Instruction::LShr:
8012 case Instruction::AShr:
Reid Spencer2341c222007-02-02 02:16:23 +00008013 return Constant::getNullValue(I->getType());
Chris Lattner56e4d3d2004-04-09 23:46:01 +00008014 case Instruction::And:
Chris Lattner37338922007-06-15 06:23:19 +00008015 return Constant::getAllOnesValue(I->getType());
Chris Lattner56e4d3d2004-04-09 23:46:01 +00008016 case Instruction::Mul:
8017 return ConstantInt::get(I->getType(), 1);
8018 }
8019}
8020
Chris Lattner411336f2005-01-19 21:50:18 +00008021/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
8022/// have the same opcode and only one use each. Try to simplify this.
8023Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
8024 Instruction *FI) {
8025 if (TI->getNumOperands() == 1) {
8026 // If this is a non-volatile load or a cast from the same type,
8027 // merge.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008028 if (TI->isCast()) {
Chris Lattner411336f2005-01-19 21:50:18 +00008029 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
8030 return 0;
8031 } else {
8032 return 0; // unknown unary op.
8033 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00008034
Chris Lattner411336f2005-01-19 21:50:18 +00008035 // Fold this by inserting a select from the input values.
Gabor Greife9ecc682008-04-06 20:25:17 +00008036 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
8037 FI->getOperand(0), SI.getName()+".v");
Chris Lattner411336f2005-01-19 21:50:18 +00008038 InsertNewInstBefore(NewSI, SI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008039 return CastInst::create(Instruction::CastOps(TI->getOpcode()), NewSI,
8040 TI->getType());
Chris Lattner411336f2005-01-19 21:50:18 +00008041 }
8042
Reid Spencer2341c222007-02-02 02:16:23 +00008043 // Only handle binary operators here.
8044 if (!isa<BinaryOperator>(TI))
Chris Lattner411336f2005-01-19 21:50:18 +00008045 return 0;
8046
8047 // Figure out if the operations have any operands in common.
8048 Value *MatchOp, *OtherOpT, *OtherOpF;
8049 bool MatchIsOpZero;
8050 if (TI->getOperand(0) == FI->getOperand(0)) {
8051 MatchOp = TI->getOperand(0);
8052 OtherOpT = TI->getOperand(1);
8053 OtherOpF = FI->getOperand(1);
8054 MatchIsOpZero = true;
8055 } else if (TI->getOperand(1) == FI->getOperand(1)) {
8056 MatchOp = TI->getOperand(1);
8057 OtherOpT = TI->getOperand(0);
8058 OtherOpF = FI->getOperand(0);
8059 MatchIsOpZero = false;
8060 } else if (!TI->isCommutative()) {
8061 return 0;
8062 } else if (TI->getOperand(0) == FI->getOperand(1)) {
8063 MatchOp = TI->getOperand(0);
8064 OtherOpT = TI->getOperand(1);
8065 OtherOpF = FI->getOperand(0);
8066 MatchIsOpZero = true;
8067 } else if (TI->getOperand(1) == FI->getOperand(0)) {
8068 MatchOp = TI->getOperand(1);
8069 OtherOpT = TI->getOperand(0);
8070 OtherOpF = FI->getOperand(1);
8071 MatchIsOpZero = true;
8072 } else {
8073 return 0;
8074 }
8075
8076 // If we reach here, they do have operations in common.
Gabor Greife9ecc682008-04-06 20:25:17 +00008077 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
8078 OtherOpF, SI.getName()+".v");
Chris Lattner411336f2005-01-19 21:50:18 +00008079 InsertNewInstBefore(NewSI, SI);
8080
8081 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
8082 if (MatchIsOpZero)
8083 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
8084 else
8085 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner411336f2005-01-19 21:50:18 +00008086 }
Reid Spencer2f34b982007-02-02 14:41:37 +00008087 assert(0 && "Shouldn't get here");
8088 return 0;
Chris Lattner411336f2005-01-19 21:50:18 +00008089}
8090
Chris Lattnerb909e8b2004-03-12 05:52:32 +00008091Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattner533bc492004-03-30 19:37:13 +00008092 Value *CondVal = SI.getCondition();
8093 Value *TrueVal = SI.getTrueValue();
8094 Value *FalseVal = SI.getFalseValue();
8095
8096 // select true, X, Y -> X
8097 // select false, X, Y -> Y
Zhou Sheng75b871f2007-01-11 12:24:14 +00008098 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencercddc9df2007-01-12 04:24:46 +00008099 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattner533bc492004-03-30 19:37:13 +00008100
8101 // select C, X, X -> X
8102 if (TrueVal == FalseVal)
8103 return ReplaceInstUsesWith(SI, TrueVal);
8104
Chris Lattner81a7a232004-10-16 18:11:37 +00008105 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
8106 return ReplaceInstUsesWith(SI, FalseVal);
8107 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
8108 return ReplaceInstUsesWith(SI, TrueVal);
8109 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
8110 if (isa<Constant>(TrueVal))
8111 return ReplaceInstUsesWith(SI, TrueVal);
8112 else
8113 return ReplaceInstUsesWith(SI, FalseVal);
8114 }
8115
Reid Spencer542964f2007-01-11 18:21:29 +00008116 if (SI.getType() == Type::Int1Ty) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +00008117 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencercddc9df2007-01-12 04:24:46 +00008118 if (C->getZExtValue()) {
Chris Lattner1c631e82004-04-08 04:43:23 +00008119 // Change: A = select B, true, C --> A = or B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00008120 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00008121 } else {
8122 // Change: A = select B, false, C --> A = and !B, C
8123 Value *NotCond =
8124 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
8125 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00008126 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00008127 }
Reid Spencer7a9c62b2007-01-12 07:05:14 +00008128 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencercddc9df2007-01-12 04:24:46 +00008129 if (C->getZExtValue() == false) {
Chris Lattner1c631e82004-04-08 04:43:23 +00008130 // Change: A = select B, C, false --> A = and B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00008131 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00008132 } else {
8133 // Change: A = select B, C, true --> A = or !B, C
8134 Value *NotCond =
8135 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
8136 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00008137 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00008138 }
8139 }
Chris Lattnerc00e8ad2007-11-25 21:27:53 +00008140
8141 // select a, b, a -> a&b
8142 // select a, a, b -> a|b
8143 if (CondVal == TrueVal)
8144 return BinaryOperator::createOr(CondVal, FalseVal);
8145 else if (CondVal == FalseVal)
8146 return BinaryOperator::createAnd(CondVal, TrueVal);
Zhou Sheng75b871f2007-01-11 12:24:14 +00008147 }
Chris Lattner1c631e82004-04-08 04:43:23 +00008148
Chris Lattner183b3362004-04-09 19:05:30 +00008149 // Selecting between two integer constants?
8150 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
8151 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattner20f23722007-04-11 06:12:58 +00008152 // select C, 1, 0 -> zext C to int
Reid Spencer959a21d2007-03-23 21:24:59 +00008153 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008154 return CastInst::create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer959a21d2007-03-23 21:24:59 +00008155 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattner20f23722007-04-11 06:12:58 +00008156 // select C, 0, 1 -> zext !C to int
Chris Lattner183b3362004-04-09 19:05:30 +00008157 Value *NotCond =
8158 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattnercf7baf32004-04-09 18:19:44 +00008159 "not."+CondVal->getName()), SI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008160 return CastInst::create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattnercf7baf32004-04-09 18:19:44 +00008161 }
Chris Lattner20f23722007-04-11 06:12:58 +00008162
8163 // FIXME: Turn select 0/-1 and -1/0 into sext from condition!
Chris Lattner35167c32004-06-09 07:59:58 +00008164
Reid Spencer266e42b2006-12-23 06:05:41 +00008165 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattner380c7e92006-09-20 04:44:59 +00008166
Reid Spencer266e42b2006-12-23 06:05:41 +00008167 // (x <s 0) ? -1 : 0 -> ashr x, 31
Reid Spencer959a21d2007-03-23 21:24:59 +00008168 if (TrueValC->isAllOnesValue() && FalseValC->isZero())
Chris Lattner380c7e92006-09-20 04:44:59 +00008169 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
Chris Lattner20f23722007-04-11 06:12:58 +00008170 if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
Chris Lattner380c7e92006-09-20 04:44:59 +00008171 // The comparison constant and the result are not neccessarily the
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008172 // same width. Make an all-ones value by inserting a AShr.
Chris Lattner380c7e92006-09-20 04:44:59 +00008173 Value *X = IC->getOperand(0);
Zhou Sheng56cda952007-04-02 08:20:41 +00008174 uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
Reid Spencer2341c222007-02-02 02:16:23 +00008175 Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
8176 Instruction *SRA = BinaryOperator::create(Instruction::AShr, X,
8177 ShAmt, "ones");
Chris Lattner380c7e92006-09-20 04:44:59 +00008178 InsertNewInstBefore(SRA, SI);
8179
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008180 // Finally, convert to the type of the select RHS. We figure out
8181 // if this requires a SExt, Trunc or BitCast based on the sizes.
8182 Instruction::CastOps opc = Instruction::BitCast;
Zhou Sheng56cda952007-04-02 08:20:41 +00008183 uint32_t SRASize = SRA->getType()->getPrimitiveSizeInBits();
8184 uint32_t SISize = SI.getType()->getPrimitiveSizeInBits();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008185 if (SRASize < SISize)
8186 opc = Instruction::SExt;
8187 else if (SRASize > SISize)
8188 opc = Instruction::Trunc;
8189 return CastInst::create(opc, SRA, SI.getType());
Chris Lattner380c7e92006-09-20 04:44:59 +00008190 }
8191 }
8192
8193
8194 // If one of the constants is zero (we know they can't both be) and we
Chris Lattner20f23722007-04-11 06:12:58 +00008195 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattner380c7e92006-09-20 04:44:59 +00008196 // non-constant value, eliminate this whole mess. This corresponds to
8197 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer959a21d2007-03-23 21:24:59 +00008198 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattnerb3f24c92006-09-18 04:22:48 +00008199 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner35167c32004-06-09 07:59:58 +00008200 cast<Constant>(IC->getOperand(1))->isNullValue())
8201 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
8202 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00008203 isa<ConstantInt>(ICA->getOperand(1)) &&
8204 (ICA->getOperand(1) == TrueValC ||
8205 ICA->getOperand(1) == FalseValC) &&
Chris Lattner35167c32004-06-09 07:59:58 +00008206 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
8207 // Okay, now we know that everything is set up, we just don't
Reid Spencer266e42b2006-12-23 06:05:41 +00008208 // know whether we have a icmp_ne or icmp_eq and whether the
8209 // true or false val is the zero.
Reid Spencer959a21d2007-03-23 21:24:59 +00008210 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencer266e42b2006-12-23 06:05:41 +00008211 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner35167c32004-06-09 07:59:58 +00008212 Value *V = ICA;
8213 if (ShouldNotVal)
8214 V = InsertNewInstBefore(BinaryOperator::create(
8215 Instruction::Xor, V, ICA->getOperand(1)), SI);
8216 return ReplaceInstUsesWith(SI, V);
8217 }
Chris Lattner380c7e92006-09-20 04:44:59 +00008218 }
Chris Lattner533bc492004-03-30 19:37:13 +00008219 }
Chris Lattner623fba12004-04-10 22:21:27 +00008220
8221 // See if we are selecting two values based on a comparison of the two values.
Reid Spencer266e42b2006-12-23 06:05:41 +00008222 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
8223 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattner623fba12004-04-10 22:21:27 +00008224 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen9d559cf2007-10-03 17:45:27 +00008225 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8226 // This is not safe in general for floating point:
8227 // consider X== -0, Y== +0.
8228 // It becomes safe if either operand is a nonzero constant.
8229 ConstantFP *CFPt, *CFPf;
8230 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8231 !CFPt->getValueAPF().isZero()) ||
8232 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8233 !CFPf->getValueAPF().isZero()))
Chris Lattner623fba12004-04-10 22:21:27 +00008234 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen9d559cf2007-10-03 17:45:27 +00008235 }
Chris Lattner623fba12004-04-10 22:21:27 +00008236 // Transform (X != Y) ? X : Y -> X
Reid Spencer266e42b2006-12-23 06:05:41 +00008237 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattner623fba12004-04-10 22:21:27 +00008238 return ReplaceInstUsesWith(SI, TrueVal);
8239 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8240
Reid Spencer266e42b2006-12-23 06:05:41 +00008241 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattner623fba12004-04-10 22:21:27 +00008242 // Transform (X == Y) ? Y : X -> X
Dale Johannesen9d559cf2007-10-03 17:45:27 +00008243 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8244 // This is not safe in general for floating point:
8245 // consider X== -0, Y== +0.
8246 // It becomes safe if either operand is a nonzero constant.
8247 ConstantFP *CFPt, *CFPf;
8248 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8249 !CFPt->getValueAPF().isZero()) ||
8250 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8251 !CFPf->getValueAPF().isZero()))
8252 return ReplaceInstUsesWith(SI, FalseVal);
8253 }
Chris Lattner623fba12004-04-10 22:21:27 +00008254 // Transform (X != Y) ? Y : X -> Y
Reid Spencer266e42b2006-12-23 06:05:41 +00008255 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8256 return ReplaceInstUsesWith(SI, TrueVal);
8257 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8258 }
8259 }
8260
8261 // See if we are selecting two values based on a comparison of the two values.
8262 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
8263 if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
8264 // Transform (X == Y) ? X : Y -> Y
8265 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8266 return ReplaceInstUsesWith(SI, FalseVal);
8267 // Transform (X != Y) ? X : Y -> X
8268 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
8269 return ReplaceInstUsesWith(SI, TrueVal);
8270 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8271
8272 } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
8273 // Transform (X == Y) ? Y : X -> X
8274 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8275 return ReplaceInstUsesWith(SI, FalseVal);
8276 // Transform (X != Y) ? Y : X -> Y
8277 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
Chris Lattner24cf0202004-04-11 01:39:19 +00008278 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner623fba12004-04-10 22:21:27 +00008279 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8280 }
8281 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00008282
Chris Lattnera04c9042005-01-13 22:52:24 +00008283 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
8284 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
8285 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattnera04c9042005-01-13 22:52:24 +00008286 Instruction *AddOp = 0, *SubOp = 0;
8287
Chris Lattner411336f2005-01-19 21:50:18 +00008288 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
8289 if (TI->getOpcode() == FI->getOpcode())
8290 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
8291 return IV;
8292
8293 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
8294 // even legal for FP.
Chris Lattnera04c9042005-01-13 22:52:24 +00008295 if (TI->getOpcode() == Instruction::Sub &&
8296 FI->getOpcode() == Instruction::Add) {
8297 AddOp = FI; SubOp = TI;
8298 } else if (FI->getOpcode() == Instruction::Sub &&
8299 TI->getOpcode() == Instruction::Add) {
8300 AddOp = TI; SubOp = FI;
8301 }
8302
8303 if (AddOp) {
8304 Value *OtherAddOp = 0;
8305 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
8306 OtherAddOp = AddOp->getOperand(1);
8307 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
8308 OtherAddOp = AddOp->getOperand(0);
8309 }
8310
8311 if (OtherAddOp) {
Chris Lattnerb580d262006-02-24 18:05:58 +00008312 // So at this point we know we have (Y -> OtherAddOp):
8313 // select C, (add X, Y), (sub X, Z)
8314 Value *NegVal; // Compute -Z
8315 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
8316 NegVal = ConstantExpr::getNeg(C);
8317 } else {
8318 NegVal = InsertNewInstBefore(
8319 BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattnera04c9042005-01-13 22:52:24 +00008320 }
Chris Lattnerb580d262006-02-24 18:05:58 +00008321
8322 Value *NewTrueOp = OtherAddOp;
8323 Value *NewFalseOp = NegVal;
8324 if (AddOp != TI)
8325 std::swap(NewTrueOp, NewFalseOp);
8326 Instruction *NewSel =
Gabor Greife9ecc682008-04-06 20:25:17 +00008327 SelectInst::Create(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
Chris Lattnerb580d262006-02-24 18:05:58 +00008328
8329 NewSel = InsertNewInstBefore(NewSel, SI);
8330 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
Chris Lattnera04c9042005-01-13 22:52:24 +00008331 }
8332 }
8333 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00008334
Chris Lattner56e4d3d2004-04-09 23:46:01 +00008335 // See if we can fold the select into one of our operands.
Chris Lattner03c49532007-01-15 02:27:26 +00008336 if (SI.getType()->isInteger()) {
Chris Lattner56e4d3d2004-04-09 23:46:01 +00008337 // See the comment above GetSelectFoldableOperands for a description of the
8338 // transformation we are doing here.
8339 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
8340 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
8341 !isa<Constant>(FalseVal))
8342 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
8343 unsigned OpToFold = 0;
8344 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
8345 OpToFold = 1;
8346 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
8347 OpToFold = 2;
8348 }
8349
8350 if (OpToFold) {
8351 Constant *C = GetSelectFoldableConstant(TVI);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00008352 Instruction *NewSel =
Gabor Greife9ecc682008-04-06 20:25:17 +00008353 SelectInst::Create(SI.getCondition(), TVI->getOperand(2-OpToFold), C);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00008354 InsertNewInstBefore(NewSel, SI);
Chris Lattner6e0123b2007-02-11 01:23:03 +00008355 NewSel->takeName(TVI);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00008356 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
8357 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00008358 else {
8359 assert(0 && "Unknown instruction!!");
8360 }
8361 }
8362 }
Chris Lattner6862fbd2004-09-29 17:40:11 +00008363
Chris Lattner56e4d3d2004-04-09 23:46:01 +00008364 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
8365 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
8366 !isa<Constant>(TrueVal))
8367 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
8368 unsigned OpToFold = 0;
8369 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
8370 OpToFold = 1;
8371 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
8372 OpToFold = 2;
8373 }
8374
8375 if (OpToFold) {
8376 Constant *C = GetSelectFoldableConstant(FVI);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00008377 Instruction *NewSel =
Gabor Greife9ecc682008-04-06 20:25:17 +00008378 SelectInst::Create(SI.getCondition(), C, FVI->getOperand(2-OpToFold));
Chris Lattner56e4d3d2004-04-09 23:46:01 +00008379 InsertNewInstBefore(NewSel, SI);
Chris Lattner6e0123b2007-02-11 01:23:03 +00008380 NewSel->takeName(FVI);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00008381 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
8382 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
Reid Spencer2341c222007-02-02 02:16:23 +00008383 else
Chris Lattner56e4d3d2004-04-09 23:46:01 +00008384 assert(0 && "Unknown instruction!!");
Chris Lattner56e4d3d2004-04-09 23:46:01 +00008385 }
8386 }
8387 }
Chris Lattnerd6f636a2005-04-24 07:30:14 +00008388
8389 if (BinaryOperator::isNot(CondVal)) {
8390 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
8391 SI.setOperand(1, FalseVal);
8392 SI.setOperand(2, TrueVal);
8393 return &SI;
8394 }
8395
Chris Lattnerb909e8b2004-03-12 05:52:32 +00008396 return 0;
8397}
8398
Dan Gohman99b7b3f2008-04-10 18:43:06 +00008399/// EnforceKnownAlignment - If the specified pointer points to an object that
8400/// we control, modify the object's alignment to PrefAlign. This isn't
8401/// often possible though. If alignment is important, a more reliable approach
8402/// is to simply align all global variables and allocation instructions to
8403/// their preferred alignment from the beginning.
8404///
8405static unsigned EnforceKnownAlignment(Value *V,
8406 unsigned Align, unsigned PrefAlign) {
Chris Lattnera8e4b4b2007-08-09 19:05:49 +00008407
Dan Gohman99b7b3f2008-04-10 18:43:06 +00008408 User *U = dyn_cast<User>(V);
8409 if (!U) return Align;
8410
8411 switch (getOpcode(U)) {
8412 default: break;
8413 case Instruction::BitCast:
8414 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
8415 case Instruction::GetElementPtr: {
Chris Lattner82f2ef22006-03-06 20:18:44 +00008416 // If all indexes are zero, it is just the alignment of the base pointer.
8417 bool AllZeroOperands = true;
Dan Gohman99b7b3f2008-04-10 18:43:06 +00008418 for (unsigned i = 1, e = U->getNumOperands(); i != e; ++i)
8419 if (!isa<Constant>(U->getOperand(i)) ||
8420 !cast<Constant>(U->getOperand(i))->isNullValue()) {
Chris Lattner82f2ef22006-03-06 20:18:44 +00008421 AllZeroOperands = false;
8422 break;
8423 }
Chris Lattnera8e4b4b2007-08-09 19:05:49 +00008424
8425 if (AllZeroOperands) {
8426 // Treat this like a bitcast.
Dan Gohman99b7b3f2008-04-10 18:43:06 +00008427 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattnera8e4b4b2007-08-09 19:05:49 +00008428 }
Dan Gohman99b7b3f2008-04-10 18:43:06 +00008429 break;
Chris Lattner82f2ef22006-03-06 20:18:44 +00008430 }
Dan Gohman99b7b3f2008-04-10 18:43:06 +00008431 }
8432
8433 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
8434 // If there is a large requested alignment and we can, bump up the alignment
8435 // of the global.
8436 if (!GV->isDeclaration()) {
8437 GV->setAlignment(PrefAlign);
8438 Align = PrefAlign;
8439 }
8440 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
8441 // If there is a requested alignment and if this is an alloca, round up. We
8442 // don't do this for malloc, because some systems can't respect the request.
8443 if (isa<AllocaInst>(AI)) {
8444 AI->setAlignment(PrefAlign);
8445 Align = PrefAlign;
8446 }
8447 }
8448
8449 return Align;
8450}
8451
8452/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
8453/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
8454/// and it is more than the alignment of the ultimate object, see if we can
8455/// increase the alignment of the ultimate object, making this check succeed.
8456unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
8457 unsigned PrefAlign) {
8458 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
8459 sizeof(PrefAlign) * CHAR_BIT;
8460 APInt Mask = APInt::getAllOnesValue(BitWidth);
8461 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8462 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
8463 unsigned TrailZ = KnownZero.countTrailingOnes();
8464 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
8465
8466 if (PrefAlign > Align)
8467 Align = EnforceKnownAlignment(V, Align, PrefAlign);
8468
8469 // We don't need to make any adjustment.
8470 return Align;
Chris Lattner82f2ef22006-03-06 20:18:44 +00008471}
8472
Chris Lattner57974c82008-01-13 23:50:23 +00008473Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohman99b7b3f2008-04-10 18:43:06 +00008474 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
8475 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattner57974c82008-01-13 23:50:23 +00008476 unsigned MinAlign = std::min(DstAlign, SrcAlign);
8477 unsigned CopyAlign = MI->getAlignment()->getZExtValue();
8478
8479 if (CopyAlign < MinAlign) {
8480 MI->setAlignment(ConstantInt::get(Type::Int32Ty, MinAlign));
8481 return MI;
8482 }
8483
8484 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
8485 // load/store.
8486 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
8487 if (MemOpLength == 0) return 0;
8488
Chris Lattner92bd7852008-01-14 00:28:35 +00008489 // Source and destination pointer types are always "i8*" for intrinsic. See
8490 // if the size is something we can handle with a single primitive load/store.
8491 // A single load+store correctly handles overlapping memory in the memmove
8492 // case.
Chris Lattner57974c82008-01-13 23:50:23 +00008493 unsigned Size = MemOpLength->getZExtValue();
8494 if (Size == 0 || Size > 8 || (Size&(Size-1)))
Chris Lattner92bd7852008-01-14 00:28:35 +00008495 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattner57974c82008-01-13 23:50:23 +00008496
Chris Lattner92bd7852008-01-14 00:28:35 +00008497 // Use an integer load+store unless we can find something better.
Chris Lattner57974c82008-01-13 23:50:23 +00008498 Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
Chris Lattner92bd7852008-01-14 00:28:35 +00008499
8500 // Memcpy forces the use of i8* for the source and destination. That means
8501 // that if you're using memcpy to move one double around, you'll get a cast
8502 // from double* to i8*. We'd much rather use a double load+store rather than
8503 // an i64 load+store, here because this improves the odds that the source or
8504 // dest address will be promotable. See if we can find a better type than the
8505 // integer datatype.
8506 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
8507 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
8508 if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
8509 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
8510 // down through these levels if so.
8511 while (!SrcETy->isFirstClassType()) {
8512 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
8513 if (STy->getNumElements() == 1)
8514 SrcETy = STy->getElementType(0);
8515 else
8516 break;
8517 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
8518 if (ATy->getNumElements() == 1)
8519 SrcETy = ATy->getElementType();
8520 else
8521 break;
8522 } else
8523 break;
8524 }
8525
8526 if (SrcETy->isFirstClassType())
8527 NewPtrTy = PointerType::getUnqual(SrcETy);
8528 }
8529 }
8530
8531
Chris Lattner57974c82008-01-13 23:50:23 +00008532 // If the memcpy/memmove provides better alignment info than we can
8533 // infer, use it.
8534 SrcAlign = std::max(SrcAlign, CopyAlign);
8535 DstAlign = std::max(DstAlign, CopyAlign);
8536
8537 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
8538 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
Chris Lattner92bd7852008-01-14 00:28:35 +00008539 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
8540 InsertNewInstBefore(L, *MI);
8541 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
8542
8543 // Set the size of the copy to 0, it will be deleted on the next iteration.
8544 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
8545 return MI;
Chris Lattner57974c82008-01-13 23:50:23 +00008546}
Chris Lattnerb909e8b2004-03-12 05:52:32 +00008547
Chris Lattnerc66b2232006-01-13 20:11:04 +00008548/// visitCallInst - CallInst simplification. This mostly only handles folding
8549/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
8550/// the heavy lifting.
8551///
Chris Lattner970c33a2003-06-19 17:00:31 +00008552Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattnerc66b2232006-01-13 20:11:04 +00008553 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
8554 if (!II) return visitCallSite(&CI);
8555
Chris Lattner51ea1272004-02-28 05:22:00 +00008556 // Intrinsics cannot occur in an invoke, so handle them here instead of in
8557 // visitCallSite.
Chris Lattnerc66b2232006-01-13 20:11:04 +00008558 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner00648e12004-10-12 04:52:52 +00008559 bool Changed = false;
8560
8561 // memmove/cpy/set of zero bytes is a noop.
8562 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
8563 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
8564
Chris Lattner00648e12004-10-12 04:52:52 +00008565 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencere0fc4df2006-10-20 07:07:24 +00008566 if (CI->getZExtValue() == 1) {
Chris Lattner00648e12004-10-12 04:52:52 +00008567 // Replace the instruction with just byte operations. We would
8568 // transform other cases to loads/stores, but we don't know if
8569 // alignment is sufficient.
8570 }
Chris Lattner51ea1272004-02-28 05:22:00 +00008571 }
8572
Chris Lattner00648e12004-10-12 04:52:52 +00008573 // If we have a memmove and the source operation is a constant global,
8574 // then the source and dest pointers can't alias, so we can change this
8575 // into a call to memcpy.
Chris Lattner57974c82008-01-13 23:50:23 +00008576 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Chris Lattner00648e12004-10-12 04:52:52 +00008577 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
8578 if (GVSrc->isConstant()) {
8579 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner5a866122008-01-13 22:23:22 +00008580 Intrinsic::ID MemCpyID;
8581 if (CI.getOperand(3)->getType() == Type::Int32Ty)
8582 MemCpyID = Intrinsic::memcpy_i32;
Chris Lattner681ef2f2006-03-03 01:34:17 +00008583 else
Chris Lattner5a866122008-01-13 22:23:22 +00008584 MemCpyID = Intrinsic::memcpy_i64;
8585 CI.setOperand(0, Intrinsic::getDeclaration(M, MemCpyID));
Chris Lattner00648e12004-10-12 04:52:52 +00008586 Changed = true;
8587 }
Chris Lattner82f2ef22006-03-06 20:18:44 +00008588 }
Chris Lattner00648e12004-10-12 04:52:52 +00008589
Chris Lattner82f2ef22006-03-06 20:18:44 +00008590 // If we can determine a pointer alignment that is bigger than currently
8591 // set, update the alignment.
8592 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
Chris Lattner57974c82008-01-13 23:50:23 +00008593 if (Instruction *I = SimplifyMemTransfer(MI))
8594 return I;
Chris Lattner82f2ef22006-03-06 20:18:44 +00008595 } else if (isa<MemSetInst>(MI)) {
Dan Gohman99b7b3f2008-04-10 18:43:06 +00008596 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
Reid Spencere0fc4df2006-10-20 07:07:24 +00008597 if (MI->getAlignment()->getZExtValue() < Alignment) {
Reid Spencerc635f472006-12-31 05:48:39 +00008598 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
Chris Lattner82f2ef22006-03-06 20:18:44 +00008599 Changed = true;
8600 }
8601 }
8602
Chris Lattnerc66b2232006-01-13 20:11:04 +00008603 if (Changed) return II;
Chris Lattner503221f2006-01-13 21:28:09 +00008604 } else {
8605 switch (II->getIntrinsicID()) {
8606 default: break;
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00008607 case Intrinsic::ppc_altivec_lvx:
8608 case Intrinsic::ppc_altivec_lvxl:
Chris Lattner36dd7c92006-04-17 22:26:56 +00008609 case Intrinsic::x86_sse_loadu_ps:
8610 case Intrinsic::x86_sse2_loadu_pd:
8611 case Intrinsic::x86_sse2_loadu_dq:
8612 // Turn PPC lvx -> load if the pointer is known aligned.
8613 // Turn X86 loadups -> load if the pointer is known aligned.
Dan Gohman99b7b3f2008-04-10 18:43:06 +00008614 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Chris Lattner5a866122008-01-13 22:23:22 +00008615 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
8616 PointerType::getUnqual(II->getType()),
8617 CI);
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00008618 return new LoadInst(Ptr);
8619 }
8620 break;
8621 case Intrinsic::ppc_altivec_stvx:
8622 case Intrinsic::ppc_altivec_stvxl:
8623 // Turn stvx -> store if the pointer is known aligned.
Dan Gohman99b7b3f2008-04-10 18:43:06 +00008624 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
Christopher Lambedf07882007-12-17 01:12:55 +00008625 const Type *OpPtrTy =
8626 PointerType::getUnqual(II->getOperand(1)->getType());
Chris Lattner5a866122008-01-13 22:23:22 +00008627 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00008628 return new StoreInst(II->getOperand(1), Ptr);
8629 }
8630 break;
Chris Lattner36dd7c92006-04-17 22:26:56 +00008631 case Intrinsic::x86_sse_storeu_ps:
8632 case Intrinsic::x86_sse2_storeu_pd:
8633 case Intrinsic::x86_sse2_storeu_dq:
8634 case Intrinsic::x86_sse2_storel_dq:
8635 // Turn X86 storeu -> store if the pointer is known aligned.
Dan Gohman99b7b3f2008-04-10 18:43:06 +00008636 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Christopher Lambedf07882007-12-17 01:12:55 +00008637 const Type *OpPtrTy =
8638 PointerType::getUnqual(II->getOperand(2)->getType());
Chris Lattner5a866122008-01-13 22:23:22 +00008639 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
Chris Lattner36dd7c92006-04-17 22:26:56 +00008640 return new StoreInst(II->getOperand(2), Ptr);
8641 }
8642 break;
Chris Lattner2deeaea2006-10-05 06:55:50 +00008643
8644 case Intrinsic::x86_sse_cvttss2si: {
8645 // These intrinsics only demands the 0th element of its input vector. If
8646 // we can simplify the input based on that, do so now.
8647 uint64_t UndefElts;
8648 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
8649 UndefElts)) {
8650 II->setOperand(1, V);
8651 return II;
8652 }
8653 break;
8654 }
8655
Chris Lattnere79d2492006-04-06 19:19:17 +00008656 case Intrinsic::ppc_altivec_vperm:
8657 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
Reid Spencerd84d35b2007-02-15 02:26:10 +00008658 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
Chris Lattnere79d2492006-04-06 19:19:17 +00008659 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
8660
8661 // Check that all of the elements are integer constants or undefs.
8662 bool AllEltsOk = true;
8663 for (unsigned i = 0; i != 16; ++i) {
8664 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
8665 !isa<UndefValue>(Mask->getOperand(i))) {
8666 AllEltsOk = false;
8667 break;
8668 }
8669 }
8670
8671 if (AllEltsOk) {
8672 // Cast the input vectors to byte vectors.
Chris Lattner5a866122008-01-13 22:23:22 +00008673 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
8674 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
Chris Lattnere79d2492006-04-06 19:19:17 +00008675 Value *Result = UndefValue::get(Op0->getType());
8676
8677 // Only extract each element once.
8678 Value *ExtractedElts[32];
8679 memset(ExtractedElts, 0, sizeof(ExtractedElts));
8680
8681 for (unsigned i = 0; i != 16; ++i) {
8682 if (isa<UndefValue>(Mask->getOperand(i)))
8683 continue;
Chris Lattner28d921d2007-04-14 23:32:02 +00008684 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
Chris Lattnere79d2492006-04-06 19:19:17 +00008685 Idx &= 31; // Match the hardware behavior.
8686
8687 if (ExtractedElts[Idx] == 0) {
8688 Instruction *Elt =
Chris Lattner2deeaea2006-10-05 06:55:50 +00008689 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
Chris Lattnere79d2492006-04-06 19:19:17 +00008690 InsertNewInstBefore(Elt, CI);
8691 ExtractedElts[Idx] = Elt;
8692 }
8693
8694 // Insert this value into the result vector.
Gabor Greife9ecc682008-04-06 20:25:17 +00008695 Result = InsertElementInst::Create(Result, ExtractedElts[Idx], i, "tmp");
Chris Lattnere79d2492006-04-06 19:19:17 +00008696 InsertNewInstBefore(cast<Instruction>(Result), CI);
8697 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008698 return CastInst::create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere79d2492006-04-06 19:19:17 +00008699 }
8700 }
8701 break;
8702
Chris Lattner503221f2006-01-13 21:28:09 +00008703 case Intrinsic::stackrestore: {
8704 // If the save is right next to the restore, remove the restore. This can
8705 // happen when variable allocas are DCE'd.
8706 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
8707 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
8708 BasicBlock::iterator BI = SS;
8709 if (&*++BI == II)
8710 return EraseInstFromFunction(CI);
8711 }
8712 }
8713
Chris Lattner024f8c82008-02-18 06:12:38 +00008714 // Scan down this block to see if there is another stack restore in the
8715 // same block without an intervening call/alloca.
8716 BasicBlock::iterator BI = II;
Chris Lattner503221f2006-01-13 21:28:09 +00008717 TerminatorInst *TI = II->getParent()->getTerminator();
Chris Lattner024f8c82008-02-18 06:12:38 +00008718 bool CannotRemove = false;
8719 for (++BI; &*BI != TI; ++BI) {
8720 if (isa<AllocaInst>(BI)) {
8721 CannotRemove = true;
8722 break;
8723 }
8724 if (isa<CallInst>(BI)) {
8725 if (!isa<IntrinsicInst>(BI)) {
Chris Lattner503221f2006-01-13 21:28:09 +00008726 CannotRemove = true;
8727 break;
8728 }
Chris Lattner024f8c82008-02-18 06:12:38 +00008729 // If there is a stackrestore below this one, remove this one.
Chris Lattner503221f2006-01-13 21:28:09 +00008730 return EraseInstFromFunction(CI);
Chris Lattner024f8c82008-02-18 06:12:38 +00008731 }
Chris Lattner503221f2006-01-13 21:28:09 +00008732 }
Chris Lattner024f8c82008-02-18 06:12:38 +00008733
8734 // If the stack restore is in a return/unwind block and if there are no
8735 // allocas or calls between the restore and the return, nuke the restore.
8736 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
8737 return EraseInstFromFunction(CI);
Chris Lattner503221f2006-01-13 21:28:09 +00008738 break;
8739 }
8740 }
Chris Lattner00648e12004-10-12 04:52:52 +00008741 }
8742
Chris Lattnerc66b2232006-01-13 20:11:04 +00008743 return visitCallSite(II);
Chris Lattner970c33a2003-06-19 17:00:31 +00008744}
8745
8746// InvokeInst simplification
8747//
8748Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattneraec3d942003-10-07 22:32:43 +00008749 return visitCallSite(&II);
Chris Lattner970c33a2003-06-19 17:00:31 +00008750}
8751
Dale Johannesen0d1d3df2008-04-25 21:16:07 +00008752/// isSafeToEliminateVarargsCast - If this cast does not affect the value
8753/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesenf6e15a42008-04-23 18:34:37 +00008754static bool isSafeToEliminateVarargsCast(const CallSite CS,
8755 const CastInst * const CI,
8756 const TargetData * const TD,
8757 const int ix) {
8758 if (!CI->isLosslessCast())
8759 return false;
8760
8761 // The size of ByVal arguments is derived from the type, so we
8762 // can't change to a type with a different size. If the size were
8763 // passed explicitly we could avoid this check.
8764 if (!CS.paramHasAttr(ix, ParamAttr::ByVal))
8765 return true;
8766
8767 const Type* SrcTy =
8768 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
8769 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
8770 if (!SrcTy->isSized() || !DstTy->isSized())
8771 return false;
8772 if (TD->getABITypeSize(SrcTy) != TD->getABITypeSize(DstTy))
8773 return false;
8774 return true;
8775}
8776
Chris Lattneraec3d942003-10-07 22:32:43 +00008777// visitCallSite - Improvements for call and invoke instructions.
8778//
8779Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00008780 bool Changed = false;
8781
8782 // If the callee is a constexpr cast of a function, attempt to move the cast
8783 // to the arguments of the call/invoke.
Chris Lattneraec3d942003-10-07 22:32:43 +00008784 if (transformConstExprCastCall(CS)) return 0;
8785
Chris Lattner75b4d1d2003-10-07 22:54:13 +00008786 Value *Callee = CS.getCalledValue();
Chris Lattner81a7a232004-10-16 18:11:37 +00008787
Chris Lattner61d9d812005-05-13 07:09:09 +00008788 if (Function *CalleeF = dyn_cast<Function>(Callee))
8789 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
8790 Instruction *OldCall = CS.getInstruction();
8791 // If the call and callee calling conventions don't match, this call must
8792 // be unreachable, as the call is undefined.
Zhou Sheng75b871f2007-01-11 12:24:14 +00008793 new StoreInst(ConstantInt::getTrue(),
Christopher Lambedf07882007-12-17 01:12:55 +00008794 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
8795 OldCall);
Chris Lattner61d9d812005-05-13 07:09:09 +00008796 if (!OldCall->use_empty())
8797 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
8798 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
8799 return EraseInstFromFunction(*OldCall);
8800 return 0;
8801 }
8802
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008803 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
8804 // This instruction is not reachable, just remove it. We insert a store to
8805 // undef so that we know that this code is not reachable, despite the fact
8806 // that we can't modify the CFG here.
Zhou Sheng75b871f2007-01-11 12:24:14 +00008807 new StoreInst(ConstantInt::getTrue(),
Christopher Lambedf07882007-12-17 01:12:55 +00008808 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008809 CS.getInstruction());
8810
8811 if (!CS.getInstruction()->use_empty())
8812 CS.getInstruction()->
8813 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
8814
8815 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
8816 // Don't break the CFG, insert a dummy cond branch.
Gabor Greife9ecc682008-04-06 20:25:17 +00008817 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
8818 ConstantInt::getTrue(), II);
Chris Lattner81a7a232004-10-16 18:11:37 +00008819 }
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008820 return EraseInstFromFunction(*CS.getInstruction());
8821 }
Chris Lattner81a7a232004-10-16 18:11:37 +00008822
Duncan Sands6d5da712007-09-17 10:26:40 +00008823 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
8824 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
8825 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
8826 return transformCallThroughTrampoline(CS);
8827
Chris Lattner75b4d1d2003-10-07 22:54:13 +00008828 const PointerType *PTy = cast<PointerType>(Callee->getType());
8829 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
8830 if (FTy->isVarArg()) {
Dale Johannesen493527d2008-04-23 01:03:05 +00008831 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Chris Lattner75b4d1d2003-10-07 22:54:13 +00008832 // See if we can optimize any arguments passed through the varargs area of
8833 // the call.
8834 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesenf6e15a42008-04-23 18:34:37 +00008835 E = CS.arg_end(); I != E; ++I, ++ix) {
8836 CastInst *CI = dyn_cast<CastInst>(*I);
8837 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
8838 *I = CI->getOperand(0);
8839 Changed = true;
Chris Lattner75b4d1d2003-10-07 22:54:13 +00008840 }
Dale Johannesenf6e15a42008-04-23 18:34:37 +00008841 }
Chris Lattner75b4d1d2003-10-07 22:54:13 +00008842 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00008843
Duncan Sandsaa31b922007-12-19 21:13:37 +00008844 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sands8e4847e2007-12-16 15:51:49 +00008845 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsaa31b922007-12-19 21:13:37 +00008846 CS.setDoesNotThrow();
Duncan Sands8e4847e2007-12-16 15:51:49 +00008847 Changed = true;
8848 }
8849
Chris Lattner75b4d1d2003-10-07 22:54:13 +00008850 return Changed ? CS.getInstruction() : 0;
Chris Lattneraec3d942003-10-07 22:32:43 +00008851}
8852
Chris Lattner970c33a2003-06-19 17:00:31 +00008853// transformConstExprCastCall - If the callee is a constexpr cast of a function,
8854// attempt to move the cast to the arguments of the call/invoke.
8855//
8856bool InstCombiner::transformConstExprCastCall(CallSite CS) {
8857 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
8858 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008859 if (CE->getOpcode() != Instruction::BitCast ||
8860 !isa<Function>(CE->getOperand(0)))
Chris Lattner970c33a2003-06-19 17:00:31 +00008861 return false;
Reid Spencer87436872004-07-18 00:38:32 +00008862 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner970c33a2003-06-19 17:00:31 +00008863 Instruction *Caller = CS.getInstruction();
Chris Lattner8a923e72008-03-12 17:45:29 +00008864 const PAListPtr &CallerPAL = CS.getParamAttrs();
Chris Lattner970c33a2003-06-19 17:00:31 +00008865
8866 // Okay, this is a cast from a function to a different type. Unless doing so
8867 // would cause a type conversion of one of our arguments, change this call to
8868 // be a direct call with arguments casted to the appropriate types.
8869 //
8870 const FunctionType *FT = Callee->getFunctionType();
8871 const Type *OldRetTy = Caller->getType();
8872
Devang Patel70c238a2008-03-11 18:04:06 +00008873 if (isa<StructType>(FT->getReturnType()))
8874 return false; // TODO: Handle multiple return values.
8875
Chris Lattner1f7942f2004-01-14 06:06:08 +00008876 // Check to see if we are changing the return type...
8877 if (OldRetTy != FT->getReturnType()) {
Reid Spencer5301e7c2007-01-30 20:08:39 +00008878 if (Callee->isDeclaration() && !Caller->use_empty() &&
Chris Lattner7051d752007-01-06 19:53:32 +00008879 // Conversion is ok if changing from pointer to int of same size.
8880 !(isa<PointerType>(FT->getReturnType()) &&
8881 TD->getIntPtrType() == OldRetTy))
Chris Lattner400f9592007-01-06 02:09:32 +00008882 return false; // Cannot transform this return value.
Chris Lattner1f7942f2004-01-14 06:06:08 +00008883
Duncan Sands55e50902008-01-06 10:12:28 +00008884 if (!Caller->use_empty() &&
Duncan Sands55e50902008-01-06 10:12:28 +00008885 // void -> non-void is handled specially
Duncan Sands781f6542008-01-13 08:02:44 +00008886 FT->getReturnType() != Type::VoidTy &&
8887 !CastInst::isCastable(FT->getReturnType(), OldRetTy))
Duncan Sands55e50902008-01-06 10:12:28 +00008888 return false; // Cannot transform this return value.
8889
Chris Lattner8a923e72008-03-12 17:45:29 +00008890 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
8891 ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
Duncan Sandsb18c30a2008-01-07 17:16:06 +00008892 if (RAttrs & ParamAttr::typeIncompatible(FT->getReturnType()))
8893 return false; // Attribute not compatible with transformed value.
8894 }
Duncan Sands404eb052008-01-06 18:27:01 +00008895
Chris Lattner1f7942f2004-01-14 06:06:08 +00008896 // If the callsite is an invoke instruction, and the return value is used by
8897 // a PHI node in a successor, we cannot change the return type of the call
8898 // because there is no place to put the cast instruction (without breaking
8899 // the critical edge). Bail out in this case.
8900 if (!Caller->use_empty())
8901 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
8902 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
8903 UI != E; ++UI)
8904 if (PHINode *PN = dyn_cast<PHINode>(*UI))
8905 if (PN->getParent() == II->getNormalDest() ||
Chris Lattnerfae8ab32004-02-08 21:44:31 +00008906 PN->getParent() == II->getUnwindDest())
Chris Lattner1f7942f2004-01-14 06:06:08 +00008907 return false;
8908 }
Chris Lattner970c33a2003-06-19 17:00:31 +00008909
8910 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
8911 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00008912
Chris Lattner970c33a2003-06-19 17:00:31 +00008913 CallSite::arg_iterator AI = CS.arg_begin();
8914 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
8915 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthebfa24e2006-06-28 01:01:52 +00008916 const Type *ActTy = (*AI)->getType();
Duncan Sands55e50902008-01-06 10:12:28 +00008917
8918 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sands404eb052008-01-06 18:27:01 +00008919 return false; // Cannot transform this parameter value.
8920
Chris Lattner8a923e72008-03-12 17:45:29 +00008921 if (CallerPAL.getParamAttrs(i + 1) & ParamAttr::typeIncompatible(ParamTy))
8922 return false; // Attribute not compatible with transformed value.
Duncan Sands55e50902008-01-06 10:12:28 +00008923
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008924 ConstantInt *c = dyn_cast<ConstantInt>(*AI);
Duncan Sands55e50902008-01-06 10:12:28 +00008925 // Some conversions are safe even if we do not have a body.
8926 // Either we can cast directly, or we can upconvert the argument
Chris Lattner400f9592007-01-06 02:09:32 +00008927 bool isConvertible = ActTy == ParamTy ||
Chris Lattner7051d752007-01-06 19:53:32 +00008928 (isa<PointerType>(ParamTy) && isa<PointerType>(ActTy)) ||
Chris Lattner03c49532007-01-15 02:27:26 +00008929 (ParamTy->isInteger() && ActTy->isInteger() &&
Reid Spencer8f166b02007-01-08 16:32:00 +00008930 ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()) ||
8931 (c && ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()
Zhou Sheng222d5eb2007-03-25 05:01:29 +00008932 && c->getValue().isStrictlyPositive());
Reid Spencer5301e7c2007-01-30 20:08:39 +00008933 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner970c33a2003-06-19 17:00:31 +00008934 }
8935
8936 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5301e7c2007-01-30 20:08:39 +00008937 Callee->isDeclaration())
Chris Lattner8a923e72008-03-12 17:45:29 +00008938 return false; // Do not delete arguments unless we have a function body.
Chris Lattner970c33a2003-06-19 17:00:31 +00008939
Chris Lattner8a923e72008-03-12 17:45:29 +00008940 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
8941 !CallerPAL.isEmpty())
Duncan Sands404eb052008-01-06 18:27:01 +00008942 // In this case we have more arguments than the new function type, but we
Duncan Sands781f6542008-01-13 08:02:44 +00008943 // won't be dropping them. Check that these extra arguments have attributes
8944 // that are compatible with being a vararg call argument.
Chris Lattner8a923e72008-03-12 17:45:29 +00008945 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
8946 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sands781f6542008-01-13 08:02:44 +00008947 break;
Chris Lattner8a923e72008-03-12 17:45:29 +00008948 ParameterAttributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Duncan Sands781f6542008-01-13 08:02:44 +00008949 if (PAttrs & ParamAttr::VarArgsIncompatible)
8950 return false;
8951 }
Duncan Sands404eb052008-01-06 18:27:01 +00008952
Chris Lattner970c33a2003-06-19 17:00:31 +00008953 // Okay, we decided that this is a safe thing to do: go ahead and start
8954 // inserting cast instructions as necessary...
8955 std::vector<Value*> Args;
8956 Args.reserve(NumActualArgs);
Chris Lattner8a923e72008-03-12 17:45:29 +00008957 SmallVector<ParamAttrsWithIndex, 8> attrVec;
Duncan Sands404eb052008-01-06 18:27:01 +00008958 attrVec.reserve(NumCommonArgs);
8959
8960 // Get any return attributes.
Chris Lattner8a923e72008-03-12 17:45:29 +00008961 ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
Duncan Sands404eb052008-01-06 18:27:01 +00008962
8963 // If the return value is not being used, the type may not be compatible
8964 // with the existing attributes. Wipe out any problematic attributes.
Duncan Sandsb18c30a2008-01-07 17:16:06 +00008965 RAttrs &= ~ParamAttr::typeIncompatible(FT->getReturnType());
Duncan Sands404eb052008-01-06 18:27:01 +00008966
8967 // Add the new return attributes.
8968 if (RAttrs)
8969 attrVec.push_back(ParamAttrsWithIndex::get(0, RAttrs));
Chris Lattner970c33a2003-06-19 17:00:31 +00008970
8971 AI = CS.arg_begin();
8972 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
8973 const Type *ParamTy = FT->getParamType(i);
8974 if ((*AI)->getType() == ParamTy) {
8975 Args.push_back(*AI);
8976 } else {
Reid Spencer668d90f2006-12-18 08:47:13 +00008977 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc635f472006-12-31 05:48:39 +00008978 false, ParamTy, false);
Reid Spencer668d90f2006-12-18 08:47:13 +00008979 CastInst *NewCast = CastInst::create(opcode, *AI, ParamTy, "tmp");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008980 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner970c33a2003-06-19 17:00:31 +00008981 }
Duncan Sands404eb052008-01-06 18:27:01 +00008982
8983 // Add any parameter attributes.
Chris Lattner8a923e72008-03-12 17:45:29 +00008984 if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
Duncan Sands404eb052008-01-06 18:27:01 +00008985 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
Chris Lattner970c33a2003-06-19 17:00:31 +00008986 }
8987
8988 // If the function takes more arguments than the call was taking, add them
8989 // now...
8990 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
8991 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
8992
8993 // If we are removing arguments to the function, emit an obnoxious warning...
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +00008994 if (FT->getNumParams() < NumActualArgs) {
Chris Lattner970c33a2003-06-19 17:00:31 +00008995 if (!FT->isVarArg()) {
Bill Wendlingf3baad32006-12-07 01:30:32 +00008996 cerr << "WARNING: While resolving call to function '"
8997 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner970c33a2003-06-19 17:00:31 +00008998 } else {
8999 // Add all of the arguments in their promoted form to the arg list...
9000 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
9001 const Type *PTy = getPromotedType((*AI)->getType());
9002 if (PTy != (*AI)->getType()) {
9003 // Must promote to pass through va_arg area!
Reid Spencerc635f472006-12-31 05:48:39 +00009004 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
9005 PTy, false);
Reid Spencer668d90f2006-12-18 08:47:13 +00009006 Instruction *Cast = CastInst::create(opcode, *AI, PTy, "tmp");
Chris Lattner970c33a2003-06-19 17:00:31 +00009007 InsertNewInstBefore(Cast, *Caller);
9008 Args.push_back(Cast);
9009 } else {
9010 Args.push_back(*AI);
9011 }
Duncan Sands404eb052008-01-06 18:27:01 +00009012
Duncan Sands781f6542008-01-13 08:02:44 +00009013 // Add any parameter attributes.
Chris Lattner8a923e72008-03-12 17:45:29 +00009014 if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
Duncan Sands781f6542008-01-13 08:02:44 +00009015 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
9016 }
Chris Lattner970c33a2003-06-19 17:00:31 +00009017 }
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +00009018 }
Chris Lattner970c33a2003-06-19 17:00:31 +00009019
9020 if (FT->getReturnType() == Type::VoidTy)
Chris Lattner6e0123b2007-02-11 01:23:03 +00009021 Caller->setName(""); // Void type should not have a name.
Chris Lattner970c33a2003-06-19 17:00:31 +00009022
Chris Lattner8a923e72008-03-12 17:45:29 +00009023 const PAListPtr &NewCallerPAL = PAListPtr::get(attrVec.begin(),attrVec.end());
Duncan Sands404eb052008-01-06 18:27:01 +00009024
Chris Lattner970c33a2003-06-19 17:00:31 +00009025 Instruction *NC;
9026 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greife9ecc682008-04-06 20:25:17 +00009027 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
9028 Args.begin(), Args.end(), Caller->getName(), Caller);
Reid Spencerdff9d692007-07-30 19:53:57 +00009029 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Duncan Sands404eb052008-01-06 18:27:01 +00009030 cast<InvokeInst>(NC)->setParamAttrs(NewCallerPAL);
Chris Lattner970c33a2003-06-19 17:00:31 +00009031 } else {
Gabor Greife9ecc682008-04-06 20:25:17 +00009032 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
9033 Caller->getName(), Caller);
Duncan Sandsad0ea2d2007-11-27 13:23:08 +00009034 CallInst *CI = cast<CallInst>(Caller);
9035 if (CI->isTailCall())
Chris Lattner6aacb0f2005-05-06 06:48:21 +00009036 cast<CallInst>(NC)->setTailCall();
Duncan Sandsad0ea2d2007-11-27 13:23:08 +00009037 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Duncan Sands404eb052008-01-06 18:27:01 +00009038 cast<CallInst>(NC)->setParamAttrs(NewCallerPAL);
Chris Lattner970c33a2003-06-19 17:00:31 +00009039 }
9040
Chris Lattner6e0123b2007-02-11 01:23:03 +00009041 // Insert a cast of the return type as necessary.
Chris Lattner970c33a2003-06-19 17:00:31 +00009042 Value *NV = NC;
Duncan Sands55e50902008-01-06 10:12:28 +00009043 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Chris Lattner970c33a2003-06-19 17:00:31 +00009044 if (NV->getType() != Type::VoidTy) {
Reid Spencerc635f472006-12-31 05:48:39 +00009045 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sands55e50902008-01-06 10:12:28 +00009046 OldRetTy, false);
9047 NV = NC = CastInst::create(opcode, NC, OldRetTy, "tmp");
Chris Lattner686767f2003-10-30 00:46:41 +00009048
9049 // If this is an invoke instruction, we should insert it after the first
9050 // non-phi, instruction in the normal successor block.
9051 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
9052 BasicBlock::iterator I = II->getNormalDest()->begin();
9053 while (isa<PHINode>(I)) ++I;
9054 InsertNewInstBefore(NC, *I);
9055 } else {
9056 // Otherwise, it's a call, just insert cast right after the call instr
9057 InsertNewInstBefore(NC, *Caller);
9058 }
Chris Lattner51ea1272004-02-28 05:22:00 +00009059 AddUsersToWorkList(*Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00009060 } else {
Chris Lattnere29d6342004-10-17 21:22:38 +00009061 NV = UndefValue::get(Caller->getType());
Chris Lattner970c33a2003-06-19 17:00:31 +00009062 }
9063 }
9064
9065 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9066 Caller->replaceAllUsesWith(NV);
Chris Lattner51f54572007-03-02 19:59:19 +00009067 Caller->eraseFromParent();
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009068 RemoveFromWorkList(Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00009069 return true;
9070}
9071
Duncan Sands6d5da712007-09-17 10:26:40 +00009072// transformCallThroughTrampoline - Turn a call to a function created by the
9073// init_trampoline intrinsic into a direct call to the underlying function.
9074//
9075Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
9076 Value *Callee = CS.getCalledValue();
9077 const PointerType *PTy = cast<PointerType>(Callee->getType());
9078 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Chris Lattner8a923e72008-03-12 17:45:29 +00009079 const PAListPtr &Attrs = CS.getParamAttrs();
Duncan Sandsb5ca2e92008-01-14 19:52:09 +00009080
9081 // If the call already has the 'nest' attribute somewhere then give up -
9082 // otherwise 'nest' would occur twice after splicing in the chain.
Chris Lattner8a923e72008-03-12 17:45:29 +00009083 if (Attrs.hasAttrSomewhere(ParamAttr::Nest))
Duncan Sandsb5ca2e92008-01-14 19:52:09 +00009084 return 0;
Duncan Sands6d5da712007-09-17 10:26:40 +00009085
9086 IntrinsicInst *Tramp =
9087 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
9088
9089 Function *NestF =
9090 cast<Function>(IntrinsicInst::StripPointerCasts(Tramp->getOperand(2)));
9091 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
9092 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
9093
Chris Lattner8a923e72008-03-12 17:45:29 +00009094 const PAListPtr &NestAttrs = NestF->getParamAttrs();
9095 if (!NestAttrs.isEmpty()) {
Duncan Sands6d5da712007-09-17 10:26:40 +00009096 unsigned NestIdx = 1;
9097 const Type *NestTy = 0;
Dale Johannesen89268bc2008-02-19 21:38:47 +00009098 ParameterAttributes NestAttr = ParamAttr::None;
Duncan Sands6d5da712007-09-17 10:26:40 +00009099
9100 // Look for a parameter marked with the 'nest' attribute.
9101 for (FunctionType::param_iterator I = NestFTy->param_begin(),
9102 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Chris Lattner8a923e72008-03-12 17:45:29 +00009103 if (NestAttrs.paramHasAttr(NestIdx, ParamAttr::Nest)) {
Duncan Sands6d5da712007-09-17 10:26:40 +00009104 // Record the parameter type and any other attributes.
9105 NestTy = *I;
Chris Lattner8a923e72008-03-12 17:45:29 +00009106 NestAttr = NestAttrs.getParamAttrs(NestIdx);
Duncan Sands6d5da712007-09-17 10:26:40 +00009107 break;
9108 }
9109
9110 if (NestTy) {
9111 Instruction *Caller = CS.getInstruction();
9112 std::vector<Value*> NewArgs;
9113 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
9114
Chris Lattner8a923e72008-03-12 17:45:29 +00009115 SmallVector<ParamAttrsWithIndex, 8> NewAttrs;
9116 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sandsb5ca2e92008-01-14 19:52:09 +00009117
Duncan Sands6d5da712007-09-17 10:26:40 +00009118 // Insert the nest argument into the call argument list, which may
Duncan Sandsb5ca2e92008-01-14 19:52:09 +00009119 // mean appending it. Likewise for attributes.
9120
9121 // Add any function result attributes.
Chris Lattner8a923e72008-03-12 17:45:29 +00009122 if (ParameterAttributes Attr = Attrs.getParamAttrs(0))
9123 NewAttrs.push_back(ParamAttrsWithIndex::get(0, Attr));
Duncan Sandsb5ca2e92008-01-14 19:52:09 +00009124
Duncan Sands6d5da712007-09-17 10:26:40 +00009125 {
9126 unsigned Idx = 1;
9127 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
9128 do {
9129 if (Idx == NestIdx) {
Duncan Sandsb5ca2e92008-01-14 19:52:09 +00009130 // Add the chain argument and attributes.
Duncan Sands6d5da712007-09-17 10:26:40 +00009131 Value *NestVal = Tramp->getOperand(3);
9132 if (NestVal->getType() != NestTy)
9133 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
9134 NewArgs.push_back(NestVal);
Duncan Sandsb5ca2e92008-01-14 19:52:09 +00009135 NewAttrs.push_back(ParamAttrsWithIndex::get(NestIdx, NestAttr));
Duncan Sands6d5da712007-09-17 10:26:40 +00009136 }
9137
9138 if (I == E)
9139 break;
9140
Duncan Sandsb5ca2e92008-01-14 19:52:09 +00009141 // Add the original argument and attributes.
Duncan Sands6d5da712007-09-17 10:26:40 +00009142 NewArgs.push_back(*I);
Chris Lattner8a923e72008-03-12 17:45:29 +00009143 if (ParameterAttributes Attr = Attrs.getParamAttrs(Idx))
Duncan Sandsb5ca2e92008-01-14 19:52:09 +00009144 NewAttrs.push_back
9145 (ParamAttrsWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sands6d5da712007-09-17 10:26:40 +00009146
9147 ++Idx, ++I;
9148 } while (1);
9149 }
9150
9151 // The trampoline may have been bitcast to a bogus type (FTy).
9152 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sandsb5ca2e92008-01-14 19:52:09 +00009153 // with the chain parameter inserted.
Duncan Sands6d5da712007-09-17 10:26:40 +00009154
Duncan Sands6d5da712007-09-17 10:26:40 +00009155 std::vector<const Type*> NewTypes;
Duncan Sands6d5da712007-09-17 10:26:40 +00009156 NewTypes.reserve(FTy->getNumParams()+1);
9157
Duncan Sands6d5da712007-09-17 10:26:40 +00009158 // Insert the chain's type into the list of parameter types, which may
Duncan Sandsb5ca2e92008-01-14 19:52:09 +00009159 // mean appending it.
Duncan Sands6d5da712007-09-17 10:26:40 +00009160 {
9161 unsigned Idx = 1;
9162 FunctionType::param_iterator I = FTy->param_begin(),
9163 E = FTy->param_end();
9164
9165 do {
Duncan Sandsb5ca2e92008-01-14 19:52:09 +00009166 if (Idx == NestIdx)
9167 // Add the chain's type.
Duncan Sands6d5da712007-09-17 10:26:40 +00009168 NewTypes.push_back(NestTy);
Duncan Sands6d5da712007-09-17 10:26:40 +00009169
9170 if (I == E)
9171 break;
9172
Duncan Sandsb5ca2e92008-01-14 19:52:09 +00009173 // Add the original type.
Duncan Sands6d5da712007-09-17 10:26:40 +00009174 NewTypes.push_back(*I);
Duncan Sands6d5da712007-09-17 10:26:40 +00009175
9176 ++Idx, ++I;
9177 } while (1);
9178 }
9179
9180 // Replace the trampoline call with a direct call. Let the generic
9181 // code sort out any function type mismatches.
9182 FunctionType *NewFTy =
Duncan Sandsad0ea2d2007-11-27 13:23:08 +00009183 FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
Christopher Lambedf07882007-12-17 01:12:55 +00009184 Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
9185 NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
Chris Lattner8a923e72008-03-12 17:45:29 +00009186 const PAListPtr &NewPAL = PAListPtr::get(NewAttrs.begin(),NewAttrs.end());
Duncan Sands6d5da712007-09-17 10:26:40 +00009187
9188 Instruction *NewCaller;
9189 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greife9ecc682008-04-06 20:25:17 +00009190 NewCaller = InvokeInst::Create(NewCallee,
9191 II->getNormalDest(), II->getUnwindDest(),
9192 NewArgs.begin(), NewArgs.end(),
9193 Caller->getName(), Caller);
Duncan Sands6d5da712007-09-17 10:26:40 +00009194 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Duncan Sandsad0ea2d2007-11-27 13:23:08 +00009195 cast<InvokeInst>(NewCaller)->setParamAttrs(NewPAL);
Duncan Sands6d5da712007-09-17 10:26:40 +00009196 } else {
Gabor Greife9ecc682008-04-06 20:25:17 +00009197 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
9198 Caller->getName(), Caller);
Duncan Sands6d5da712007-09-17 10:26:40 +00009199 if (cast<CallInst>(Caller)->isTailCall())
9200 cast<CallInst>(NewCaller)->setTailCall();
9201 cast<CallInst>(NewCaller)->
9202 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Duncan Sandsad0ea2d2007-11-27 13:23:08 +00009203 cast<CallInst>(NewCaller)->setParamAttrs(NewPAL);
Duncan Sands6d5da712007-09-17 10:26:40 +00009204 }
9205 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9206 Caller->replaceAllUsesWith(NewCaller);
9207 Caller->eraseFromParent();
9208 RemoveFromWorkList(Caller);
9209 return 0;
9210 }
9211 }
9212
9213 // Replace the trampoline call with a direct call. Since there is no 'nest'
9214 // parameter, there is no need to adjust the argument list. Let the generic
9215 // code sort out any function type mismatches.
9216 Constant *NewCallee =
9217 NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
9218 CS.setCalledFunction(NewCallee);
9219 return CS.getInstruction();
9220}
9221
Chris Lattnercadac0c2006-11-01 04:51:18 +00009222/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
9223/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
9224/// and a single binop.
9225Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
9226 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Reid Spencer2341c222007-02-02 02:16:23 +00009227 assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
9228 isa<CmpInst>(FirstInst));
Chris Lattnercadac0c2006-11-01 04:51:18 +00009229 unsigned Opc = FirstInst->getOpcode();
Chris Lattnercd62f112006-11-08 19:29:23 +00009230 Value *LHSVal = FirstInst->getOperand(0);
9231 Value *RHSVal = FirstInst->getOperand(1);
9232
9233 const Type *LHSType = LHSVal->getType();
9234 const Type *RHSType = RHSVal->getType();
Chris Lattnercadac0c2006-11-01 04:51:18 +00009235
9236 // Scan to see if all operands are the same opcode, all have one use, and all
9237 // kill their operands (i.e. the operands have one use).
Chris Lattnerdc826fc2006-11-01 04:55:47 +00009238 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
Chris Lattnercadac0c2006-11-01 04:51:18 +00009239 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnerdc826fc2006-11-01 04:55:47 +00009240 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencer266e42b2006-12-23 06:05:41 +00009241 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattnereebea432006-11-01 07:43:41 +00009242 // types or GEP's with different index types.
9243 I->getOperand(0)->getType() != LHSType ||
9244 I->getOperand(1)->getType() != RHSType)
Chris Lattnercadac0c2006-11-01 04:51:18 +00009245 return 0;
Reid Spencer266e42b2006-12-23 06:05:41 +00009246
9247 // If they are CmpInst instructions, check their predicates
9248 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
9249 if (cast<CmpInst>(I)->getPredicate() !=
9250 cast<CmpInst>(FirstInst)->getPredicate())
9251 return 0;
Chris Lattnercd62f112006-11-08 19:29:23 +00009252
9253 // Keep track of which operand needs a phi node.
9254 if (I->getOperand(0) != LHSVal) LHSVal = 0;
9255 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattnercadac0c2006-11-01 04:51:18 +00009256 }
9257
Chris Lattner4f218d52006-11-08 19:42:28 +00009258 // Otherwise, this is safe to transform, determine if it is profitable.
9259
9260 // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
9261 // Indexes are often folded into load/store instructions, so we don't want to
9262 // hide them behind a phi.
9263 if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
9264 return 0;
9265
Chris Lattnercadac0c2006-11-01 04:51:18 +00009266 Value *InLHS = FirstInst->getOperand(0);
Chris Lattnercadac0c2006-11-01 04:51:18 +00009267 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner4f218d52006-11-08 19:42:28 +00009268 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnercd62f112006-11-08 19:29:23 +00009269 if (LHSVal == 0) {
Gabor Greife9ecc682008-04-06 20:25:17 +00009270 NewLHS = PHINode::Create(LHSType, FirstInst->getOperand(0)->getName()+".pn");
Chris Lattnercd62f112006-11-08 19:29:23 +00009271 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
9272 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattnereebea432006-11-01 07:43:41 +00009273 InsertNewInstBefore(NewLHS, PN);
9274 LHSVal = NewLHS;
9275 }
Chris Lattnercd62f112006-11-08 19:29:23 +00009276
9277 if (RHSVal == 0) {
Gabor Greife9ecc682008-04-06 20:25:17 +00009278 NewRHS = PHINode::Create(RHSType, FirstInst->getOperand(1)->getName()+".pn");
Chris Lattnercd62f112006-11-08 19:29:23 +00009279 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
9280 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattnereebea432006-11-01 07:43:41 +00009281 InsertNewInstBefore(NewRHS, PN);
9282 RHSVal = NewRHS;
9283 }
9284
Chris Lattnercd62f112006-11-08 19:29:23 +00009285 // Add all operands to the new PHIs.
9286 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9287 if (NewLHS) {
9288 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9289 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
9290 }
9291 if (NewRHS) {
9292 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
9293 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
9294 }
9295 }
9296
Chris Lattnercadac0c2006-11-01 04:51:18 +00009297 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattnereebea432006-11-01 07:43:41 +00009298 return BinaryOperator::create(BinOp->getOpcode(), LHSVal, RHSVal);
Reid Spencer266e42b2006-12-23 06:05:41 +00009299 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
9300 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
9301 RHSVal);
Chris Lattnereebea432006-11-01 07:43:41 +00009302 else {
9303 assert(isa<GetElementPtrInst>(FirstInst));
Gabor Greife9ecc682008-04-06 20:25:17 +00009304 return GetElementPtrInst::Create(LHSVal, RHSVal);
Chris Lattnereebea432006-11-01 07:43:41 +00009305 }
Chris Lattnercadac0c2006-11-01 04:51:18 +00009306}
9307
Chris Lattner14f82c72006-11-01 07:13:54 +00009308/// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
9309/// of the block that defines it. This means that it must be obvious the value
9310/// of the load is not changed from the point of the load to the end of the
9311/// block it is in.
Chris Lattnerc9042052007-02-01 22:30:07 +00009312///
9313/// Finally, it is safe, but not profitable, to sink a load targetting a
9314/// non-address-taken alloca. Doing so will cause us to not promote the alloca
9315/// to a register.
Chris Lattner14f82c72006-11-01 07:13:54 +00009316static bool isSafeToSinkLoad(LoadInst *L) {
9317 BasicBlock::iterator BBI = L, E = L->getParent()->end();
9318
9319 for (++BBI; BBI != E; ++BBI)
9320 if (BBI->mayWriteToMemory())
9321 return false;
Chris Lattnerc9042052007-02-01 22:30:07 +00009322
9323 // Check for non-address taken alloca. If not address-taken already, it isn't
9324 // profitable to do this xform.
9325 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
9326 bool isAddressTaken = false;
9327 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
9328 UI != E; ++UI) {
9329 if (isa<LoadInst>(UI)) continue;
9330 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
9331 // If storing TO the alloca, then the address isn't taken.
9332 if (SI->getOperand(1) == AI) continue;
9333 }
9334 isAddressTaken = true;
9335 break;
9336 }
9337
9338 if (!isAddressTaken)
9339 return false;
9340 }
9341
Chris Lattner14f82c72006-11-01 07:13:54 +00009342 return true;
9343}
9344
Chris Lattner970c33a2003-06-19 17:00:31 +00009345
Chris Lattner7515cab2004-11-14 19:13:23 +00009346// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
9347// operator and they all are only used by the PHI, PHI together their
9348// inputs, and do the operation once, to the result of the PHI.
9349Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
9350 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
9351
9352 // Scan the instruction, looking for input operations that can be folded away.
9353 // If all input operands to the phi are the same instruction (e.g. a cast from
9354 // the same type or "+42") we can pull the operation through the PHI, reducing
9355 // code size and simplifying code.
9356 Constant *ConstantOp = 0;
9357 const Type *CastSrcTy = 0;
Chris Lattner14f82c72006-11-01 07:13:54 +00009358 bool isVolatile = false;
Chris Lattner7515cab2004-11-14 19:13:23 +00009359 if (isa<CastInst>(FirstInst)) {
9360 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer2341c222007-02-02 02:16:23 +00009361 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00009362 // Can fold binop, compare or shift here if the RHS is a constant,
9363 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattner7515cab2004-11-14 19:13:23 +00009364 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattnercadac0c2006-11-01 04:51:18 +00009365 if (ConstantOp == 0)
9366 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner14f82c72006-11-01 07:13:54 +00009367 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
9368 isVolatile = LI->isVolatile();
9369 // We can't sink the load if the loaded value could be modified between the
9370 // load and the PHI.
9371 if (LI->getParent() != PN.getIncomingBlock(0) ||
9372 !isSafeToSinkLoad(LI))
9373 return 0;
Chris Lattnereebea432006-11-01 07:43:41 +00009374 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner4f218d52006-11-08 19:42:28 +00009375 if (FirstInst->getNumOperands() == 2)
Chris Lattnereebea432006-11-01 07:43:41 +00009376 return FoldPHIArgBinOpIntoPHI(PN);
9377 // Can't handle general GEPs yet.
9378 return 0;
Chris Lattner7515cab2004-11-14 19:13:23 +00009379 } else {
9380 return 0; // Cannot fold this operation.
9381 }
9382
9383 // Check to see if all arguments are the same operation.
9384 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9385 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
9386 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencer266e42b2006-12-23 06:05:41 +00009387 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattner7515cab2004-11-14 19:13:23 +00009388 return 0;
9389 if (CastSrcTy) {
9390 if (I->getOperand(0)->getType() != CastSrcTy)
9391 return 0; // Cast operation must match.
Chris Lattner14f82c72006-11-01 07:13:54 +00009392 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00009393 // We can't sink the load if the loaded value could be modified between
9394 // the load and the PHI.
Chris Lattner14f82c72006-11-01 07:13:54 +00009395 if (LI->isVolatile() != isVolatile ||
9396 LI->getParent() != PN.getIncomingBlock(i) ||
9397 !isSafeToSinkLoad(LI))
9398 return 0;
Chris Lattnerd9e3b5c2008-04-29 17:28:22 +00009399
9400 // If the PHI is volatile and its block has multiple successors, sinking
9401 // it would remove a load of the volatile value from the path through the
9402 // other successor.
9403 if (isVolatile &&
9404 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
9405 return 0;
9406
9407
Chris Lattner7515cab2004-11-14 19:13:23 +00009408 } else if (I->getOperand(1) != ConstantOp) {
9409 return 0;
9410 }
9411 }
9412
9413 // Okay, they are all the same operation. Create a new PHI node of the
9414 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greife9ecc682008-04-06 20:25:17 +00009415 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
9416 PN.getName()+".in");
Chris Lattnerd8e20182005-01-29 00:39:08 +00009417 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattner46dd5a62004-11-14 19:29:34 +00009418
9419 Value *InVal = FirstInst->getOperand(0);
9420 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00009421
9422 // Add all operands to the new PHI.
Chris Lattner46dd5a62004-11-14 19:29:34 +00009423 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9424 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9425 if (NewInVal != InVal)
9426 InVal = 0;
9427 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
9428 }
9429
9430 Value *PhiVal;
9431 if (InVal) {
9432 // The new PHI unions all of the same values together. This is really
9433 // common, so we handle it intelligently here for compile-time speed.
9434 PhiVal = InVal;
9435 delete NewPN;
9436 } else {
9437 InsertNewInstBefore(NewPN, PN);
9438 PhiVal = NewPN;
9439 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00009440
Chris Lattner7515cab2004-11-14 19:13:23 +00009441 // Insert and return the new operation.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00009442 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
9443 return CastInst::create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattner9233c122008-04-29 17:13:43 +00009444 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00009445 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner9233c122008-04-29 17:13:43 +00009446 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Reid Spencer266e42b2006-12-23 06:05:41 +00009447 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(),
9448 PhiVal, ConstantOp);
Chris Lattner9233c122008-04-29 17:13:43 +00009449 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
9450
9451 // If this was a volatile load that we are merging, make sure to loop through
9452 // and mark all the input loads as non-volatile. If we don't do this, we will
9453 // insert a new volatile load and the old ones will not be deletable.
9454 if (isVolatile)
9455 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
9456 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
9457
9458 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattner7515cab2004-11-14 19:13:23 +00009459}
Chris Lattner48a44f72002-05-02 17:06:02 +00009460
Chris Lattner71536432005-01-17 05:10:15 +00009461/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
9462/// that is dead.
Chris Lattnerd2602d52007-03-26 20:40:50 +00009463static bool DeadPHICycle(PHINode *PN,
9464 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattner71536432005-01-17 05:10:15 +00009465 if (PN->use_empty()) return true;
9466 if (!PN->hasOneUse()) return false;
9467
9468 // Remember this node, and if we find the cycle, return.
Chris Lattnerd2602d52007-03-26 20:40:50 +00009469 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattner71536432005-01-17 05:10:15 +00009470 return true;
Chris Lattner0e258b82007-08-28 04:23:55 +00009471
9472 // Don't scan crazily complex things.
9473 if (PotentiallyDeadPHIs.size() == 16)
9474 return false;
Chris Lattner71536432005-01-17 05:10:15 +00009475
9476 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
9477 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00009478
Chris Lattner71536432005-01-17 05:10:15 +00009479 return false;
9480}
9481
Chris Lattnerd8515f82007-11-06 21:52:06 +00009482/// PHIsEqualValue - Return true if this phi node is always equal to
9483/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
9484/// z = some value; x = phi (y, z); y = phi (x, z)
9485static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
9486 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
9487 // See if we already saw this PHI node.
9488 if (!ValueEqualPHIs.insert(PN))
9489 return true;
9490
9491 // Don't scan crazily complex things.
9492 if (ValueEqualPHIs.size() == 16)
9493 return false;
9494
9495 // Scan the operands to see if they are either phi nodes or are equal to
9496 // the value.
9497 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
9498 Value *Op = PN->getIncomingValue(i);
9499 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
9500 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
9501 return false;
9502 } else if (Op != NonPhiInVal)
9503 return false;
9504 }
9505
9506 return true;
9507}
9508
9509
Chris Lattnerbbbdd852002-05-06 18:06:38 +00009510// PHINode simplification
9511//
Chris Lattner113f4f42002-06-25 16:13:24 +00009512Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonbbf89902006-07-10 22:15:25 +00009513 // If LCSSA is around, don't mess with Phi nodes
Chris Lattner8258b442007-03-04 04:27:24 +00009514 if (MustPreserveLCSSA) return 0;
Owen Andersona6968f82006-07-10 19:03:49 +00009515
Owen Andersonae8aa642006-07-10 22:03:18 +00009516 if (Value *V = PN.hasConstantValue())
9517 return ReplaceInstUsesWith(PN, V);
9518
Owen Andersonae8aa642006-07-10 22:03:18 +00009519 // If all PHI operands are the same operation, pull them through the PHI,
9520 // reducing code size.
9521 if (isa<Instruction>(PN.getIncomingValue(0)) &&
9522 PN.getIncomingValue(0)->hasOneUse())
9523 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
9524 return Result;
9525
9526 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
9527 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
9528 // PHI)... break the cycle.
Chris Lattnerc8dcede2007-01-15 07:30:06 +00009529 if (PN.hasOneUse()) {
9530 Instruction *PHIUser = cast<Instruction>(PN.use_back());
9531 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattnerd2602d52007-03-26 20:40:50 +00009532 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Andersonae8aa642006-07-10 22:03:18 +00009533 PotentiallyDeadPHIs.insert(&PN);
9534 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
9535 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9536 }
Chris Lattnerc8dcede2007-01-15 07:30:06 +00009537
9538 // If this phi has a single use, and if that use just computes a value for
9539 // the next iteration of a loop, delete the phi. This occurs with unused
9540 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
9541 // common case here is good because the only other things that catch this
9542 // are induction variable analysis (sometimes) and ADCE, which is only run
9543 // late.
9544 if (PHIUser->hasOneUse() &&
9545 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
9546 PHIUser->use_back() == &PN) {
9547 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9548 }
9549 }
Owen Andersonae8aa642006-07-10 22:03:18 +00009550
Chris Lattnerd8515f82007-11-06 21:52:06 +00009551 // We sometimes end up with phi cycles that non-obviously end up being the
9552 // same value, for example:
9553 // z = some value; x = phi (y, z); y = phi (x, z)
9554 // where the phi nodes don't necessarily need to be in the same block. Do a
9555 // quick check to see if the PHI node only contains a single non-phi value, if
9556 // so, scan to see if the phi cycle is actually equal to that value.
9557 {
9558 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
9559 // Scan for the first non-phi operand.
9560 while (InValNo != NumOperandVals &&
9561 isa<PHINode>(PN.getIncomingValue(InValNo)))
9562 ++InValNo;
9563
9564 if (InValNo != NumOperandVals) {
9565 Value *NonPhiInVal = PN.getOperand(InValNo);
9566
9567 // Scan the rest of the operands to see if there are any conflicts, if so
9568 // there is no need to recursively scan other phis.
9569 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
9570 Value *OpVal = PN.getIncomingValue(InValNo);
9571 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
9572 break;
9573 }
9574
9575 // If we scanned over all operands, then we have one unique value plus
9576 // phi values. Scan PHI nodes to see if they all merge in each other or
9577 // the value.
9578 if (InValNo == NumOperandVals) {
9579 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
9580 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
9581 return ReplaceInstUsesWith(PN, NonPhiInVal);
9582 }
9583 }
9584 }
Chris Lattner91daeb52003-12-19 05:58:40 +00009585 return 0;
Chris Lattnerbbbdd852002-05-06 18:06:38 +00009586}
9587
Reid Spencer13bc5d72006-12-12 09:18:51 +00009588static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
9589 Instruction *InsertPoint,
9590 InstCombiner *IC) {
Reid Spencer8f166b02007-01-08 16:32:00 +00009591 unsigned PtrSize = DTy->getPrimitiveSizeInBits();
9592 unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
Reid Spencer13bc5d72006-12-12 09:18:51 +00009593 // We must cast correctly to the pointer type. Ensure that we
9594 // sign extend the integer value if it is smaller as this is
9595 // used for address computation.
9596 Instruction::CastOps opcode =
9597 (VTySize < PtrSize ? Instruction::SExt :
9598 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
9599 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
Chris Lattner69193f92004-04-05 01:30:19 +00009600}
9601
Chris Lattner48a44f72002-05-02 17:06:02 +00009602
Chris Lattner113f4f42002-06-25 16:13:24 +00009603Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner5f667a62004-05-07 22:09:22 +00009604 Value *PtrOp = GEP.getOperand(0);
Chris Lattneracbf6a42007-04-28 00:57:34 +00009605 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
Chris Lattner113f4f42002-06-25 16:13:24 +00009606 // If so, eliminate the noop.
Chris Lattner8d0bacb2004-02-22 05:25:17 +00009607 if (GEP.getNumOperands() == 1)
Chris Lattner5f667a62004-05-07 22:09:22 +00009608 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner8d0bacb2004-02-22 05:25:17 +00009609
Chris Lattner81a7a232004-10-16 18:11:37 +00009610 if (isa<UndefValue>(GEP.getOperand(0)))
9611 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
9612
Chris Lattner8d0bacb2004-02-22 05:25:17 +00009613 bool HasZeroPointerIndex = false;
9614 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
9615 HasZeroPointerIndex = C->isNullValue();
9616
9617 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner5f667a62004-05-07 22:09:22 +00009618 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner48a44f72002-05-02 17:06:02 +00009619
Chris Lattner69193f92004-04-05 01:30:19 +00009620 // Eliminate unneeded casts for indices.
9621 bool MadeChange = false;
Chris Lattner9bf53ff2007-03-25 20:43:09 +00009622
Chris Lattner2b2412d2004-04-07 18:38:20 +00009623 gep_type_iterator GTI = gep_type_begin(GEP);
Chris Lattner9bf53ff2007-03-25 20:43:09 +00009624 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattner2b2412d2004-04-07 18:38:20 +00009625 if (isa<SequentialType>(*GTI)) {
9626 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
Chris Lattner27df1db2007-01-15 07:02:54 +00009627 if (CI->getOpcode() == Instruction::ZExt ||
9628 CI->getOpcode() == Instruction::SExt) {
9629 const Type *SrcTy = CI->getOperand(0)->getType();
9630 // We can eliminate a cast from i32 to i64 iff the target
9631 // is a 32-bit pointer target.
9632 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
9633 MadeChange = true;
9634 GEP.setOperand(i, CI->getOperand(0));
Chris Lattner69193f92004-04-05 01:30:19 +00009635 }
9636 }
9637 }
Chris Lattner2b2412d2004-04-07 18:38:20 +00009638 // If we are using a wider index than needed for this platform, shrink it
9639 // to what we need. If the incoming value needs a cast instruction,
9640 // insert it. This explicit cast can make subsequent optimizations more
9641 // obvious.
9642 Value *Op = GEP.getOperand(i);
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +00009643 if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00009644 if (Constant *C = dyn_cast<Constant>(Op)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00009645 GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00009646 MadeChange = true;
9647 } else {
Reid Spencer13bc5d72006-12-12 09:18:51 +00009648 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
9649 GEP);
Chris Lattner2b2412d2004-04-07 18:38:20 +00009650 GEP.setOperand(i, Op);
9651 MadeChange = true;
9652 }
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +00009653 }
Chris Lattner69193f92004-04-05 01:30:19 +00009654 }
Chris Lattner9bf53ff2007-03-25 20:43:09 +00009655 }
Chris Lattner69193f92004-04-05 01:30:19 +00009656 if (MadeChange) return &GEP;
9657
Chris Lattner9bf53ff2007-03-25 20:43:09 +00009658 // If this GEP instruction doesn't move the pointer, and if the input operand
9659 // is a bitcast of another pointer, just replace the GEP with a bitcast of the
9660 // real input to the dest type.
Chris Lattnerd8675e42007-10-12 05:30:59 +00009661 if (GEP.hasAllZeroIndices()) {
9662 if (BitCastInst *BCI = dyn_cast<BitCastInst>(GEP.getOperand(0))) {
9663 // If the bitcast is of an allocation, and the allocation will be
9664 // converted to match the type of the cast, don't touch this.
9665 if (isa<AllocationInst>(BCI->getOperand(0))) {
9666 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
Chris Lattnerad618f62007-10-12 18:05:47 +00009667 if (Instruction *I = visitBitCast(*BCI)) {
9668 if (I != BCI) {
9669 I->takeName(BCI);
9670 BCI->getParent()->getInstList().insert(BCI, I);
9671 ReplaceInstUsesWith(*BCI, I);
9672 }
Chris Lattnerd8675e42007-10-12 05:30:59 +00009673 return &GEP;
Chris Lattnerad618f62007-10-12 18:05:47 +00009674 }
Chris Lattnerd8675e42007-10-12 05:30:59 +00009675 }
9676 return new BitCastInst(BCI->getOperand(0), GEP.getType());
9677 }
9678 }
9679
Chris Lattnerae7a0d32002-08-02 19:29:35 +00009680 // Combine Indices - If the source pointer to this getelementptr instruction
9681 // is a getelementptr instruction, combine the indices of the two
9682 // getelementptr instructions into a single instruction.
9683 //
Chris Lattneraf6094f2007-02-15 22:48:32 +00009684 SmallVector<Value*, 8> SrcGEPOperands;
Chris Lattner0798af32005-01-13 20:14:25 +00009685 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattneraf6094f2007-02-15 22:48:32 +00009686 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
Chris Lattner57c67b02004-03-25 22:59:29 +00009687
9688 if (!SrcGEPOperands.empty()) {
Chris Lattner5f667a62004-05-07 22:09:22 +00009689 // Note that if our source is a gep chain itself that we wait for that
9690 // chain to be resolved before we perform this transformation. This
9691 // avoids us creating a TON of code in some cases.
9692 //
9693 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
9694 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
9695 return 0; // Wait until our source is folded to completion.
9696
Chris Lattneraf6094f2007-02-15 22:48:32 +00009697 SmallVector<Value*, 8> Indices;
Chris Lattner5f667a62004-05-07 22:09:22 +00009698
9699 // Find out whether the last index in the source GEP is a sequential idx.
9700 bool EndsWithSequential = false;
9701 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
9702 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattner8ec5f882004-05-08 22:41:42 +00009703 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00009704
Chris Lattnerae7a0d32002-08-02 19:29:35 +00009705 // Can we combine the two pointer arithmetics offsets?
Chris Lattner5f667a62004-05-07 22:09:22 +00009706 if (EndsWithSequential) {
Chris Lattner235af562003-03-05 22:33:14 +00009707 // Replace: gep (gep %P, long B), long A, ...
9708 // With: T = long A+B; gep %P, T, ...
9709 //
Chris Lattner5f667a62004-05-07 22:09:22 +00009710 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner69193f92004-04-05 01:30:19 +00009711 if (SO1 == Constant::getNullValue(SO1->getType())) {
9712 Sum = GO1;
9713 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
9714 Sum = SO1;
9715 } else {
9716 // If they aren't the same type, convert both to an integer of the
9717 // target's pointer size.
9718 if (SO1->getType() != GO1->getType()) {
9719 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00009720 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
Chris Lattner69193f92004-04-05 01:30:19 +00009721 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00009722 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
Chris Lattner69193f92004-04-05 01:30:19 +00009723 } else {
Duncan Sands44b87212007-11-01 20:53:16 +00009724 unsigned PS = TD->getPointerSizeInBits();
9725 if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
Chris Lattner69193f92004-04-05 01:30:19 +00009726 // Convert GO1 to SO1's type.
Reid Spencer13bc5d72006-12-12 09:18:51 +00009727 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
Chris Lattner69193f92004-04-05 01:30:19 +00009728
Duncan Sands44b87212007-11-01 20:53:16 +00009729 } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
Chris Lattner69193f92004-04-05 01:30:19 +00009730 // Convert SO1 to GO1's type.
Reid Spencer13bc5d72006-12-12 09:18:51 +00009731 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
Chris Lattner69193f92004-04-05 01:30:19 +00009732 } else {
9733 const Type *PT = TD->getIntPtrType();
Reid Spencer13bc5d72006-12-12 09:18:51 +00009734 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
9735 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
Chris Lattner69193f92004-04-05 01:30:19 +00009736 }
9737 }
9738 }
Chris Lattner5f667a62004-05-07 22:09:22 +00009739 if (isa<Constant>(SO1) && isa<Constant>(GO1))
9740 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
9741 else {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00009742 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
9743 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner5f667a62004-05-07 22:09:22 +00009744 }
Chris Lattner69193f92004-04-05 01:30:19 +00009745 }
Chris Lattner5f667a62004-05-07 22:09:22 +00009746
9747 // Recycle the GEP we already have if possible.
9748 if (SrcGEPOperands.size() == 2) {
9749 GEP.setOperand(0, SrcGEPOperands[0]);
9750 GEP.setOperand(1, Sum);
9751 return &GEP;
9752 } else {
9753 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9754 SrcGEPOperands.end()-1);
9755 Indices.push_back(Sum);
9756 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
9757 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00009758 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner69193f92004-04-05 01:30:19 +00009759 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00009760 SrcGEPOperands.size() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00009761 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattner57c67b02004-03-25 22:59:29 +00009762 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9763 SrcGEPOperands.end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +00009764 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
9765 }
9766
9767 if (!Indices.empty())
Gabor Greife9ecc682008-04-06 20:25:17 +00009768 return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
9769 Indices.end(), GEP.getName());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00009770
Chris Lattner5f667a62004-05-07 22:09:22 +00009771 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattnerc59af1d2002-08-17 22:21:59 +00009772 // GEP of global variable. If all of the indices for this GEP are
9773 // constants, we can promote this to a constexpr instead of an instruction.
9774
9775 // Scan for nonconstants...
Chris Lattnerf96f4a82007-01-31 04:40:53 +00009776 SmallVector<Constant*, 8> Indices;
Chris Lattnerc59af1d2002-08-17 22:21:59 +00009777 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
9778 for (; I != E && isa<Constant>(*I); ++I)
9779 Indices.push_back(cast<Constant>(*I));
9780
9781 if (I == E) { // If they are all constants...
Chris Lattnerf96f4a82007-01-31 04:40:53 +00009782 Constant *CE = ConstantExpr::getGetElementPtr(GV,
9783 &Indices[0],Indices.size());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00009784
9785 // Replace all uses of the GEP with the new constexpr...
9786 return ReplaceInstUsesWith(GEP, CE);
9787 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00009788 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
Chris Lattner567b81f2005-09-13 00:40:14 +00009789 if (!isa<PointerType>(X->getType())) {
9790 // Not interesting. Source pointer must be a cast from pointer.
9791 } else if (HasZeroPointerIndex) {
Wojciech Matyjewicz309e5a72007-12-12 15:21:32 +00009792 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
9793 // into : GEP [10 x i8]* X, i32 0, ...
Chris Lattner567b81f2005-09-13 00:40:14 +00009794 //
9795 // This occurs when the program declares an array extern like "int X[];"
9796 //
9797 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
9798 const PointerType *XTy = cast<PointerType>(X->getType());
9799 if (const ArrayType *XATy =
9800 dyn_cast<ArrayType>(XTy->getElementType()))
9801 if (const ArrayType *CATy =
9802 dyn_cast<ArrayType>(CPTy->getElementType()))
9803 if (CATy->getElementType() == XATy->getElementType()) {
9804 // At this point, we know that the cast source type is a pointer
9805 // to an array of the same type as the destination pointer
9806 // array. Because the array type is never stepped over (there
9807 // is a leading zero) we can fold the cast into this GEP.
9808 GEP.setOperand(0, X);
9809 return &GEP;
9810 }
9811 } else if (GEP.getNumOperands() == 2) {
9812 // Transform things like:
Wojciech Matyjewicz309e5a72007-12-12 15:21:32 +00009813 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
9814 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattner567b81f2005-09-13 00:40:14 +00009815 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
9816 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
9817 if (isa<ArrayType>(SrcElTy) &&
Duncan Sands44b87212007-11-01 20:53:16 +00009818 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
9819 TD->getABITypeSize(ResElTy)) {
David Greenec656cbb2007-09-04 15:46:09 +00009820 Value *Idx[2];
9821 Idx[0] = Constant::getNullValue(Type::Int32Ty);
9822 Idx[1] = GEP.getOperand(1);
Chris Lattner567b81f2005-09-13 00:40:14 +00009823 Value *V = InsertNewInstBefore(
Gabor Greife9ecc682008-04-06 20:25:17 +00009824 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00009825 // V and GEP are both pointer types --> BitCast
9826 return new BitCastInst(V, GEP.getType());
Chris Lattner8d0bacb2004-02-22 05:25:17 +00009827 }
Chris Lattner2a893292005-09-13 18:36:04 +00009828
9829 // Transform things like:
Wojciech Matyjewicz309e5a72007-12-12 15:21:32 +00009830 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner2a893292005-09-13 18:36:04 +00009831 // (where tmp = 8*tmp2) into:
Wojciech Matyjewicz309e5a72007-12-12 15:21:32 +00009832 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner2a893292005-09-13 18:36:04 +00009833
Wojciech Matyjewicz309e5a72007-12-12 15:21:32 +00009834 if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
Chris Lattner2a893292005-09-13 18:36:04 +00009835 uint64_t ArrayEltSize =
Duncan Sands44b87212007-11-01 20:53:16 +00009836 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner2a893292005-09-13 18:36:04 +00009837
9838 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
9839 // allow either a mul, shift, or constant here.
9840 Value *NewIdx = 0;
9841 ConstantInt *Scale = 0;
9842 if (ArrayEltSize == 1) {
9843 NewIdx = GEP.getOperand(1);
9844 Scale = ConstantInt::get(NewIdx->getType(), 1);
9845 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattnera393e4d2005-09-14 17:32:56 +00009846 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner2a893292005-09-13 18:36:04 +00009847 Scale = CI;
9848 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
9849 if (Inst->getOpcode() == Instruction::Shl &&
9850 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Shengb25806f2007-03-30 09:29:48 +00009851 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
9852 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
9853 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
Chris Lattner2a893292005-09-13 18:36:04 +00009854 NewIdx = Inst->getOperand(0);
9855 } else if (Inst->getOpcode() == Instruction::Mul &&
9856 isa<ConstantInt>(Inst->getOperand(1))) {
9857 Scale = cast<ConstantInt>(Inst->getOperand(1));
9858 NewIdx = Inst->getOperand(0);
9859 }
9860 }
Wojciech Matyjewicz309e5a72007-12-12 15:21:32 +00009861
Chris Lattner2a893292005-09-13 18:36:04 +00009862 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewicz309e5a72007-12-12 15:21:32 +00009863 // out, perform the transformation. Note, we don't know whether Scale is
9864 // signed or not. We'll use unsigned version of division/modulo
9865 // operation after making sure Scale doesn't have the sign bit set.
9866 if (Scale && Scale->getSExtValue() >= 0LL &&
9867 Scale->getZExtValue() % ArrayEltSize == 0) {
9868 Scale = ConstantInt::get(Scale->getType(),
9869 Scale->getZExtValue() / ArrayEltSize);
Reid Spencere0fc4df2006-10-20 07:07:24 +00009870 if (Scale->getZExtValue() != 1) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00009871 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
Wojciech Matyjewicz309e5a72007-12-12 15:21:32 +00009872 false /*ZExt*/);
Chris Lattner2a893292005-09-13 18:36:04 +00009873 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
9874 NewIdx = InsertNewInstBefore(Sc, GEP);
9875 }
9876
9877 // Insert the new GEP instruction.
David Greenec656cbb2007-09-04 15:46:09 +00009878 Value *Idx[2];
9879 Idx[0] = Constant::getNullValue(Type::Int32Ty);
9880 Idx[1] = NewIdx;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00009881 Instruction *NewGEP =
Gabor Greife9ecc682008-04-06 20:25:17 +00009882 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00009883 NewGEP = InsertNewInstBefore(NewGEP, GEP);
9884 // The NewGEP must be pointer typed, so must the old one -> BitCast
9885 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner2a893292005-09-13 18:36:04 +00009886 }
9887 }
Chris Lattner8d0bacb2004-02-22 05:25:17 +00009888 }
Chris Lattnerca081252001-12-14 16:52:21 +00009889 }
9890
Chris Lattnerca081252001-12-14 16:52:21 +00009891 return 0;
9892}
9893
Chris Lattner1085bdf2002-11-04 16:18:53 +00009894Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
9895 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +00009896 if (AI.isArrayAllocation()) { // Check C != 1
Reid Spencere0fc4df2006-10-20 07:07:24 +00009897 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
9898 const Type *NewTy =
9899 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattnera2620ac2002-11-09 00:49:43 +00009900 AllocationInst *New = 0;
Chris Lattner1085bdf2002-11-04 16:18:53 +00009901
9902 // Create and insert the replacement instruction...
9903 if (isa<MallocInst>(AI))
Nate Begeman848622f2005-11-05 09:21:28 +00009904 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00009905 else {
9906 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman848622f2005-11-05 09:21:28 +00009907 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00009908 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00009909
9910 InsertNewInstBefore(New, AI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00009911
Chris Lattner1085bdf2002-11-04 16:18:53 +00009912 // Scan to the end of the allocation instructions, to skip over a block of
9913 // allocas if possible...
9914 //
9915 BasicBlock::iterator It = New;
9916 while (isa<AllocationInst>(*It)) ++It;
9917
9918 // Now that I is pointing to the first non-allocation-inst in the block,
9919 // insert our getelementptr instruction...
9920 //
Reid Spencerc635f472006-12-31 05:48:39 +00009921 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
David Greenec656cbb2007-09-04 15:46:09 +00009922 Value *Idx[2];
9923 Idx[0] = NullIdx;
9924 Idx[1] = NullIdx;
Gabor Greife9ecc682008-04-06 20:25:17 +00009925 Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
9926 New->getName()+".sub", It);
Chris Lattner1085bdf2002-11-04 16:18:53 +00009927
9928 // Now make everything use the getelementptr instead of the original
9929 // allocation.
Chris Lattnerabb77c92004-03-19 06:08:10 +00009930 return ReplaceInstUsesWith(AI, V);
Chris Lattner81a7a232004-10-16 18:11:37 +00009931 } else if (isa<UndefValue>(AI.getArraySize())) {
9932 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner1085bdf2002-11-04 16:18:53 +00009933 }
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +00009934 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00009935
9936 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
9937 // Note that we only do this for alloca's, because malloc should allocate and
9938 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanb1c93172005-04-21 23:48:37 +00009939 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Duncan Sands44b87212007-11-01 20:53:16 +00009940 TD->getABITypeSize(AI.getAllocatedType()) == 0)
Chris Lattnerabb77c92004-03-19 06:08:10 +00009941 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
9942
Chris Lattner1085bdf2002-11-04 16:18:53 +00009943 return 0;
9944}
9945
Chris Lattner8427bff2003-12-07 01:24:23 +00009946Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
9947 Value *Op = FI.getOperand(0);
9948
Chris Lattner8ba9ec92004-10-18 02:59:09 +00009949 // free undef -> unreachable.
9950 if (isa<UndefValue>(Op)) {
9951 // Insert a new store to null because we cannot modify the CFG here.
Zhou Sheng75b871f2007-01-11 12:24:14 +00009952 new StoreInst(ConstantInt::getTrue(),
Christopher Lambedf07882007-12-17 01:12:55 +00009953 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
Chris Lattner8ba9ec92004-10-18 02:59:09 +00009954 return EraseInstFromFunction(FI);
9955 }
Chris Lattnerefb33d22007-04-14 00:20:02 +00009956
Chris Lattnerf3a36602004-02-28 04:57:37 +00009957 // If we have 'free null' delete the instruction. This can happen in stl code
9958 // when lots of inlining happens.
Chris Lattner8ba9ec92004-10-18 02:59:09 +00009959 if (isa<ConstantPointerNull>(Op))
Chris Lattner51ea1272004-02-28 05:22:00 +00009960 return EraseInstFromFunction(FI);
Chris Lattnerefb33d22007-04-14 00:20:02 +00009961
9962 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
9963 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
9964 FI.setOperand(0, CI->getOperand(0));
9965 return &FI;
9966 }
9967
9968 // Change free (gep X, 0,0,0,0) into free(X)
9969 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
9970 if (GEPI->hasAllZeroIndices()) {
9971 AddToWorkList(GEPI);
9972 FI.setOperand(0, GEPI->getOperand(0));
9973 return &FI;
9974 }
9975 }
9976
9977 // Change free(malloc) into nothing, if the malloc has a single use.
9978 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
9979 if (MI->hasOneUse()) {
9980 EraseInstFromFunction(FI);
9981 return EraseInstFromFunction(*MI);
9982 }
Chris Lattnerf3a36602004-02-28 04:57:37 +00009983
Chris Lattner8427bff2003-12-07 01:24:23 +00009984 return 0;
9985}
9986
9987
Chris Lattner72684fe2005-01-31 05:51:45 +00009988/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Pateldf49cf52007-10-18 19:52:32 +00009989static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendlingd188e032008-02-26 10:53:30 +00009990 const TargetData *TD) {
Chris Lattner35e24772004-07-13 01:49:43 +00009991 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00009992 Value *CastOp = CI->getOperand(0);
Chris Lattner35e24772004-07-13 01:49:43 +00009993
Devang Pateldf49cf52007-10-18 19:52:32 +00009994 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
9995 // Instead of loading constant c string, use corresponding integer value
9996 // directly if string length is small enough.
9997 const std::string &Str = CE->getOperand(0)->getStringValue();
9998 if (!Str.empty()) {
9999 unsigned len = Str.length();
10000 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
10001 unsigned numBits = Ty->getPrimitiveSizeInBits();
10002 // Replace LI with immediate integer store.
10003 if ((numBits >> 3) == len + 1) {
Bill Wendlingd188e032008-02-26 10:53:30 +000010004 APInt StrVal(numBits, 0);
10005 APInt SingleChar(numBits, 0);
10006 if (TD->isLittleEndian()) {
10007 for (signed i = len-1; i >= 0; i--) {
10008 SingleChar = (uint64_t) Str[i];
10009 StrVal = (StrVal << 8) | SingleChar;
10010 }
10011 } else {
10012 for (unsigned i = 0; i < len; i++) {
10013 SingleChar = (uint64_t) Str[i];
10014 StrVal = (StrVal << 8) | SingleChar;
10015 }
10016 // Append NULL at the end.
10017 SingleChar = 0;
10018 StrVal = (StrVal << 8) | SingleChar;
10019 }
10020 Value *NL = ConstantInt::get(StrVal);
10021 return IC.ReplaceInstUsesWith(LI, NL);
Devang Pateldf49cf52007-10-18 19:52:32 +000010022 }
10023 }
10024 }
10025
Chris Lattner35e24772004-07-13 01:49:43 +000010026 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +000010027 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattner35e24772004-07-13 01:49:43 +000010028 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +000010029
Reid Spencer31a4ef42007-01-22 05:51:25 +000010030 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencerd84d35b2007-02-15 02:26:10 +000010031 isa<VectorType>(DestPTy)) {
Chris Lattnerfe1b0b82005-01-31 04:50:46 +000010032 // If the source is an array, the code below will not succeed. Check to
10033 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
10034 // constants.
10035 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10036 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10037 if (ASrcTy->getNumElements() != 0) {
Chris Lattnerf96f4a82007-01-31 04:40:53 +000010038 Value *Idxs[2];
10039 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10040 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerfe1b0b82005-01-31 04:50:46 +000010041 SrcTy = cast<PointerType>(CastOp->getType());
10042 SrcPTy = SrcTy->getElementType();
10043 }
10044
Reid Spencer31a4ef42007-01-22 05:51:25 +000010045 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencerd84d35b2007-02-15 02:26:10 +000010046 isa<VectorType>(SrcPTy)) &&
Chris Lattnerecfa9b52005-03-29 06:37:47 +000010047 // Do not allow turning this into a load of an integer, which is then
10048 // casted to a pointer, this pessimizes pointer analysis a lot.
10049 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Reid Spencer31a4ef42007-01-22 05:51:25 +000010050 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10051 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Misha Brukmanb1c93172005-04-21 23:48:37 +000010052
Chris Lattnerfe1b0b82005-01-31 04:50:46 +000010053 // Okay, we are casting from one integer or pointer type to another of
10054 // the same size. Instead of casting the pointer before the load, cast
10055 // the result of the loaded value.
10056 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
10057 CI->getName(),
10058 LI.isVolatile()),LI);
10059 // Now cast the result of the load.
Reid Spencerbb65ebf2006-12-12 23:36:14 +000010060 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerfe1b0b82005-01-31 04:50:46 +000010061 }
Chris Lattner35e24772004-07-13 01:49:43 +000010062 }
10063 }
10064 return 0;
10065}
10066
Chris Lattnerf62ea8e2004-09-19 18:43:46 +000010067/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattnere6f13092004-09-19 19:18:10 +000010068/// from this value cannot trap. If it is not obviously safe to load from the
10069/// specified pointer, we do a quick local scan of the basic block containing
10070/// ScanFrom, to determine if the address is already accessed.
10071static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
Duncan Sands56df7de2007-09-19 10:10:31 +000010072 // If it is an alloca it is always safe to load from.
10073 if (isa<AllocaInst>(V)) return true;
10074
Duncan Sandsd31649b2007-09-19 10:25:38 +000010075 // If it is a global variable it is mostly safe to load from.
Duncan Sands56df7de2007-09-19 10:10:31 +000010076 if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
Duncan Sandsd31649b2007-09-19 10:25:38 +000010077 // Don't try to evaluate aliases. External weak GV can be null.
Duncan Sands56df7de2007-09-19 10:10:31 +000010078 return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
Chris Lattnere6f13092004-09-19 19:18:10 +000010079
10080 // Otherwise, be a little bit agressive by scanning the local block where we
10081 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +000010082 // from/to. If so, the previous load or store would have already trapped,
10083 // so there is no harm doing an extra load (also, CSE will later eliminate
10084 // the load entirely).
Chris Lattnere6f13092004-09-19 19:18:10 +000010085 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
10086
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +000010087 while (BBI != E) {
Chris Lattnere6f13092004-09-19 19:18:10 +000010088 --BBI;
10089
10090 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
10091 if (LI->getOperand(0) == V) return true;
10092 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
10093 if (SI->getOperand(1) == V) return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +000010094
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +000010095 }
Chris Lattnere6f13092004-09-19 19:18:10 +000010096 return false;
Chris Lattnerf62ea8e2004-09-19 18:43:46 +000010097}
10098
Chris Lattner99c8ee22007-08-11 18:48:48 +000010099/// GetUnderlyingObject - Trace through a series of getelementptrs and bitcasts
10100/// until we find the underlying object a pointer is referring to or something
10101/// we don't understand. Note that the returned pointer may be offset from the
10102/// input, because we ignore GEP indices.
10103static Value *GetUnderlyingObject(Value *Ptr) {
10104 while (1) {
10105 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
10106 if (CE->getOpcode() == Instruction::BitCast ||
10107 CE->getOpcode() == Instruction::GetElementPtr)
10108 Ptr = CE->getOperand(0);
10109 else
10110 return Ptr;
10111 } else if (BitCastInst *BCI = dyn_cast<BitCastInst>(Ptr)) {
10112 Ptr = BCI->getOperand(0);
10113 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
10114 Ptr = GEP->getOperand(0);
10115 } else {
10116 return Ptr;
10117 }
10118 }
10119}
10120
Chris Lattner0f1d8a32003-06-26 05:06:25 +000010121Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
10122 Value *Op = LI.getOperand(0);
Chris Lattner7e8af382004-01-12 04:13:56 +000010123
Dan Gohmane31a61e2007-07-20 16:34:21 +000010124 // Attempt to improve the alignment.
Dan Gohman99b7b3f2008-04-10 18:43:06 +000010125 unsigned KnownAlign = GetOrEnforceKnownAlignment(Op);
10126 if (KnownAlign >
10127 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
10128 LI.getAlignment()))
Dan Gohmane31a61e2007-07-20 16:34:21 +000010129 LI.setAlignment(KnownAlign);
10130
Chris Lattnera9d84e32005-05-01 04:24:53 +000010131 // load (cast X) --> cast (load X) iff safe
Reid Spencerde46e482006-11-02 20:25:50 +000010132 if (isa<CastInst>(Op))
Devang Pateldf49cf52007-10-18 19:52:32 +000010133 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattnera9d84e32005-05-01 04:24:53 +000010134 return Res;
10135
10136 // None of the following transforms are legal for volatile loads.
10137 if (LI.isVolatile()) return 0;
Chris Lattnerb990f7d2005-09-12 22:00:15 +000010138
Chris Lattnerb990f7d2005-09-12 22:00:15 +000010139 if (&LI.getParent()->front() != &LI) {
10140 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattnere0bfdf12005-09-12 22:21:03 +000010141 // If the instruction immediately before this is a store to the same
10142 // address, do a simple form of store->load forwarding.
Chris Lattnerb990f7d2005-09-12 22:00:15 +000010143 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
10144 if (SI->getOperand(1) == LI.getOperand(0))
10145 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattnere0bfdf12005-09-12 22:21:03 +000010146 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
10147 if (LIB->getOperand(0) == LI.getOperand(0))
10148 return ReplaceInstUsesWith(LI, LIB);
Chris Lattnerb990f7d2005-09-12 22:00:15 +000010149 }
Chris Lattnera9d84e32005-05-01 04:24:53 +000010150
Christopher Lambb053b802007-12-29 07:56:53 +000010151 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10152 const Value *GEPI0 = GEPI->getOperand(0);
10153 // TODO: Consider a target hook for valid address spaces for this xform.
10154 if (isa<ConstantPointerNull>(GEPI0) &&
10155 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
Chris Lattnera9d84e32005-05-01 04:24:53 +000010156 // Insert a new store to null instruction before the load to indicate
10157 // that this code is not reachable. We do this instead of inserting
10158 // an unreachable instruction directly because we cannot modify the
10159 // CFG.
10160 new StoreInst(UndefValue::get(LI.getType()),
10161 Constant::getNullValue(Op->getType()), &LI);
10162 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10163 }
Christopher Lambb053b802007-12-29 07:56:53 +000010164 }
Chris Lattnera9d84e32005-05-01 04:24:53 +000010165
Chris Lattner81a7a232004-10-16 18:11:37 +000010166 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattnera9d84e32005-05-01 04:24:53 +000010167 // load null/undef -> undef
Christopher Lambb053b802007-12-29 07:56:53 +000010168 // TODO: Consider a target hook for valid address spaces for this xform.
10169 if (isa<UndefValue>(C) || (C->isNullValue() &&
10170 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
Chris Lattner8ba9ec92004-10-18 02:59:09 +000010171 // Insert a new store to null instruction before the load to indicate that
10172 // this code is not reachable. We do this instead of inserting an
10173 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattnera9d84e32005-05-01 04:24:53 +000010174 new StoreInst(UndefValue::get(LI.getType()),
10175 Constant::getNullValue(Op->getType()), &LI);
Chris Lattner81a7a232004-10-16 18:11:37 +000010176 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner8ba9ec92004-10-18 02:59:09 +000010177 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +000010178
Chris Lattner81a7a232004-10-16 18:11:37 +000010179 // Instcombine load (constant global) into the value loaded.
10180 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Reid Spencer5301e7c2007-01-30 20:08:39 +000010181 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattner81a7a232004-10-16 18:11:37 +000010182 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanb1c93172005-04-21 23:48:37 +000010183
Chris Lattner81a7a232004-10-16 18:11:37 +000010184 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +000010185 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
Chris Lattner81a7a232004-10-16 18:11:37 +000010186 if (CE->getOpcode() == Instruction::GetElementPtr) {
10187 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Reid Spencer5301e7c2007-01-30 20:08:39 +000010188 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattner0b011ec2005-09-26 05:28:06 +000010189 if (Constant *V =
10190 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattner81a7a232004-10-16 18:11:37 +000010191 return ReplaceInstUsesWith(LI, V);
Chris Lattnera9d84e32005-05-01 04:24:53 +000010192 if (CE->getOperand(0)->isNullValue()) {
10193 // Insert a new store to null instruction before the load to indicate
10194 // that this code is not reachable. We do this instead of inserting
10195 // an unreachable instruction directly because we cannot modify the
10196 // CFG.
10197 new StoreInst(UndefValue::get(LI.getType()),
10198 Constant::getNullValue(Op->getType()), &LI);
10199 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10200 }
10201
Reid Spencer6c38f0b2006-11-27 01:05:10 +000010202 } else if (CE->isCast()) {
Devang Pateldf49cf52007-10-18 19:52:32 +000010203 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattner81a7a232004-10-16 18:11:37 +000010204 return Res;
10205 }
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +000010206 }
Chris Lattner81a7a232004-10-16 18:11:37 +000010207 }
Chris Lattner99c8ee22007-08-11 18:48:48 +000010208
10209 // If this load comes from anywhere in a constant global, and if the global
10210 // is all undef or zero, we know what it loads.
10211 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(Op))) {
10212 if (GV->isConstant() && GV->hasInitializer()) {
10213 if (GV->getInitializer()->isNullValue())
10214 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
10215 else if (isa<UndefValue>(GV->getInitializer()))
10216 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10217 }
10218 }
Chris Lattnere228ee52004-04-08 20:39:49 +000010219
Chris Lattnera9d84e32005-05-01 04:24:53 +000010220 if (Op->hasOneUse()) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +000010221 // Change select and PHI nodes to select values instead of addresses: this
10222 // helps alias analysis out a lot, allows many others simplifications, and
10223 // exposes redundancy in the code.
10224 //
10225 // Note that we cannot do the transformation unless we know that the
10226 // introduced loads cannot trap! Something like this is valid as long as
10227 // the condition is always false: load (select bool %C, int* null, int* %G),
10228 // but it would not be valid if we transformed it to load from null
10229 // unconditionally.
10230 //
10231 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
10232 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattnere6f13092004-09-19 19:18:10 +000010233 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
10234 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +000010235 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner42618552004-09-20 10:15:10 +000010236 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +000010237 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner42618552004-09-20 10:15:10 +000010238 SI->getOperand(2)->getName()+".val"), LI);
Gabor Greife9ecc682008-04-06 20:25:17 +000010239 return SelectInst::Create(SI->getCondition(), V1, V2);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +000010240 }
10241
Chris Lattnerbdcf41a2004-09-23 15:46:00 +000010242 // load (select (cond, null, P)) -> load P
10243 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
10244 if (C->isNullValue()) {
10245 LI.setOperand(0, SI->getOperand(2));
10246 return &LI;
10247 }
10248
10249 // load (select (cond, P, null)) -> load P
10250 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
10251 if (C->isNullValue()) {
10252 LI.setOperand(0, SI->getOperand(1));
10253 return &LI;
10254 }
Chris Lattnerf62ea8e2004-09-19 18:43:46 +000010255 }
10256 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +000010257 return 0;
10258}
10259
Reid Spencere928a152007-01-19 21:20:31 +000010260/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattner72684fe2005-01-31 05:51:45 +000010261/// when possible.
10262static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
10263 User *CI = cast<User>(SI.getOperand(1));
10264 Value *CastOp = CI->getOperand(0);
10265
10266 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
10267 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
10268 const Type *SrcPTy = SrcTy->getElementType();
10269
Reid Spencer31a4ef42007-01-22 05:51:25 +000010270 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
Chris Lattner72684fe2005-01-31 05:51:45 +000010271 // If the source is an array, the code below will not succeed. Check to
10272 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
10273 // constants.
10274 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10275 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10276 if (ASrcTy->getNumElements() != 0) {
Chris Lattnerf96f4a82007-01-31 04:40:53 +000010277 Value* Idxs[2];
10278 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10279 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattner72684fe2005-01-31 05:51:45 +000010280 SrcTy = cast<PointerType>(CastOp->getType());
10281 SrcPTy = SrcTy->getElementType();
10282 }
10283
Reid Spencer9a4bed02007-01-20 23:35:48 +000010284 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
10285 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10286 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Chris Lattner72684fe2005-01-31 05:51:45 +000010287
10288 // Okay, we are casting from one integer or pointer type to another of
Reid Spencerc050af92007-01-18 18:54:33 +000010289 // the same size. Instead of casting the pointer before
10290 // the store, cast the value to be stored.
Chris Lattner72684fe2005-01-31 05:51:45 +000010291 Value *NewCast;
Reid Spencerbb65ebf2006-12-12 23:36:14 +000010292 Value *SIOp0 = SI.getOperand(0);
Reid Spencerc050af92007-01-18 18:54:33 +000010293 Instruction::CastOps opcode = Instruction::BitCast;
10294 const Type* CastSrcTy = SIOp0->getType();
10295 const Type* CastDstTy = SrcPTy;
10296 if (isa<PointerType>(CastDstTy)) {
10297 if (CastSrcTy->isInteger())
Reid Spencerbb65ebf2006-12-12 23:36:14 +000010298 opcode = Instruction::IntToPtr;
Reid Spencer9a4bed02007-01-20 23:35:48 +000010299 } else if (isa<IntegerType>(CastDstTy)) {
Reid Spencer74a528b2006-12-13 18:21:21 +000010300 if (isa<PointerType>(SIOp0->getType()))
Reid Spencerbb65ebf2006-12-12 23:36:14 +000010301 opcode = Instruction::PtrToInt;
10302 }
10303 if (Constant *C = dyn_cast<Constant>(SIOp0))
Reid Spencerc050af92007-01-18 18:54:33 +000010304 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
Chris Lattner72684fe2005-01-31 05:51:45 +000010305 else
Reid Spencer6c38f0b2006-11-27 01:05:10 +000010306 NewCast = IC.InsertNewInstBefore(
Reid Spencerc050af92007-01-18 18:54:33 +000010307 CastInst::create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
10308 SI);
Chris Lattner72684fe2005-01-31 05:51:45 +000010309 return new StoreInst(NewCast, CastOp);
10310 }
10311 }
10312 }
10313 return 0;
10314}
10315
Chris Lattner31f486c2005-01-31 05:36:43 +000010316Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
10317 Value *Val = SI.getOperand(0);
10318 Value *Ptr = SI.getOperand(1);
10319
10320 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner5997cf92006-02-08 03:25:32 +000010321 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +000010322 ++NumCombined;
10323 return 0;
10324 }
Chris Lattnera4beeef2007-01-15 06:51:56 +000010325
10326 // If the RHS is an alloca with a single use, zapify the store, making the
10327 // alloca dead.
Chris Lattnere331a652008-04-29 04:58:38 +000010328 if (Ptr->hasOneUse() && !SI.isVolatile()) {
Chris Lattnera4beeef2007-01-15 06:51:56 +000010329 if (isa<AllocaInst>(Ptr)) {
10330 EraseInstFromFunction(SI);
10331 ++NumCombined;
10332 return 0;
10333 }
10334
10335 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
10336 if (isa<AllocaInst>(GEP->getOperand(0)) &&
10337 GEP->getOperand(0)->hasOneUse()) {
10338 EraseInstFromFunction(SI);
10339 ++NumCombined;
10340 return 0;
10341 }
10342 }
Chris Lattner31f486c2005-01-31 05:36:43 +000010343
Dan Gohmane31a61e2007-07-20 16:34:21 +000010344 // Attempt to improve the alignment.
Dan Gohman99b7b3f2008-04-10 18:43:06 +000010345 unsigned KnownAlign = GetOrEnforceKnownAlignment(Ptr);
10346 if (KnownAlign >
10347 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
10348 SI.getAlignment()))
Dan Gohmane31a61e2007-07-20 16:34:21 +000010349 SI.setAlignment(KnownAlign);
10350
Chris Lattner5997cf92006-02-08 03:25:32 +000010351 // Do really simple DSE, to catch cases where there are several consequtive
10352 // stores to the same location, separated by a few arithmetic operations. This
10353 // situation often occurs with bitfield accesses.
10354 BasicBlock::iterator BBI = &SI;
10355 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
10356 --ScanInsts) {
10357 --BBI;
10358
10359 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
10360 // Prev store isn't volatile, and stores to the same location?
10361 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
10362 ++NumDeadStore;
10363 ++BBI;
10364 EraseInstFromFunction(*PrevSI);
10365 continue;
10366 }
10367 break;
10368 }
10369
Chris Lattnerdab43b22006-05-26 19:19:20 +000010370 // If this is a load, we have to stop. However, if the loaded value is from
10371 // the pointer we're loading and is producing the pointer we're storing,
10372 // then *this* store is dead (X = load P; store X -> P).
10373 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Chris Lattner85a51e02007-09-07 05:33:03 +000010374 if (LI == Val && LI->getOperand(0) == Ptr && !SI.isVolatile()) {
Chris Lattnerdab43b22006-05-26 19:19:20 +000010375 EraseInstFromFunction(SI);
10376 ++NumCombined;
10377 return 0;
10378 }
10379 // Otherwise, this is a load from some other location. Stores before it
10380 // may not be dead.
10381 break;
10382 }
10383
Chris Lattner5997cf92006-02-08 03:25:32 +000010384 // Don't skip over loads or things that can modify memory.
Chris Lattnerdab43b22006-05-26 19:19:20 +000010385 if (BBI->mayWriteToMemory())
Chris Lattner5997cf92006-02-08 03:25:32 +000010386 break;
10387 }
10388
10389
10390 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner31f486c2005-01-31 05:36:43 +000010391
10392 // store X, null -> turns into 'unreachable' in SimplifyCFG
10393 if (isa<ConstantPointerNull>(Ptr)) {
10394 if (!isa<UndefValue>(Val)) {
10395 SI.setOperand(0, UndefValue::get(Val->getType()));
10396 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattnerb15e2b12007-03-02 21:28:56 +000010397 AddToWorkList(U); // Dropped a use.
Chris Lattner31f486c2005-01-31 05:36:43 +000010398 ++NumCombined;
10399 }
10400 return 0; // Do not modify these!
10401 }
10402
10403 // store undef, Ptr -> noop
10404 if (isa<UndefValue>(Val)) {
Chris Lattner5997cf92006-02-08 03:25:32 +000010405 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +000010406 ++NumCombined;
10407 return 0;
10408 }
10409
Chris Lattner72684fe2005-01-31 05:51:45 +000010410 // If the pointer destination is a cast, see if we can fold the cast into the
10411 // source instead.
Reid Spencerde46e482006-11-02 20:25:50 +000010412 if (isa<CastInst>(Ptr))
Chris Lattner72684fe2005-01-31 05:51:45 +000010413 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10414 return Res;
10415 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer6c38f0b2006-11-27 01:05:10 +000010416 if (CE->isCast())
Chris Lattner72684fe2005-01-31 05:51:45 +000010417 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10418 return Res;
10419
Chris Lattner219175c2005-09-12 23:23:25 +000010420
10421 // If this store is the last instruction in the basic block, and if the block
10422 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner5997cf92006-02-08 03:25:32 +000010423 BBI = &SI; ++BBI;
Chris Lattner219175c2005-09-12 23:23:25 +000010424 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
Chris Lattner14a251b2007-04-15 00:07:55 +000010425 if (BI->isUnconditional())
10426 if (SimplifyStoreAtEndOfBlock(SI))
10427 return 0; // xform done!
Chris Lattner219175c2005-09-12 23:23:25 +000010428
Chris Lattner31f486c2005-01-31 05:36:43 +000010429 return 0;
10430}
10431
Chris Lattner14a251b2007-04-15 00:07:55 +000010432/// SimplifyStoreAtEndOfBlock - Turn things like:
10433/// if () { *P = v1; } else { *P = v2 }
10434/// into a phi node with a store in the successor.
10435///
Chris Lattner4a6e0cb2007-04-15 01:02:18 +000010436/// Simplify things like:
10437/// *P = v1; if () { *P = v2; }
10438/// into a phi node with a store in the successor.
10439///
Chris Lattner14a251b2007-04-15 00:07:55 +000010440bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
10441 BasicBlock *StoreBB = SI.getParent();
10442
10443 // Check to see if the successor block has exactly two incoming edges. If
10444 // so, see if the other predecessor contains a store to the same location.
10445 // if so, insert a PHI node (if needed) and move the stores down.
Chris Lattner4a6e0cb2007-04-15 01:02:18 +000010446 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Chris Lattner14a251b2007-04-15 00:07:55 +000010447
10448 // Determine whether Dest has exactly two predecessors and, if so, compute
10449 // the other predecessor.
Chris Lattner4a6e0cb2007-04-15 01:02:18 +000010450 pred_iterator PI = pred_begin(DestBB);
10451 BasicBlock *OtherBB = 0;
Chris Lattner14a251b2007-04-15 00:07:55 +000010452 if (*PI != StoreBB)
Chris Lattner4a6e0cb2007-04-15 01:02:18 +000010453 OtherBB = *PI;
Chris Lattner14a251b2007-04-15 00:07:55 +000010454 ++PI;
Chris Lattner4a6e0cb2007-04-15 01:02:18 +000010455 if (PI == pred_end(DestBB))
Chris Lattner14a251b2007-04-15 00:07:55 +000010456 return false;
10457
10458 if (*PI != StoreBB) {
Chris Lattner4a6e0cb2007-04-15 01:02:18 +000010459 if (OtherBB)
Chris Lattner14a251b2007-04-15 00:07:55 +000010460 return false;
Chris Lattner4a6e0cb2007-04-15 01:02:18 +000010461 OtherBB = *PI;
Chris Lattner14a251b2007-04-15 00:07:55 +000010462 }
Chris Lattner4a6e0cb2007-04-15 01:02:18 +000010463 if (++PI != pred_end(DestBB))
Chris Lattner14a251b2007-04-15 00:07:55 +000010464 return false;
10465
10466
Chris Lattner4a6e0cb2007-04-15 01:02:18 +000010467 // Verify that the other block ends in a branch and is not otherwise empty.
10468 BasicBlock::iterator BBI = OtherBB->getTerminator();
Chris Lattner14a251b2007-04-15 00:07:55 +000010469 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
Chris Lattner4a6e0cb2007-04-15 01:02:18 +000010470 if (!OtherBr || BBI == OtherBB->begin())
Chris Lattner14a251b2007-04-15 00:07:55 +000010471 return false;
10472
Chris Lattner4a6e0cb2007-04-15 01:02:18 +000010473 // If the other block ends in an unconditional branch, check for the 'if then
10474 // else' case. there is an instruction before the branch.
10475 StoreInst *OtherStore = 0;
10476 if (OtherBr->isUnconditional()) {
10477 // If this isn't a store, or isn't a store to the same location, bail out.
10478 --BBI;
10479 OtherStore = dyn_cast<StoreInst>(BBI);
10480 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
10481 return false;
10482 } else {
Chris Lattner361e9812007-05-05 22:32:24 +000010483 // Otherwise, the other block ended with a conditional branch. If one of the
Chris Lattner4a6e0cb2007-04-15 01:02:18 +000010484 // destinations is StoreBB, then we have the if/then case.
10485 if (OtherBr->getSuccessor(0) != StoreBB &&
10486 OtherBr->getSuccessor(1) != StoreBB)
10487 return false;
10488
10489 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
Chris Lattner361e9812007-05-05 22:32:24 +000010490 // if/then triangle. See if there is a store to the same ptr as SI that
10491 // lives in OtherBB.
Chris Lattner4a6e0cb2007-04-15 01:02:18 +000010492 for (;; --BBI) {
10493 // Check to see if we find the matching store.
10494 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
10495 if (OtherStore->getOperand(1) != SI.getOperand(1))
10496 return false;
10497 break;
10498 }
Chris Lattner361e9812007-05-05 22:32:24 +000010499 // If we find something that may be using the stored value, or if we run
10500 // out of instructions, we can't do the xform.
Chris Lattner4a6e0cb2007-04-15 01:02:18 +000010501 if (isa<LoadInst>(BBI) || BBI->mayWriteToMemory() ||
10502 BBI == OtherBB->begin())
10503 return false;
10504 }
10505
10506 // In order to eliminate the store in OtherBr, we have to
10507 // make sure nothing reads the stored value in StoreBB.
10508 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
10509 // FIXME: This should really be AA driven.
10510 if (isa<LoadInst>(I) || I->mayWriteToMemory())
10511 return false;
10512 }
10513 }
Chris Lattner14a251b2007-04-15 00:07:55 +000010514
Chris Lattner4a6e0cb2007-04-15 01:02:18 +000010515 // Insert a PHI node now if we need it.
Chris Lattner14a251b2007-04-15 00:07:55 +000010516 Value *MergedVal = OtherStore->getOperand(0);
10517 if (MergedVal != SI.getOperand(0)) {
Gabor Greife9ecc682008-04-06 20:25:17 +000010518 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Chris Lattner14a251b2007-04-15 00:07:55 +000010519 PN->reserveOperandSpace(2);
10520 PN->addIncoming(SI.getOperand(0), SI.getParent());
Chris Lattner4a6e0cb2007-04-15 01:02:18 +000010521 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
10522 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Chris Lattner14a251b2007-04-15 00:07:55 +000010523 }
10524
10525 // Advance to a place where it is safe to insert the new store and
10526 // insert it.
Chris Lattner4a6e0cb2007-04-15 01:02:18 +000010527 BBI = DestBB->begin();
Chris Lattner14a251b2007-04-15 00:07:55 +000010528 while (isa<PHINode>(BBI)) ++BBI;
10529 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
10530 OtherStore->isVolatile()), *BBI);
10531
10532 // Nuke the old stores.
10533 EraseInstFromFunction(SI);
10534 EraseInstFromFunction(*OtherStore);
10535 ++NumCombined;
10536 return true;
10537}
10538
Chris Lattner31f486c2005-01-31 05:36:43 +000010539
Chris Lattner9eef8a72003-06-04 04:46:00 +000010540Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
10541 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4fdd96c2005-06-18 17:37:34 +000010542 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +000010543 BasicBlock *TrueDest;
10544 BasicBlock *FalseDest;
10545 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
10546 !isa<Constant>(X)) {
10547 // Swap Destinations and condition...
10548 BI.setCondition(X);
10549 BI.setSuccessor(0, FalseDest);
10550 BI.setSuccessor(1, TrueDest);
10551 return &BI;
10552 }
10553
Reid Spencer266e42b2006-12-23 06:05:41 +000010554 // Cannonicalize fcmp_one -> fcmp_oeq
10555 FCmpInst::Predicate FPred; Value *Y;
10556 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
10557 TrueDest, FalseDest)))
10558 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
10559 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
10560 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
Reid Spencer266e42b2006-12-23 06:05:41 +000010561 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
Chris Lattner6e0123b2007-02-11 01:23:03 +000010562 Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
10563 NewSCC->takeName(I);
Reid Spencer266e42b2006-12-23 06:05:41 +000010564 // Swap Destinations and condition...
10565 BI.setCondition(NewSCC);
10566 BI.setSuccessor(0, FalseDest);
10567 BI.setSuccessor(1, TrueDest);
Chris Lattnerb15e2b12007-03-02 21:28:56 +000010568 RemoveFromWorkList(I);
Chris Lattner6e0123b2007-02-11 01:23:03 +000010569 I->eraseFromParent();
Chris Lattnerb15e2b12007-03-02 21:28:56 +000010570 AddToWorkList(NewSCC);
Reid Spencer266e42b2006-12-23 06:05:41 +000010571 return &BI;
10572 }
10573
10574 // Cannonicalize icmp_ne -> icmp_eq
10575 ICmpInst::Predicate IPred;
10576 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
10577 TrueDest, FalseDest)))
10578 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
10579 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
10580 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
10581 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
Reid Spencer266e42b2006-12-23 06:05:41 +000010582 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
Chris Lattner6e0123b2007-02-11 01:23:03 +000010583 Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
10584 NewSCC->takeName(I);
Chris Lattnere967b342003-06-04 05:10:11 +000010585 // Swap Destinations and condition...
Chris Lattnerd4252a72004-07-30 07:50:03 +000010586 BI.setCondition(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +000010587 BI.setSuccessor(0, FalseDest);
10588 BI.setSuccessor(1, TrueDest);
Chris Lattnerb15e2b12007-03-02 21:28:56 +000010589 RemoveFromWorkList(I);
Chris Lattner6e0123b2007-02-11 01:23:03 +000010590 I->eraseFromParent();;
Chris Lattnerb15e2b12007-03-02 21:28:56 +000010591 AddToWorkList(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +000010592 return &BI;
10593 }
Misha Brukmanb1c93172005-04-21 23:48:37 +000010594
Chris Lattner9eef8a72003-06-04 04:46:00 +000010595 return 0;
10596}
Chris Lattner1085bdf2002-11-04 16:18:53 +000010597
Chris Lattner4c9c20a2004-07-03 00:26:11 +000010598Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
10599 Value *Cond = SI.getCondition();
10600 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
10601 if (I->getOpcode() == Instruction::Add)
10602 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
10603 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
10604 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattner81a7a232004-10-16 18:11:37 +000010605 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner4c9c20a2004-07-03 00:26:11 +000010606 AddRHS));
10607 SI.setOperand(0, I->getOperand(0));
Chris Lattnerb15e2b12007-03-02 21:28:56 +000010608 AddToWorkList(I);
Chris Lattner4c9c20a2004-07-03 00:26:11 +000010609 return &SI;
10610 }
10611 }
10612 return 0;
10613}
10614
Chris Lattner6bc98652006-03-05 00:22:33 +000010615/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
10616/// is to leave as a vector operation.
10617static bool CheapToScalarize(Value *V, bool isConstant) {
10618 if (isa<ConstantAggregateZero>(V))
10619 return true;
Reid Spencerd84d35b2007-02-15 02:26:10 +000010620 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner6bc98652006-03-05 00:22:33 +000010621 if (isConstant) return true;
10622 // If all elts are the same, we can extract.
10623 Constant *Op0 = C->getOperand(0);
10624 for (unsigned i = 1; i < C->getNumOperands(); ++i)
10625 if (C->getOperand(i) != Op0)
10626 return false;
10627 return true;
10628 }
10629 Instruction *I = dyn_cast<Instruction>(V);
10630 if (!I) return false;
10631
10632 // Insert element gets simplified to the inserted element or is deleted if
10633 // this is constant idx extract element and its a constant idx insertelt.
10634 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
10635 isa<ConstantInt>(I->getOperand(2)))
10636 return true;
10637 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
10638 return true;
10639 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
10640 if (BO->hasOneUse() &&
10641 (CheapToScalarize(BO->getOperand(0), isConstant) ||
10642 CheapToScalarize(BO->getOperand(1), isConstant)))
10643 return true;
Reid Spencer266e42b2006-12-23 06:05:41 +000010644 if (CmpInst *CI = dyn_cast<CmpInst>(I))
10645 if (CI->hasOneUse() &&
10646 (CheapToScalarize(CI->getOperand(0), isConstant) ||
10647 CheapToScalarize(CI->getOperand(1), isConstant)))
10648 return true;
Chris Lattner6bc98652006-03-05 00:22:33 +000010649
10650 return false;
10651}
10652
Chris Lattner945e4372007-02-14 05:52:17 +000010653/// Read and decode a shufflevector mask.
10654///
10655/// It turns undef elements into values that are larger than the number of
10656/// elements in the input.
Chris Lattner12249be2006-05-25 23:48:38 +000010657static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
10658 unsigned NElts = SVI->getType()->getNumElements();
10659 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
10660 return std::vector<unsigned>(NElts, 0);
10661 if (isa<UndefValue>(SVI->getOperand(2)))
10662 return std::vector<unsigned>(NElts, 2*NElts);
10663
10664 std::vector<unsigned> Result;
Reid Spencerd84d35b2007-02-15 02:26:10 +000010665 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Chris Lattner12249be2006-05-25 23:48:38 +000010666 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
10667 if (isa<UndefValue>(CP->getOperand(i)))
10668 Result.push_back(NElts*2); // undef -> 8
10669 else
Reid Spencere0fc4df2006-10-20 07:07:24 +000010670 Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
Chris Lattner12249be2006-05-25 23:48:38 +000010671 return Result;
10672}
10673
Chris Lattner8d1d8d32006-03-31 23:01:56 +000010674/// FindScalarElement - Given a vector and an element number, see if the scalar
10675/// value is already around as a register, for example if it were inserted then
10676/// extracted from the vector.
10677static Value *FindScalarElement(Value *V, unsigned EltNo) {
Reid Spencerd84d35b2007-02-15 02:26:10 +000010678 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
10679 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner2d37f922006-04-10 23:06:36 +000010680 unsigned Width = PTy->getNumElements();
10681 if (EltNo >= Width) // Out of range access.
Chris Lattner8d1d8d32006-03-31 23:01:56 +000010682 return UndefValue::get(PTy->getElementType());
10683
10684 if (isa<UndefValue>(V))
10685 return UndefValue::get(PTy->getElementType());
10686 else if (isa<ConstantAggregateZero>(V))
10687 return Constant::getNullValue(PTy->getElementType());
Reid Spencerd84d35b2007-02-15 02:26:10 +000010688 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner8d1d8d32006-03-31 23:01:56 +000010689 return CP->getOperand(EltNo);
10690 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
10691 // If this is an insert to a variable element, we don't know what it is.
Reid Spencere0fc4df2006-10-20 07:07:24 +000010692 if (!isa<ConstantInt>(III->getOperand(2)))
10693 return 0;
10694 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner8d1d8d32006-03-31 23:01:56 +000010695
10696 // If this is an insert to the element we are looking for, return the
10697 // inserted value.
Reid Spencere0fc4df2006-10-20 07:07:24 +000010698 if (EltNo == IIElt)
10699 return III->getOperand(1);
Chris Lattner8d1d8d32006-03-31 23:01:56 +000010700
10701 // Otherwise, the insertelement doesn't modify the value, recurse on its
10702 // vector input.
10703 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner2d37f922006-04-10 23:06:36 +000010704 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Chris Lattner12249be2006-05-25 23:48:38 +000010705 unsigned InEl = getShuffleMask(SVI)[EltNo];
10706 if (InEl < Width)
10707 return FindScalarElement(SVI->getOperand(0), InEl);
10708 else if (InEl < Width*2)
10709 return FindScalarElement(SVI->getOperand(1), InEl - Width);
10710 else
10711 return UndefValue::get(PTy->getElementType());
Chris Lattner8d1d8d32006-03-31 23:01:56 +000010712 }
10713
10714 // Otherwise, we don't know.
10715 return 0;
10716}
10717
Robert Bocchinoa8352962006-01-13 22:48:06 +000010718Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Chris Lattner8d1d8d32006-03-31 23:01:56 +000010719
Dan Gohman06c60b62007-07-16 14:29:03 +000010720 // If vector val is undef, replace extract with scalar undef.
Chris Lattner92346c32006-03-31 18:25:14 +000010721 if (isa<UndefValue>(EI.getOperand(0)))
10722 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10723
Dan Gohman06c60b62007-07-16 14:29:03 +000010724 // If vector val is constant 0, replace extract with scalar 0.
Chris Lattner92346c32006-03-31 18:25:14 +000010725 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
10726 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
10727
Reid Spencerd84d35b2007-02-15 02:26:10 +000010728 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Dan Gohman06c60b62007-07-16 14:29:03 +000010729 // If vector val is constant with uniform operands, replace EI
Robert Bocchinoa8352962006-01-13 22:48:06 +000010730 // with that operand
Chris Lattner6bc98652006-03-05 00:22:33 +000010731 Constant *op0 = C->getOperand(0);
Robert Bocchinoa8352962006-01-13 22:48:06 +000010732 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner6bc98652006-03-05 00:22:33 +000010733 if (C->getOperand(i) != op0) {
10734 op0 = 0;
10735 break;
10736 }
10737 if (op0)
10738 return ReplaceInstUsesWith(EI, op0);
Robert Bocchinoa8352962006-01-13 22:48:06 +000010739 }
Chris Lattner6bc98652006-03-05 00:22:33 +000010740
Chris Lattner8d1d8d32006-03-31 23:01:56 +000010741 // If extracting a specified index from the vector, see if we can recursively
10742 // find a previously computed scalar that was inserted into the vector.
Reid Spencere0fc4df2006-10-20 07:07:24 +000010743 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattnera87c9f62007-04-09 01:37:55 +000010744 unsigned IndexVal = IdxC->getZExtValue();
10745 unsigned VectorWidth =
10746 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
10747
10748 // If this is extracting an invalid index, turn this into undef, to avoid
10749 // crashing the code below.
10750 if (IndexVal >= VectorWidth)
10751 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10752
Chris Lattner2deeaea2006-10-05 06:55:50 +000010753 // This instruction only demands the single element from the input vector.
10754 // If the input vector has a single use, simplify it based on this use
10755 // property.
Chris Lattnera87c9f62007-04-09 01:37:55 +000010756 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Chris Lattner2deeaea2006-10-05 06:55:50 +000010757 uint64_t UndefElts;
10758 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Reid Spencere0fc4df2006-10-20 07:07:24 +000010759 1 << IndexVal,
Chris Lattner2deeaea2006-10-05 06:55:50 +000010760 UndefElts)) {
10761 EI.setOperand(0, V);
10762 return &EI;
10763 }
10764 }
10765
Reid Spencere0fc4df2006-10-20 07:07:24 +000010766 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
Chris Lattner8d1d8d32006-03-31 23:01:56 +000010767 return ReplaceInstUsesWith(EI, Elt);
Chris Lattner7bfdd0a2007-04-14 23:02:14 +000010768
10769 // If the this extractelement is directly using a bitcast from a vector of
10770 // the same number of elements, see if we can find the source element from
10771 // it. In this case, we will end up needing to bitcast the scalars.
10772 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
10773 if (const VectorType *VT =
10774 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
10775 if (VT->getNumElements() == VectorWidth)
10776 if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
10777 return new BitCastInst(Elt, EI.getType());
10778 }
Chris Lattner2d37f922006-04-10 23:06:36 +000010779 }
Chris Lattner8d1d8d32006-03-31 23:01:56 +000010780
Chris Lattner83f65782006-05-25 22:53:38 +000010781 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchinoa8352962006-01-13 22:48:06 +000010782 if (I->hasOneUse()) {
10783 // Push extractelement into predecessor operation if legal and
10784 // profitable to do so
10785 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner6bc98652006-03-05 00:22:33 +000010786 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
10787 if (CheapToScalarize(BO, isConstantElt)) {
10788 ExtractElementInst *newEI0 =
10789 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
10790 EI.getName()+".lhs");
10791 ExtractElementInst *newEI1 =
10792 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
10793 EI.getName()+".rhs");
10794 InsertNewInstBefore(newEI0, EI);
10795 InsertNewInstBefore(newEI1, EI);
10796 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
10797 }
Reid Spencerde46e482006-11-02 20:25:50 +000010798 } else if (isa<LoadInst>(I)) {
Christopher Lambedf07882007-12-17 01:12:55 +000010799 unsigned AS =
10800 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
Chris Lattner5a866122008-01-13 22:23:22 +000010801 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
10802 PointerType::get(EI.getType(), AS),EI);
Robert Bocchinoa8352962006-01-13 22:48:06 +000010803 GetElementPtrInst *GEP =
Gabor Greife9ecc682008-04-06 20:25:17 +000010804 GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName() + ".gep");
Robert Bocchinoa8352962006-01-13 22:48:06 +000010805 InsertNewInstBefore(GEP, EI);
10806 return new LoadInst(GEP);
Chris Lattner83f65782006-05-25 22:53:38 +000010807 }
10808 }
10809 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
10810 // Extracting the inserted element?
10811 if (IE->getOperand(2) == EI.getOperand(1))
10812 return ReplaceInstUsesWith(EI, IE->getOperand(1));
10813 // If the inserted and extracted elements are constants, they must not
10814 // be the same value, extract from the pre-inserted value instead.
10815 if (isa<Constant>(IE->getOperand(2)) &&
10816 isa<Constant>(EI.getOperand(1))) {
10817 AddUsesToWorkList(EI);
10818 EI.setOperand(0, IE->getOperand(0));
10819 return &EI;
10820 }
10821 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
10822 // If this is extracting an element from a shufflevector, figure out where
10823 // it came from and extract from the appropriate input element instead.
Reid Spencere0fc4df2006-10-20 07:07:24 +000010824 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
10825 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner12249be2006-05-25 23:48:38 +000010826 Value *Src;
10827 if (SrcIdx < SVI->getType()->getNumElements())
10828 Src = SVI->getOperand(0);
10829 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
10830 SrcIdx -= SVI->getType()->getNumElements();
10831 Src = SVI->getOperand(1);
10832 } else {
10833 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner612fa8e2006-03-30 22:02:40 +000010834 }
Chris Lattner2deeaea2006-10-05 06:55:50 +000010835 return new ExtractElementInst(Src, SrcIdx);
Robert Bocchinoa8352962006-01-13 22:48:06 +000010836 }
10837 }
Chris Lattner83f65782006-05-25 22:53:38 +000010838 }
Robert Bocchinoa8352962006-01-13 22:48:06 +000010839 return 0;
10840}
10841
Chris Lattner90951862006-04-16 00:51:47 +000010842/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
10843/// elements from either LHS or RHS, return the shuffle mask and true.
10844/// Otherwise, return false.
10845static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
10846 std::vector<Constant*> &Mask) {
10847 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
10848 "Invalid CollectSingleShuffleElements");
Reid Spencerd84d35b2007-02-15 02:26:10 +000010849 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner90951862006-04-16 00:51:47 +000010850
10851 if (isa<UndefValue>(V)) {
Reid Spencerc635f472006-12-31 05:48:39 +000010852 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner90951862006-04-16 00:51:47 +000010853 return true;
10854 } else if (V == LHS) {
10855 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc635f472006-12-31 05:48:39 +000010856 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner90951862006-04-16 00:51:47 +000010857 return true;
10858 } else if (V == RHS) {
10859 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc635f472006-12-31 05:48:39 +000010860 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
Chris Lattner90951862006-04-16 00:51:47 +000010861 return true;
10862 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
10863 // If this is an insert of an extract from some other vector, include it.
10864 Value *VecOp = IEI->getOperand(0);
10865 Value *ScalarOp = IEI->getOperand(1);
10866 Value *IdxOp = IEI->getOperand(2);
10867
Chris Lattnerb6cb64b2006-04-27 21:14:21 +000010868 if (!isa<ConstantInt>(IdxOp))
10869 return false;
Reid Spencere0fc4df2006-10-20 07:07:24 +000010870 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerb6cb64b2006-04-27 21:14:21 +000010871
10872 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
10873 // Okay, we can handle this if the vector we are insertinting into is
10874 // transitively ok.
10875 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
10876 // If so, update the mask to reflect the inserted undef.
Reid Spencerc635f472006-12-31 05:48:39 +000010877 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
Chris Lattnerb6cb64b2006-04-27 21:14:21 +000010878 return true;
10879 }
10880 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
10881 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner90951862006-04-16 00:51:47 +000010882 EI->getOperand(0)->getType() == V->getType()) {
10883 unsigned ExtractedIdx =
Reid Spencere0fc4df2006-10-20 07:07:24 +000010884 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner90951862006-04-16 00:51:47 +000010885
10886 // This must be extracting from either LHS or RHS.
10887 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
10888 // Okay, we can handle this if the vector we are insertinting into is
10889 // transitively ok.
10890 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
10891 // If so, update the mask to reflect the inserted value.
10892 if (EI->getOperand(0) == LHS) {
10893 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc635f472006-12-31 05:48:39 +000010894 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner90951862006-04-16 00:51:47 +000010895 } else {
10896 assert(EI->getOperand(0) == RHS);
10897 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc635f472006-12-31 05:48:39 +000010898 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
Chris Lattner90951862006-04-16 00:51:47 +000010899
10900 }
10901 return true;
10902 }
10903 }
10904 }
10905 }
10906 }
10907 // TODO: Handle shufflevector here!
10908
10909 return false;
10910}
10911
10912/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
10913/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
10914/// that computes V and the LHS value of the shuffle.
Chris Lattner39fac442006-04-15 01:39:45 +000010915static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner90951862006-04-16 00:51:47 +000010916 Value *&RHS) {
Reid Spencerd84d35b2007-02-15 02:26:10 +000010917 assert(isa<VectorType>(V->getType()) &&
Chris Lattner90951862006-04-16 00:51:47 +000010918 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattner39fac442006-04-15 01:39:45 +000010919 "Invalid shuffle!");
Reid Spencerd84d35b2007-02-15 02:26:10 +000010920 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner39fac442006-04-15 01:39:45 +000010921
10922 if (isa<UndefValue>(V)) {
Reid Spencerc635f472006-12-31 05:48:39 +000010923 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner39fac442006-04-15 01:39:45 +000010924 return V;
10925 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencerc635f472006-12-31 05:48:39 +000010926 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
Chris Lattner39fac442006-04-15 01:39:45 +000010927 return V;
10928 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
10929 // If this is an insert of an extract from some other vector, include it.
10930 Value *VecOp = IEI->getOperand(0);
10931 Value *ScalarOp = IEI->getOperand(1);
10932 Value *IdxOp = IEI->getOperand(2);
10933
10934 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
10935 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
10936 EI->getOperand(0)->getType() == V->getType()) {
10937 unsigned ExtractedIdx =
Reid Spencere0fc4df2006-10-20 07:07:24 +000010938 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
10939 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattner39fac442006-04-15 01:39:45 +000010940
10941 // Either the extracted from or inserted into vector must be RHSVec,
10942 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner90951862006-04-16 00:51:47 +000010943 if (EI->getOperand(0) == RHS || RHS == 0) {
10944 RHS = EI->getOperand(0);
10945 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Chris Lattner39fac442006-04-15 01:39:45 +000010946 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc635f472006-12-31 05:48:39 +000010947 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
Chris Lattner39fac442006-04-15 01:39:45 +000010948 return V;
10949 }
10950
Chris Lattner90951862006-04-16 00:51:47 +000010951 if (VecOp == RHS) {
10952 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattner39fac442006-04-15 01:39:45 +000010953 // Everything but the extracted element is replaced with the RHS.
10954 for (unsigned i = 0; i != NumElts; ++i) {
10955 if (i != InsertedIdx)
Reid Spencerc635f472006-12-31 05:48:39 +000010956 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
Chris Lattner39fac442006-04-15 01:39:45 +000010957 }
10958 return V;
10959 }
Chris Lattner90951862006-04-16 00:51:47 +000010960
10961 // If this insertelement is a chain that comes from exactly these two
10962 // vectors, return the vector and the effective shuffle.
10963 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
10964 return EI->getOperand(0);
10965
Chris Lattner39fac442006-04-15 01:39:45 +000010966 }
10967 }
10968 }
Chris Lattner90951862006-04-16 00:51:47 +000010969 // TODO: Handle shufflevector here!
Chris Lattner39fac442006-04-15 01:39:45 +000010970
10971 // Otherwise, can't do anything fancy. Return an identity vector.
10972 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc635f472006-12-31 05:48:39 +000010973 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner39fac442006-04-15 01:39:45 +000010974 return V;
10975}
10976
10977Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
10978 Value *VecOp = IE.getOperand(0);
10979 Value *ScalarOp = IE.getOperand(1);
10980 Value *IdxOp = IE.getOperand(2);
10981
Chris Lattner4ca9cbb2007-04-09 01:11:16 +000010982 // Inserting an undef or into an undefined place, remove this.
10983 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
10984 ReplaceInstUsesWith(IE, VecOp);
10985
Chris Lattner39fac442006-04-15 01:39:45 +000010986 // If the inserted element was extracted from some other vector, and if the
10987 // indexes are constant, try to turn this into a shufflevector operation.
10988 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
10989 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
10990 EI->getOperand(0)->getType() == IE.getType()) {
10991 unsigned NumVectorElts = IE.getType()->getNumElements();
Chris Lattner28d921d2007-04-14 23:32:02 +000010992 unsigned ExtractedIdx =
10993 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Reid Spencere0fc4df2006-10-20 07:07:24 +000010994 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattner39fac442006-04-15 01:39:45 +000010995
10996 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
10997 return ReplaceInstUsesWith(IE, VecOp);
10998
10999 if (InsertedIdx >= NumVectorElts) // Out of range insert.
11000 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
11001
11002 // If we are extracting a value from a vector, then inserting it right
11003 // back into the same place, just use the input vector.
11004 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
11005 return ReplaceInstUsesWith(IE, VecOp);
11006
11007 // We could theoretically do this for ANY input. However, doing so could
11008 // turn chains of insertelement instructions into a chain of shufflevector
11009 // instructions, and right now we do not merge shufflevectors. As such,
11010 // only do this in a situation where it is clear that there is benefit.
11011 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
11012 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
11013 // the values of VecOp, except then one read from EIOp0.
11014 // Build a new shuffle mask.
11015 std::vector<Constant*> Mask;
11016 if (isa<UndefValue>(VecOp))
Reid Spencerc635f472006-12-31 05:48:39 +000011017 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
Chris Lattner39fac442006-04-15 01:39:45 +000011018 else {
11019 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Reid Spencerc635f472006-12-31 05:48:39 +000011020 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
Chris Lattner39fac442006-04-15 01:39:45 +000011021 NumVectorElts));
11022 }
Reid Spencerc635f472006-12-31 05:48:39 +000011023 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner39fac442006-04-15 01:39:45 +000011024 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Reid Spencerd84d35b2007-02-15 02:26:10 +000011025 ConstantVector::get(Mask));
Chris Lattner39fac442006-04-15 01:39:45 +000011026 }
11027
11028 // If this insertelement isn't used by some other insertelement, turn it
11029 // (and any insertelements it points to), into one big shuffle.
11030 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
11031 std::vector<Constant*> Mask;
Chris Lattner90951862006-04-16 00:51:47 +000011032 Value *RHS = 0;
11033 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
11034 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
11035 // We now have a shuffle of LHS, RHS, Mask.
Reid Spencerd84d35b2007-02-15 02:26:10 +000011036 return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
Chris Lattner39fac442006-04-15 01:39:45 +000011037 }
11038 }
11039 }
11040
11041 return 0;
11042}
11043
11044
Chris Lattnerfbb77a42006-04-10 22:45:52 +000011045Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
11046 Value *LHS = SVI.getOperand(0);
11047 Value *RHS = SVI.getOperand(1);
Chris Lattner12249be2006-05-25 23:48:38 +000011048 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnerfbb77a42006-04-10 22:45:52 +000011049
11050 bool MadeChange = false;
11051
Chris Lattner2deeaea2006-10-05 06:55:50 +000011052 // Undefined shuffle mask -> undefined value.
Chris Lattner12249be2006-05-25 23:48:38 +000011053 if (isa<UndefValue>(SVI.getOperand(2)))
Chris Lattnerfbb77a42006-04-10 22:45:52 +000011054 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
11055
Chris Lattnerd7b6ea12007-01-05 07:36:08 +000011056 // If we have shuffle(x, undef, mask) and any elements of mask refer to
Chris Lattner39fac442006-04-15 01:39:45 +000011057 // the undef, change them to undefs.
Chris Lattnerd7b6ea12007-01-05 07:36:08 +000011058 if (isa<UndefValue>(SVI.getOperand(1))) {
11059 // Scan to see if there are any references to the RHS. If so, replace them
11060 // with undef element refs and set MadeChange to true.
11061 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11062 if (Mask[i] >= e && Mask[i] != 2*e) {
11063 Mask[i] = 2*e;
11064 MadeChange = true;
11065 }
11066 }
11067
11068 if (MadeChange) {
11069 // Remap any references to RHS to use LHS.
11070 std::vector<Constant*> Elts;
11071 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11072 if (Mask[i] == 2*e)
11073 Elts.push_back(UndefValue::get(Type::Int32Ty));
11074 else
11075 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
11076 }
Reid Spencerd84d35b2007-02-15 02:26:10 +000011077 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattnerd7b6ea12007-01-05 07:36:08 +000011078 }
11079 }
Chris Lattner39fac442006-04-15 01:39:45 +000011080
Chris Lattner12249be2006-05-25 23:48:38 +000011081 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
11082 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
11083 if (LHS == RHS || isa<UndefValue>(LHS)) {
11084 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnerfbb77a42006-04-10 22:45:52 +000011085 // shuffle(undef,undef,mask) -> undef.
11086 return ReplaceInstUsesWith(SVI, LHS);
11087 }
11088
Chris Lattner12249be2006-05-25 23:48:38 +000011089 // Remap any references to RHS to use LHS.
11090 std::vector<Constant*> Elts;
11091 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner0e477162006-05-26 00:29:06 +000011092 if (Mask[i] >= 2*e)
Reid Spencerc635f472006-12-31 05:48:39 +000011093 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner0e477162006-05-26 00:29:06 +000011094 else {
11095 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
11096 (Mask[i] < e && isa<UndefValue>(LHS)))
11097 Mask[i] = 2*e; // Turn into undef.
11098 else
11099 Mask[i] &= (e-1); // Force to LHS.
Reid Spencerc635f472006-12-31 05:48:39 +000011100 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
Chris Lattner0e477162006-05-26 00:29:06 +000011101 }
Chris Lattnerfbb77a42006-04-10 22:45:52 +000011102 }
Chris Lattner12249be2006-05-25 23:48:38 +000011103 SVI.setOperand(0, SVI.getOperand(1));
Chris Lattnerfbb77a42006-04-10 22:45:52 +000011104 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Reid Spencerd84d35b2007-02-15 02:26:10 +000011105 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner0e477162006-05-26 00:29:06 +000011106 LHS = SVI.getOperand(0);
11107 RHS = SVI.getOperand(1);
Chris Lattnerfbb77a42006-04-10 22:45:52 +000011108 MadeChange = true;
11109 }
11110
Chris Lattner0e477162006-05-26 00:29:06 +000011111 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner12249be2006-05-25 23:48:38 +000011112 bool isLHSID = true, isRHSID = true;
Chris Lattner34cebe72006-04-16 00:03:56 +000011113
Chris Lattner12249be2006-05-25 23:48:38 +000011114 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11115 if (Mask[i] >= e*2) continue; // Ignore undef values.
11116 // Is this an identity shuffle of the LHS value?
11117 isLHSID &= (Mask[i] == i);
11118
11119 // Is this an identity shuffle of the RHS value?
11120 isRHSID &= (Mask[i]-e == i);
Chris Lattner34cebe72006-04-16 00:03:56 +000011121 }
Chris Lattnerfbb77a42006-04-10 22:45:52 +000011122
Chris Lattner12249be2006-05-25 23:48:38 +000011123 // Eliminate identity shuffles.
11124 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
11125 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnerfbb77a42006-04-10 22:45:52 +000011126
Chris Lattner0e477162006-05-26 00:29:06 +000011127 // If the LHS is a shufflevector itself, see if we can combine it with this
11128 // one without producing an unusual shuffle. Here we are really conservative:
11129 // we are absolutely afraid of producing a shuffle mask not in the input
11130 // program, because the code gen may not be smart enough to turn a merged
11131 // shuffle into two specific shuffles: it may produce worse code. As such,
11132 // we only merge two shuffles if the result is one of the two input shuffle
11133 // masks. In this case, merging the shuffles just removes one instruction,
11134 // which we know is safe. This is good for things like turning:
11135 // (splat(splat)) -> splat.
11136 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
11137 if (isa<UndefValue>(RHS)) {
11138 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
11139
11140 std::vector<unsigned> NewMask;
11141 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
11142 if (Mask[i] >= 2*e)
11143 NewMask.push_back(2*e);
11144 else
11145 NewMask.push_back(LHSMask[Mask[i]]);
11146
11147 // If the result mask is equal to the src shuffle or this shuffle mask, do
11148 // the replacement.
11149 if (NewMask == LHSMask || NewMask == Mask) {
11150 std::vector<Constant*> Elts;
11151 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
11152 if (NewMask[i] >= e*2) {
Reid Spencerc635f472006-12-31 05:48:39 +000011153 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner0e477162006-05-26 00:29:06 +000011154 } else {
Reid Spencerc635f472006-12-31 05:48:39 +000011155 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
Chris Lattner0e477162006-05-26 00:29:06 +000011156 }
11157 }
11158 return new ShuffleVectorInst(LHSSVI->getOperand(0),
11159 LHSSVI->getOperand(1),
Reid Spencerd84d35b2007-02-15 02:26:10 +000011160 ConstantVector::get(Elts));
Chris Lattner0e477162006-05-26 00:29:06 +000011161 }
11162 }
11163 }
Chris Lattner4284f642007-01-30 22:32:46 +000011164
Chris Lattnerfbb77a42006-04-10 22:45:52 +000011165 return MadeChange ? &SVI : 0;
11166}
11167
11168
Robert Bocchinoa8352962006-01-13 22:48:06 +000011169
Chris Lattner39c98bb2004-12-08 23:43:58 +000011170
11171/// TryToSinkInstruction - Try to move the specified instruction from its
11172/// current block into the beginning of DestBlock, which can only happen if it's
11173/// safe to move the instruction past all of the instructions between it and the
11174/// end of its block.
11175static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
11176 assert(I->hasOneUse() && "Invariants didn't hold!");
11177
Chris Lattnerc4f67e62005-10-27 17:13:11 +000011178 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
11179 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +000011180
Chris Lattner39c98bb2004-12-08 23:43:58 +000011181 // Do not sink alloca instructions out of the entry block.
Dan Gohmandcb291f2007-03-22 16:38:57 +000011182 if (isa<AllocaInst>(I) && I->getParent() ==
11183 &DestBlock->getParent()->getEntryBlock())
Chris Lattner39c98bb2004-12-08 23:43:58 +000011184 return false;
11185
Chris Lattnerf17a2fb2004-12-09 07:14:34 +000011186 // We can only sink load instructions if there is nothing between the load and
11187 // the end of block that could change the value.
11188 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattnerf17a2fb2004-12-09 07:14:34 +000011189 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
11190 Scan != E; ++Scan)
11191 if (Scan->mayWriteToMemory())
11192 return false;
Chris Lattnerf17a2fb2004-12-09 07:14:34 +000011193 }
Chris Lattner39c98bb2004-12-08 23:43:58 +000011194
11195 BasicBlock::iterator InsertPos = DestBlock->begin();
11196 while (isa<PHINode>(InsertPos)) ++InsertPos;
11197
Chris Lattner9f269e42005-08-08 19:11:57 +000011198 I->moveBefore(InsertPos);
Chris Lattner39c98bb2004-12-08 23:43:58 +000011199 ++NumSunkInst;
11200 return true;
11201}
11202
Chris Lattnera36ee4e2006-05-10 19:00:36 +000011203
11204/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
11205/// all reachable code to the worklist.
11206///
11207/// This has a couple of tricks to make the code faster and more powerful. In
11208/// particular, we constant fold and DCE instructions as we go, to avoid adding
11209/// them to the worklist (this significantly speeds up instcombine on code where
11210/// many instructions are dead or constant). Additionally, if we find a branch
11211/// whose condition is a known constant, we only visit the reachable successors.
11212///
11213static void AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner7907e5f2007-02-15 19:41:52 +000011214 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerb15e2b12007-03-02 21:28:56 +000011215 InstCombiner &IC,
Chris Lattner1443bc52006-05-11 17:11:52 +000011216 const TargetData *TD) {
Chris Lattner12b89cc2007-03-23 19:17:18 +000011217 std::vector<BasicBlock*> Worklist;
11218 Worklist.push_back(BB);
Chris Lattnera36ee4e2006-05-10 19:00:36 +000011219
Chris Lattner12b89cc2007-03-23 19:17:18 +000011220 while (!Worklist.empty()) {
11221 BB = Worklist.back();
11222 Worklist.pop_back();
11223
11224 // We have now visited this block! If we've already been here, ignore it.
11225 if (!Visited.insert(BB)) continue;
11226
11227 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
11228 Instruction *Inst = BBI++;
Chris Lattnera36ee4e2006-05-10 19:00:36 +000011229
Chris Lattner12b89cc2007-03-23 19:17:18 +000011230 // DCE instruction if trivially dead.
11231 if (isInstructionTriviallyDead(Inst)) {
11232 ++NumDeadInst;
11233 DOUT << "IC: DCE: " << *Inst;
11234 Inst->eraseFromParent();
11235 continue;
11236 }
11237
11238 // ConstantProp instruction if trivially constant.
11239 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
11240 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
11241 Inst->replaceAllUsesWith(C);
11242 ++NumConstProp;
11243 Inst->eraseFromParent();
11244 continue;
11245 }
Chris Lattnerd82e4a12007-07-20 22:06:41 +000011246
Chris Lattner12b89cc2007-03-23 19:17:18 +000011247 IC.AddToWorkList(Inst);
Chris Lattnera36ee4e2006-05-10 19:00:36 +000011248 }
Chris Lattner12b89cc2007-03-23 19:17:18 +000011249
11250 // Recursively visit successors. If this is a branch or switch on a
11251 // constant, only visit the reachable successor.
11252 TerminatorInst *TI = BB->getTerminator();
11253 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
11254 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
11255 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky271506f2008-03-09 08:50:23 +000011256 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewycky4d43d3c2008-04-25 16:53:59 +000011257 Worklist.push_back(ReachableBB);
Chris Lattner12b89cc2007-03-23 19:17:18 +000011258 continue;
11259 }
11260 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
11261 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
11262 // See if this is an explicit destination.
11263 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
11264 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky271506f2008-03-09 08:50:23 +000011265 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewycky4d43d3c2008-04-25 16:53:59 +000011266 Worklist.push_back(ReachableBB);
Chris Lattner12b89cc2007-03-23 19:17:18 +000011267 continue;
11268 }
11269
11270 // Otherwise it is the default destination.
11271 Worklist.push_back(SI->getSuccessor(0));
11272 continue;
11273 }
11274 }
11275
11276 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
11277 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnera36ee4e2006-05-10 19:00:36 +000011278 }
Chris Lattnera36ee4e2006-05-10 19:00:36 +000011279}
11280
Chris Lattner960a5432007-03-03 02:04:50 +000011281bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattner260ab202002-04-18 17:39:14 +000011282 bool Changed = false;
Chris Lattnerf4ad1652003-11-02 05:57:39 +000011283 TD = &getAnalysis<TargetData>();
Chris Lattner960a5432007-03-03 02:04:50 +000011284
11285 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
11286 << F.getNameStr() << "\n");
Chris Lattnerca081252001-12-14 16:52:21 +000011287
Chris Lattner4ed40f72005-07-07 20:40:38 +000011288 {
Chris Lattnera36ee4e2006-05-10 19:00:36 +000011289 // Do a depth-first traversal of the function, populate the worklist with
11290 // the reachable instructions. Ignore blocks that are not reachable. Keep
11291 // track of which blocks we visit.
Chris Lattner7907e5f2007-02-15 19:41:52 +000011292 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerb15e2b12007-03-02 21:28:56 +000011293 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +000011294
Chris Lattner4ed40f72005-07-07 20:40:38 +000011295 // Do a quick scan over the function. If we find any blocks that are
11296 // unreachable, remove any instructions inside of them. This prevents
11297 // the instcombine code from having to deal with some bad special cases.
11298 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
11299 if (!Visited.count(BB)) {
11300 Instruction *Term = BB->getTerminator();
11301 while (Term != BB->begin()) { // Remove instrs bottom-up
11302 BasicBlock::iterator I = Term; --I;
Chris Lattner2d3a7a62004-04-27 15:13:33 +000011303
Bill Wendling5dbf43c2006-11-26 09:46:52 +000011304 DOUT << "IC: DCE: " << *I;
Chris Lattner4ed40f72005-07-07 20:40:38 +000011305 ++NumDeadInst;
11306
11307 if (!I->use_empty())
11308 I->replaceAllUsesWith(UndefValue::get(I->getType()));
11309 I->eraseFromParent();
11310 }
11311 }
11312 }
Chris Lattnerca081252001-12-14 16:52:21 +000011313
Chris Lattnerb15e2b12007-03-02 21:28:56 +000011314 while (!Worklist.empty()) {
11315 Instruction *I = RemoveOneFromWorkList();
11316 if (I == 0) continue; // skip null values.
Chris Lattnerca081252001-12-14 16:52:21 +000011317
Chris Lattner1443bc52006-05-11 17:11:52 +000011318 // Check to see if we can DCE the instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +000011319 if (isInstructionTriviallyDead(I)) {
Chris Lattner1443bc52006-05-11 17:11:52 +000011320 // Add operands to the worklist.
Chris Lattnere8ed4ef2003-10-06 17:11:01 +000011321 if (I->getNumOperands() < 4)
Chris Lattner51ea1272004-02-28 05:22:00 +000011322 AddUsesToWorkList(*I);
Chris Lattner99f48c62002-09-02 04:59:56 +000011323 ++NumDeadInst;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +000011324
Bill Wendling5dbf43c2006-11-26 09:46:52 +000011325 DOUT << "IC: DCE: " << *I;
Chris Lattnercd517ff2005-01-28 19:32:01 +000011326
11327 I->eraseFromParent();
Chris Lattnerb15e2b12007-03-02 21:28:56 +000011328 RemoveFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +000011329 continue;
11330 }
Chris Lattner99f48c62002-09-02 04:59:56 +000011331
Chris Lattner1443bc52006-05-11 17:11:52 +000011332 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattnere3eda252007-01-30 23:16:15 +000011333 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +000011334 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
Chris Lattnercd517ff2005-01-28 19:32:01 +000011335
Chris Lattner1443bc52006-05-11 17:11:52 +000011336 // Add operands to the worklist.
Chris Lattner51ea1272004-02-28 05:22:00 +000011337 AddUsesToWorkList(*I);
Chris Lattnerc6509f42002-12-05 22:41:53 +000011338 ReplaceInstUsesWith(*I, C);
11339
Chris Lattner99f48c62002-09-02 04:59:56 +000011340 ++NumConstProp;
Chris Lattnera36ee4e2006-05-10 19:00:36 +000011341 I->eraseFromParent();
Chris Lattnerb15e2b12007-03-02 21:28:56 +000011342 RemoveFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +000011343 continue;
Chris Lattner99f48c62002-09-02 04:59:56 +000011344 }
Chris Lattnere8ed4ef2003-10-06 17:11:01 +000011345
Chris Lattner39c98bb2004-12-08 23:43:58 +000011346 // See if we can trivially sink this instruction to a successor basic block.
11347 if (I->hasOneUse()) {
11348 BasicBlock *BB = I->getParent();
11349 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
11350 if (UserParent != BB) {
11351 bool UserIsSuccessor = false;
11352 // See if the user is one of our successors.
11353 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
11354 if (*SI == UserParent) {
11355 UserIsSuccessor = true;
11356 break;
11357 }
11358
11359 // If the user is one of our immediate successors, and if that successor
11360 // only has us as a predecessors (we'd have to split the critical edge
11361 // otherwise), we can keep going.
11362 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
11363 next(pred_begin(UserParent)) == pred_end(UserParent))
11364 // Okay, the CFG is simple enough, try to sink this instruction.
11365 Changed |= TryToSinkInstruction(I, UserParent);
11366 }
11367 }
11368
Chris Lattnerca081252001-12-14 16:52:21 +000011369 // Now that we have an instruction, try combining it to simplify it...
Reid Spencer755d0e72007-03-26 17:44:01 +000011370#ifndef NDEBUG
11371 std::string OrigI;
11372#endif
11373 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
Chris Lattnerae7a0d32002-08-02 19:29:35 +000011374 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +000011375 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +000011376 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +000011377 if (Result != I) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +000011378 DOUT << "IC: Old = " << *I
11379 << " New = " << *Result;
Chris Lattner7d2a5392004-03-13 23:54:27 +000011380
Chris Lattner396dbfe2004-06-09 05:08:07 +000011381 // Everything uses the new instruction now.
11382 I->replaceAllUsesWith(Result);
11383
11384 // Push the new instruction and any users onto the worklist.
Chris Lattnerb15e2b12007-03-02 21:28:56 +000011385 AddToWorkList(Result);
Chris Lattner396dbfe2004-06-09 05:08:07 +000011386 AddUsersToWorkList(*Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +000011387
Chris Lattner6e0123b2007-02-11 01:23:03 +000011388 // Move the name to the new instruction first.
11389 Result->takeName(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +000011390
11391 // Insert the new instruction into the basic block...
11392 BasicBlock *InstParent = I->getParent();
Chris Lattner7515cab2004-11-14 19:13:23 +000011393 BasicBlock::iterator InsertPos = I;
11394
11395 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
11396 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
11397 ++InsertPos;
11398
11399 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +000011400
Chris Lattner63d75af2004-05-01 23:27:23 +000011401 // Make sure that we reprocess all operands now that we reduced their
11402 // use counts.
Chris Lattnerb15e2b12007-03-02 21:28:56 +000011403 AddUsesToWorkList(*I);
Chris Lattnerb643a9e2004-05-01 23:19:52 +000011404
Chris Lattner396dbfe2004-06-09 05:08:07 +000011405 // Instructions can end up on the worklist more than once. Make sure
11406 // we do not process an instruction that has been deleted.
Chris Lattnerb15e2b12007-03-02 21:28:56 +000011407 RemoveFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +000011408
11409 // Erase the old instruction.
11410 InstParent->getInstList().erase(I);
Chris Lattner113f4f42002-06-25 16:13:24 +000011411 } else {
Evan Chenga4ed8a52007-03-27 16:44:48 +000011412#ifndef NDEBUG
Reid Spencer755d0e72007-03-26 17:44:01 +000011413 DOUT << "IC: Mod = " << OrigI
11414 << " New = " << *I;
Evan Chenga4ed8a52007-03-27 16:44:48 +000011415#endif
Chris Lattner7d2a5392004-03-13 23:54:27 +000011416
Chris Lattnerae7a0d32002-08-02 19:29:35 +000011417 // If the instruction was modified, it's possible that it is now dead.
11418 // if so, remove it.
Chris Lattner63d75af2004-05-01 23:27:23 +000011419 if (isInstructionTriviallyDead(I)) {
11420 // Make sure we process all operands now that we are reducing their
11421 // use counts.
Chris Lattner960a5432007-03-03 02:04:50 +000011422 AddUsesToWorkList(*I);
Misha Brukmanb1c93172005-04-21 23:48:37 +000011423
Chris Lattner63d75af2004-05-01 23:27:23 +000011424 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchinoa8352962006-01-13 22:48:06 +000011425 // occurrences of this instruction.
Chris Lattnerb15e2b12007-03-02 21:28:56 +000011426 RemoveFromWorkList(I);
Chris Lattner31f486c2005-01-31 05:36:43 +000011427 I->eraseFromParent();
Chris Lattner396dbfe2004-06-09 05:08:07 +000011428 } else {
Chris Lattner960a5432007-03-03 02:04:50 +000011429 AddToWorkList(I);
11430 AddUsersToWorkList(*I);
Chris Lattnerae7a0d32002-08-02 19:29:35 +000011431 }
Chris Lattner053c0932002-05-14 15:24:07 +000011432 }
Chris Lattner260ab202002-04-18 17:39:14 +000011433 Changed = true;
Chris Lattnerca081252001-12-14 16:52:21 +000011434 }
11435 }
11436
Chris Lattner960a5432007-03-03 02:04:50 +000011437 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattnerf0da7972007-08-05 08:47:58 +000011438
11439 // Do an explicit clear, this shrinks the map if needed.
11440 WorklistMap.clear();
Chris Lattner260ab202002-04-18 17:39:14 +000011441 return Changed;
Chris Lattner04805fa2002-02-26 21:46:54 +000011442}
11443
Chris Lattner960a5432007-03-03 02:04:50 +000011444
11445bool InstCombiner::runOnFunction(Function &F) {
Chris Lattner8258b442007-03-04 04:27:24 +000011446 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
11447
Chris Lattner960a5432007-03-03 02:04:50 +000011448 bool EverMadeChange = false;
11449
11450 // Iterate while there is work to do.
11451 unsigned Iteration = 0;
11452 while (DoOneIteration(F, Iteration++))
11453 EverMadeChange = true;
11454 return EverMadeChange;
11455}
11456
Brian Gaeke38b79e82004-07-27 17:43:21 +000011457FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +000011458 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +000011459}
Brian Gaeke960707c2003-11-11 22:41:34 +000011460