blob: 4397540c22f5cc03032352e2dd35db5387afc160 [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
Dan Gohmand78c4002008-05-13 00:00:25 +000011// instructions. This pass does not modify the CFG. This pass is where
12// algebraic 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"
Owen Andersonb5618da2009-07-03 00:17:18 +000039#include "llvm/LLVMContext.h"
Chris Lattner04805fa2002-02-26 21:46:54 +000040#include "llvm/Pass.h"
Chris Lattner1085bdf2002-11-04 16:18:53 +000041#include "llvm/DerivedTypes.h"
Chris Lattner0f1d8a32003-06-26 05:06:25 +000042#include "llvm/GlobalVariable.h"
Chris Lattner024f4ab2007-01-30 23:46:24 +000043#include "llvm/Analysis/ConstantFolding.h"
Chris Lattner965c7692008-06-02 01:18:21 +000044#include "llvm/Analysis/ValueTracking.h"
Chris Lattnerf4ad1652003-11-02 05:57:39 +000045#include "llvm/Target/TargetData.h"
46#include "llvm/Transforms/Utils/BasicBlockUtils.h"
47#include "llvm/Transforms/Utils/Local.h"
Chris Lattner69193f92004-04-05 01:30:19 +000048#include "llvm/Support/CallSite.h"
Nick Lewycky3b592142008-02-03 16:33:09 +000049#include "llvm/Support/ConstantRange.h"
Chris Lattner39c98bb2004-12-08 23:43:58 +000050#include "llvm/Support/Debug.h"
Torok Edwinccb29cd2009-07-11 13:10:19 +000051#include "llvm/Support/ErrorHandling.h"
Chris Lattner69193f92004-04-05 01:30:19 +000052#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner260ab202002-04-18 17:39:14 +000053#include "llvm/Support/InstVisitor.h"
Chris Lattner22d00a82005-08-02 19:16:58 +000054#include "llvm/Support/MathExtras.h"
Chris Lattnerd4252a72004-07-30 07:50:03 +000055#include "llvm/Support/PatternMatch.h"
Chris Lattner3d27be12006-08-27 12:54:02 +000056#include "llvm/Support/Compiler.h"
Chris Lattnerb15e2b12007-03-02 21:28:56 +000057#include "llvm/ADT/DenseMap.h"
Chris Lattnerf96f4a82007-01-31 04:40:53 +000058#include "llvm/ADT/SmallVector.h"
Chris Lattner7907e5f2007-02-15 19:41:52 +000059#include "llvm/ADT/SmallPtrSet.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000060#include "llvm/ADT/Statistic.h"
Chris Lattner39c98bb2004-12-08 23:43:58 +000061#include "llvm/ADT/STLExtras.h"
Chris Lattner053c0932002-05-14 15:24:07 +000062#include <algorithm>
Torok Edwinab207842008-04-20 08:33:11 +000063#include <climits>
Reid Spencer755d0e72007-03-26 17:44:01 +000064#include <sstream>
Chris Lattner8427bff2003-12-07 01:24:23 +000065using namespace llvm;
Chris Lattnerd4252a72004-07-30 07:50:03 +000066using namespace llvm::PatternMatch;
Brian Gaeke960707c2003-11-11 22:41:34 +000067
Chris Lattner79a42ac2006-12-19 21:40:18 +000068STATISTIC(NumCombined , "Number of insts combined");
69STATISTIC(NumConstProp, "Number of constant folds");
70STATISTIC(NumDeadInst , "Number of dead inst eliminated");
71STATISTIC(NumDeadStore, "Number of dead stores eliminated");
72STATISTIC(NumSunkInst , "Number of instructions sunk");
Chris Lattnerbf3a0992002-10-01 22:38:41 +000073
Chris Lattner79a42ac2006-12-19 21:40:18 +000074namespace {
Chris Lattner4a4c7fe2006-06-28 22:08:15 +000075 class VISIBILITY_HIDDEN InstCombiner
76 : public FunctionPass,
77 public InstVisitor<InstCombiner, Instruction*> {
Chris Lattner260ab202002-04-18 17:39:14 +000078 // Worklist of all of the instructions that need to be simplified.
Chris Lattner1d239152008-08-15 04:03:01 +000079 SmallVector<Instruction*, 256> Worklist;
Chris Lattnerb15e2b12007-03-02 21:28:56 +000080 DenseMap<Instruction*, unsigned> WorklistMap;
Chris Lattnerf4ad1652003-11-02 05:57:39 +000081 TargetData *TD;
Chris Lattner8258b442007-03-04 04:27:24 +000082 bool MustPreserveLCSSA;
Chris Lattnerb15e2b12007-03-02 21:28:56 +000083 public:
Nick Lewyckye7da2d62007-05-06 13:37:16 +000084 static char ID; // Pass identification, replacement for typeid
Dan Gohmana79db302008-09-04 17:05:41 +000085 InstCombiner() : FunctionPass(&ID) {}
Devang Patel09f162c2007-05-01 21:15:47 +000086
Owen Anderson38264b12009-07-06 23:00:19 +000087 LLVMContext *getContext() { return Context; }
Owen Andersonb5618da2009-07-03 00:17:18 +000088
Chris Lattnerb15e2b12007-03-02 21:28:56 +000089 /// AddToWorkList - Add the specified instruction to the worklist if it
90 /// isn't already in it.
91 void AddToWorkList(Instruction *I) {
Dan Gohman38740a92008-07-07 17:46:23 +000092 if (WorklistMap.insert(std::make_pair(I, Worklist.size())).second)
Chris Lattnerb15e2b12007-03-02 21:28:56 +000093 Worklist.push_back(I);
94 }
95
96 // RemoveFromWorkList - remove I from the worklist if it exists.
97 void RemoveFromWorkList(Instruction *I) {
98 DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
99 if (It == WorklistMap.end()) return; // Not in worklist.
100
101 // Don't bother moving everything down, just null out the slot.
102 Worklist[It->second] = 0;
103
104 WorklistMap.erase(It);
105 }
106
107 Instruction *RemoveOneFromWorkList() {
108 Instruction *I = Worklist.back();
109 Worklist.pop_back();
110 WorklistMap.erase(I);
111 return I;
112 }
Chris Lattner260ab202002-04-18 17:39:14 +0000113
Chris Lattnerb15e2b12007-03-02 21:28:56 +0000114
Chris Lattner51ea1272004-02-28 05:22:00 +0000115 /// AddUsersToWorkList - When an instruction is simplified, add all users of
116 /// the instruction to the work lists because they might get more simplified
117 /// now.
118 ///
Chris Lattner2590e512006-02-07 06:56:34 +0000119 void AddUsersToWorkList(Value &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +0000120 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattner260ab202002-04-18 17:39:14 +0000121 UI != UE; ++UI)
Chris Lattnerb15e2b12007-03-02 21:28:56 +0000122 AddToWorkList(cast<Instruction>(*UI));
Chris Lattner260ab202002-04-18 17:39:14 +0000123 }
124
Chris Lattner51ea1272004-02-28 05:22:00 +0000125 /// AddUsesToWorkList - When an instruction is simplified, add operands to
126 /// the work lists because they might get more simplified now.
127 ///
128 void AddUsesToWorkList(Instruction &I) {
Gabor Greiff6d8e772008-06-12 21:37:33 +0000129 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
130 if (Instruction *Op = dyn_cast<Instruction>(*i))
Chris Lattnerb15e2b12007-03-02 21:28:56 +0000131 AddToWorkList(Op);
Chris Lattner51ea1272004-02-28 05:22:00 +0000132 }
Chris Lattner2deeaea2006-10-05 06:55:50 +0000133
134 /// AddSoonDeadInstToWorklist - The specified instruction is about to become
135 /// dead. Add all of its operands to the worklist, turning them into
136 /// undef's to reduce the number of uses of those instructions.
137 ///
138 /// Return the specified operand before it is turned into an undef.
139 ///
140 Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
141 Value *R = I.getOperand(op);
142
Gabor Greiff6d8e772008-06-12 21:37:33 +0000143 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
144 if (Instruction *Op = dyn_cast<Instruction>(*i)) {
Chris Lattnerb15e2b12007-03-02 21:28:56 +0000145 AddToWorkList(Op);
Chris Lattner2deeaea2006-10-05 06:55:50 +0000146 // Set the operand to undef to drop the use.
Owen Andersonb5618da2009-07-03 00:17:18 +0000147 *i = Context->getUndef(Op->getType());
Chris Lattner2deeaea2006-10-05 06:55:50 +0000148 }
149
150 return R;
151 }
Chris Lattner51ea1272004-02-28 05:22:00 +0000152
Chris Lattner260ab202002-04-18 17:39:14 +0000153 public:
Chris Lattner113f4f42002-06-25 16:13:24 +0000154 virtual bool runOnFunction(Function &F);
Chris Lattner960a5432007-03-03 02:04:50 +0000155
156 bool DoOneIteration(Function &F, unsigned ItNum);
Chris Lattner260ab202002-04-18 17:39:14 +0000157
Chris Lattnerf12cc842002-04-28 21:27:06 +0000158 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerf4ad1652003-11-02 05:57:39 +0000159 AU.addRequired<TargetData>();
Owen Andersona6968f82006-07-10 19:03:49 +0000160 AU.addPreservedID(LCSSAID);
Chris Lattner820d9712002-10-21 20:00:28 +0000161 AU.setPreservesCFG();
Chris Lattnerf12cc842002-04-28 21:27:06 +0000162 }
163
Chris Lattner69193f92004-04-05 01:30:19 +0000164 TargetData &getTargetData() const { return *TD; }
165
Chris Lattner260ab202002-04-18 17:39:14 +0000166 // Visitation implementation - Implement instruction combining for different
167 // instruction types. The semantics are as follows:
168 // Return Value:
169 // null - No change was made
Chris Lattnere6794492002-08-12 21:17:25 +0000170 // I - Change was made, I is still valid, I may be dead though
Chris Lattner260ab202002-04-18 17:39:14 +0000171 // otherwise - Change was made, replace I with returned instruction
Misha Brukmanb1c93172005-04-21 23:48:37 +0000172 //
Chris Lattner113f4f42002-06-25 16:13:24 +0000173 Instruction *visitAdd(BinaryOperator &I);
Dan Gohmana5b96452009-06-04 22:49:04 +0000174 Instruction *visitFAdd(BinaryOperator &I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000175 Instruction *visitSub(BinaryOperator &I);
Dan Gohmana5b96452009-06-04 22:49:04 +0000176 Instruction *visitFSub(BinaryOperator &I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000177 Instruction *visitMul(BinaryOperator &I);
Dan Gohmana5b96452009-06-04 22:49:04 +0000178 Instruction *visitFMul(BinaryOperator &I);
Reid Spencer7eb55b32006-11-02 01:53:59 +0000179 Instruction *visitURem(BinaryOperator &I);
180 Instruction *visitSRem(BinaryOperator &I);
181 Instruction *visitFRem(BinaryOperator &I);
Chris Lattner16395e52008-07-14 00:15:52 +0000182 bool SimplifyDivRemOfSelect(BinaryOperator &I);
Reid Spencer7eb55b32006-11-02 01:53:59 +0000183 Instruction *commonRemTransforms(BinaryOperator &I);
184 Instruction *commonIRemTransforms(BinaryOperator &I);
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000185 Instruction *commonDivTransforms(BinaryOperator &I);
186 Instruction *commonIDivTransforms(BinaryOperator &I);
187 Instruction *visitUDiv(BinaryOperator &I);
188 Instruction *visitSDiv(BinaryOperator &I);
189 Instruction *visitFDiv(BinaryOperator &I);
Chris Lattner269cbd52008-11-16 05:06:21 +0000190 Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Chris Lattner113f4f42002-06-25 16:13:24 +0000191 Instruction *visitAnd(BinaryOperator &I);
Chris Lattnerd397fef2008-11-16 05:20:07 +0000192 Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Bill Wendling47f733e2008-12-01 08:32:40 +0000193 Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendling22e761b2008-12-01 08:23:25 +0000194 Value *A, Value *B, Value *C);
Chris Lattner113f4f42002-06-25 16:13:24 +0000195 Instruction *visitOr (BinaryOperator &I);
196 Instruction *visitXor(BinaryOperator &I);
Reid Spencer2341c222007-02-02 02:16:23 +0000197 Instruction *visitShl(BinaryOperator &I);
198 Instruction *visitAShr(BinaryOperator &I);
199 Instruction *visitLShr(BinaryOperator &I);
200 Instruction *commonShiftTransforms(BinaryOperator &I);
Chris Lattner5920a782008-05-19 20:18:56 +0000201 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
202 Constant *RHSC);
Reid Spencer266e42b2006-12-23 06:05:41 +0000203 Instruction *visitFCmpInst(FCmpInst &I);
204 Instruction *visitICmpInst(ICmpInst &I);
205 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
Chris Lattnera74deaf2007-04-03 17:43:25 +0000206 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
207 Instruction *LHS,
208 ConstantInt *RHS);
Chris Lattner3bbec592007-06-20 23:46:26 +0000209 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
210 ConstantInt *DivRHS);
Chris Lattnerd1f46d32005-04-24 06:59:08 +0000211
Reid Spencer266e42b2006-12-23 06:05:41 +0000212 Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
213 ICmpInst::Predicate Cond, Instruction &I);
Reid Spencere0fc4df2006-10-20 07:07:24 +0000214 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer2341c222007-02-02 02:16:23 +0000215 BinaryOperator &I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000216 Instruction *commonCastTransforms(CastInst &CI);
217 Instruction *commonIntCastTransforms(CastInst &CI);
Chris Lattner1db224d2007-04-27 17:44:50 +0000218 Instruction *commonPointerCastTransforms(CastInst &CI);
Chris Lattner74ff60f2007-04-11 06:57:46 +0000219 Instruction *visitTrunc(TruncInst &CI);
220 Instruction *visitZExt(ZExtInst &CI);
221 Instruction *visitSExt(SExtInst &CI);
Chris Lattnerfa1e7ee2008-01-27 05:29:54 +0000222 Instruction *visitFPTrunc(FPTruncInst &CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000223 Instruction *visitFPExt(CastInst &CI);
Chris Lattnere35fe0f2008-05-19 20:25:04 +0000224 Instruction *visitFPToUI(FPToUIInst &FI);
225 Instruction *visitFPToSI(FPToSIInst &FI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000226 Instruction *visitUIToFP(CastInst &CI);
227 Instruction *visitSIToFP(CastInst &CI);
Chris Lattner306813c2009-03-24 18:35:40 +0000228 Instruction *visitPtrToInt(PtrToIntInst &CI);
Chris Lattner2940c5c2008-01-08 07:23:51 +0000229 Instruction *visitIntToPtr(IntToPtrInst &CI);
Chris Lattner1db224d2007-04-27 17:44:50 +0000230 Instruction *visitBitCast(BitCastInst &CI);
Chris Lattner411336f2005-01-19 21:50:18 +0000231 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
232 Instruction *FI);
Evan Cheng826b6f02009-03-31 20:42:45 +0000233 Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
Dan Gohmandafa9c62008-09-16 18:46:06 +0000234 Instruction *visitSelectInst(SelectInst &SI);
235 Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
Chris Lattner970c33a2003-06-19 17:00:31 +0000236 Instruction *visitCallInst(CallInst &CI);
237 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner113f4f42002-06-25 16:13:24 +0000238 Instruction *visitPHINode(PHINode &PN);
239 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner1085bdf2002-11-04 16:18:53 +0000240 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner8427bff2003-12-07 01:24:23 +0000241 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner0f1d8a32003-06-26 05:06:25 +0000242 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner31f486c2005-01-31 05:36:43 +0000243 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattner9eef8a72003-06-04 04:46:00 +0000244 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner4c9c20a2004-07-03 00:26:11 +0000245 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattner39fac442006-04-15 01:39:45 +0000246 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchinoa8352962006-01-13 22:48:06 +0000247 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnerfbb77a42006-04-10 22:45:52 +0000248 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Matthijs Kooijmanb2fc72b2008-06-11 14:05:05 +0000249 Instruction *visitExtractValueInst(ExtractValueInst &EV);
Chris Lattner260ab202002-04-18 17:39:14 +0000250
251 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner113f4f42002-06-25 16:13:24 +0000252 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000253
Chris Lattner970c33a2003-06-19 17:00:31 +0000254 private:
Chris Lattneraec3d942003-10-07 22:32:43 +0000255 Instruction *visitCallSite(CallSite CS);
Chris Lattner970c33a2003-06-19 17:00:31 +0000256 bool transformConstExprCastCall(CallSite CS);
Duncan Sands6d5da712007-09-17 10:26:40 +0000257 Instruction *transformCallThroughTrampoline(CallSite CS);
Evan Chengc3cf9f82008-03-24 00:21:34 +0000258 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
259 bool DoXform = true);
Chris Lattner7ac943f2008-05-20 05:46:13 +0000260 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
Dale Johannesen77456b72009-03-03 21:26:39 +0000261 DbgDeclareInst *hasOneUsePlusDeclare(Value *V);
262
Chris Lattner970c33a2003-06-19 17:00:31 +0000263
Chris Lattner69193f92004-04-05 01:30:19 +0000264 public:
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000265 // InsertNewInstBefore - insert an instruction New before instruction Old
266 // in the program. Add the new instruction to the worklist.
267 //
Chris Lattner623826c2004-09-28 21:48:02 +0000268 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattner65217ff2002-08-23 18:32:43 +0000269 assert(New && New->getParent() == 0 &&
270 "New instruction already inserted into a basic block!");
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000271 BasicBlock *BB = Old.getParent();
272 BB->getInstList().insert(&Old, New); // Insert inst
Chris Lattnerb15e2b12007-03-02 21:28:56 +0000273 AddToWorkList(New);
Chris Lattnere79e8542004-02-23 06:38:22 +0000274 return New;
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000275 }
276
Chris Lattner7e794272004-09-24 15:21:34 +0000277 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
278 /// This also adds the cast to the worklist. Finally, this returns the
279 /// cast.
Reid Spencer13bc5d72006-12-12 09:18:51 +0000280 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
281 Instruction &Pos) {
Chris Lattner7e794272004-09-24 15:21:34 +0000282 if (V->getType() == Ty) return V;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000283
Chris Lattnere79d2492006-04-06 19:19:17 +0000284 if (Constant *CV = dyn_cast<Constant>(V))
Owen Andersonb5618da2009-07-03 00:17:18 +0000285 return Context->getConstantExprCast(opc, CV, Ty);
Chris Lattnere79d2492006-04-06 19:19:17 +0000286
Gabor Greife1f6e4b2008-05-16 19:29:10 +0000287 Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
Chris Lattnerb15e2b12007-03-02 21:28:56 +0000288 AddToWorkList(C);
Chris Lattner7e794272004-09-24 15:21:34 +0000289 return C;
290 }
Chris Lattner5a866122008-01-13 22:23:22 +0000291
292 Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
293 return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
294 }
295
Chris Lattner7e794272004-09-24 15:21:34 +0000296
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000297 // ReplaceInstUsesWith - This method is to be used when an instruction is
298 // found to be dead, replacable with another preexisting expression. Here
299 // we add all uses of I to the worklist, replace all uses of I with the new
300 // value, then return I, so that the inst combiner will know that I was
301 // modified.
302 //
303 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner51ea1272004-02-28 05:22:00 +0000304 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner8953b902004-04-05 02:10:19 +0000305 if (&I != V) {
306 I.replaceAllUsesWith(V);
307 return &I;
308 } else {
309 // If we are replacing the instruction with itself, this must be in a
310 // segment of unreachable code, so just clobber the instruction.
Owen Andersonb5618da2009-07-03 00:17:18 +0000311 I.replaceAllUsesWith(Context->getUndef(I.getType()));
Chris Lattner8953b902004-04-05 02:10:19 +0000312 return &I;
313 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000314 }
Chris Lattner51ea1272004-02-28 05:22:00 +0000315
316 // EraseInstFromFunction - When dealing with an instruction that has side
317 // effects or produces a void value, we can't rely on DCE to delete the
318 // instruction. Instead, visit methods should return the value returned by
319 // this function.
320 Instruction *EraseInstFromFunction(Instruction &I) {
321 assert(I.use_empty() && "Cannot erase instruction that is used!");
322 AddUsesToWorkList(I);
Chris Lattnerb15e2b12007-03-02 21:28:56 +0000323 RemoveFromWorkList(&I);
Chris Lattner95307542004-11-18 21:41:39 +0000324 I.eraseFromParent();
Chris Lattner51ea1272004-02-28 05:22:00 +0000325 return 0; // Don't do anything with FI
326 }
Chris Lattner965c7692008-06-02 01:18:21 +0000327
328 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
329 APInt &KnownOne, unsigned Depth = 0) const {
330 return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
331 }
332
333 bool MaskedValueIsZero(Value *V, const APInt &Mask,
334 unsigned Depth = 0) const {
335 return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
336 }
337 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
338 return llvm::ComputeNumSignBits(Op, TD, Depth);
339 }
Chris Lattner51ea1272004-02-28 05:22:00 +0000340
Chris Lattner3ac7c262003-08-13 20:16:26 +0000341 private:
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000342
Reid Spencer266e42b2006-12-23 06:05:41 +0000343 /// SimplifyCommutative - This performs a few simplifications for
344 /// commutative operators.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000345 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerba1cb382003-09-19 17:17:26 +0000346
Reid Spencer266e42b2006-12-23 06:05:41 +0000347 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
348 /// most-complex to least-complex order.
349 bool SimplifyCompare(CmpInst &I);
350
Chris Lattner83c6a142009-01-31 08:15:18 +0000351 /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
352 /// based on the demanded bits.
353 Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
354 APInt& KnownZero, APInt& KnownOne,
355 unsigned Depth);
356 bool SimplifyDemandedBits(Use &U, APInt DemandedMask,
Reid Spencer1791f232007-03-12 17:25:59 +0000357 APInt& KnownZero, APInt& KnownOne,
Chris Lattner83c6a142009-01-31 08:15:18 +0000358 unsigned Depth=0);
359
360 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
361 /// SimplifyDemandedBits knows about. See if the instruction has any
362 /// properties that allow us to simplify its operands.
363 bool SimplifyDemandedInstructionBits(Instruction &Inst);
364
Evan Cheng8542caa2009-02-03 10:05:09 +0000365 Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
366 APInt& UndefElts, unsigned Depth = 0);
Chris Lattner2deeaea2006-10-05 06:55:50 +0000367
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000368 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
369 // PHI node as operand #0, see if we can fold the instruction into the PHI
370 // (which is only possible if all operands to the PHI are constants).
371 Instruction *FoldOpIntoPhi(Instruction &I);
372
Chris Lattner7515cab2004-11-14 19:13:23 +0000373 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
374 // operator and they all are only used by the PHI, PHI together their
375 // inputs, and do the operation once, to the result of the PHI.
376 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
Chris Lattnercadac0c2006-11-01 04:51:18 +0000377 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
Chris Lattner9d02a702008-12-01 02:34:36 +0000378 Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
379
Chris Lattnercadac0c2006-11-01 04:51:18 +0000380
Zhou Sheng75b871f2007-01-11 12:24:14 +0000381 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
382 ConstantInt *AndRHS, BinaryOperator &TheAnd);
Chris Lattneraf517572005-09-18 04:24:45 +0000383
Zhou Sheng75b871f2007-01-11 12:24:14 +0000384 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
Chris Lattneraf517572005-09-18 04:24:45 +0000385 bool isSub, Instruction &I);
Chris Lattner6862fbd2004-09-29 17:40:11 +0000386 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencer266e42b2006-12-23 06:05:41 +0000387 bool isSigned, bool Inside, Instruction &IB);
Chris Lattner1db224d2007-04-27 17:44:50 +0000388 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
Chris Lattnerc482a9e2006-06-15 19:07:26 +0000389 Instruction *MatchBSwap(BinaryOperator &I);
Chris Lattner14a251b2007-04-15 00:07:55 +0000390 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattner57974c82008-01-13 23:50:23 +0000391 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
Chris Lattner2dc44262008-04-30 06:39:11 +0000392 Instruction *SimplifyMemSet(MemSetInst *MI);
Chris Lattner57974c82008-01-13 23:50:23 +0000393
Chris Lattnerc482a9e2006-06-15 19:07:26 +0000394
Reid Spencer74a528b2006-12-13 18:21:21 +0000395 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Dan Gohman99b7b3f2008-04-10 18:43:06 +0000396
Dan Gohman7ccc52f2009-06-15 22:12:54 +0000397 bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Chengbeac6f82009-01-16 02:11:43 +0000398 unsigned CastOpc, int &NumCastsRemoved);
Dan Gohman99b7b3f2008-04-10 18:43:06 +0000399 unsigned GetOrEnforceKnownAlignment(Value *V,
400 unsigned PrefAlign = 0);
Matthijs Kooijmanb2fc72b2008-06-11 14:05:05 +0000401
Chris Lattner260ab202002-04-18 17:39:14 +0000402 };
403}
404
Dan Gohmand78c4002008-05-13 00:00:25 +0000405char InstCombiner::ID = 0;
406static RegisterPass<InstCombiner>
407X("instcombine", "Combine redundant instructions");
408
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000409// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattner81a7a232004-10-16 18:11:37 +0000410// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Owen Anderson53a52212009-07-13 04:09:18 +0000411static unsigned getComplexity(LLVMContext *Context, Value *V) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000412 if (isa<Instruction>(V)) {
Owen Anderson53a52212009-07-13 04:09:18 +0000413 if (BinaryOperator::isNeg(*Context, V) ||
414 BinaryOperator::isFNeg(*Context, V) ||
Dan Gohmana5b96452009-06-04 22:49:04 +0000415 BinaryOperator::isNot(V))
Chris Lattner81a7a232004-10-16 18:11:37 +0000416 return 3;
417 return 4;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000418 }
Chris Lattner81a7a232004-10-16 18:11:37 +0000419 if (isa<Argument>(V)) return 3;
420 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000421}
Chris Lattner260ab202002-04-18 17:39:14 +0000422
Chris Lattner7fb29e12003-03-11 00:12:48 +0000423// isOnlyUse - Return true if this instruction will be deleted if we stop using
424// it.
425static bool isOnlyUse(Value *V) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000426 return V->hasOneUse() || isa<Constant>(V);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000427}
428
Chris Lattnere79e8542004-02-23 06:38:22 +0000429// getPromotedType - Return the specified type promoted as it would be to pass
430// though a va_arg area...
431static const Type *getPromotedType(const Type *Ty) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000432 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
433 if (ITy->getBitWidth() < 32)
434 return Type::Int32Ty;
Chris Lattnerf79577d2007-05-23 01:17:04 +0000435 }
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000436 return Ty;
Chris Lattnere79e8542004-02-23 06:38:22 +0000437}
438
Matthijs Kooijmanf7d3cb52008-10-13 15:17:01 +0000439/// getBitCastOperand - If the specified operand is a CastInst, a constant
440/// expression bitcast, or a GetElementPtrInst with all zero indices, return the
441/// operand value, otherwise return null.
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000442static Value *getBitCastOperand(Value *V) {
443 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
Matthijs Kooijmanf7d3cb52008-10-13 15:17:01 +0000444 // BitCastInst?
Chris Lattner567b81f2005-09-13 00:40:14 +0000445 return I->getOperand(0);
Matthijs Kooijmanf7d3cb52008-10-13 15:17:01 +0000446 else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(V)) {
447 // GetElementPtrInst?
448 if (GEP->hasAllZeroIndices())
449 return GEP->getOperand(0);
450 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000451 if (CE->getOpcode() == Instruction::BitCast)
Matthijs Kooijmanf7d3cb52008-10-13 15:17:01 +0000452 // BitCast ConstantExp?
Chris Lattner567b81f2005-09-13 00:40:14 +0000453 return CE->getOperand(0);
Matthijs Kooijmanf7d3cb52008-10-13 15:17:01 +0000454 else if (CE->getOpcode() == Instruction::GetElementPtr) {
455 // GetElementPtr ConstantExp?
456 for (User::op_iterator I = CE->op_begin() + 1, E = CE->op_end();
457 I != E; ++I) {
458 ConstantInt *CI = dyn_cast<ConstantInt>(I);
459 if (!CI || !CI->isZero())
460 // Any non-zero indices? Not cast-like.
461 return 0;
462 }
463 // All-zero indices? This is just like casting.
464 return CE->getOperand(0);
465 }
466 }
Chris Lattner567b81f2005-09-13 00:40:14 +0000467 return 0;
468}
469
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000470/// This function is a wrapper around CastInst::isEliminableCastPair. It
471/// simply extracts arguments and returns what that function returns.
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000472static Instruction::CastOps
473isEliminableCastPair(
474 const CastInst *CI, ///< The first cast instruction
475 unsigned opcode, ///< The opcode of the second cast instruction
476 const Type *DstTy, ///< The target type for the second cast instruction
477 TargetData *TD ///< The target data for pointer size
478) {
479
480 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
481 const Type *MidTy = CI->getType(); // B from above
Chris Lattner1d441ad2006-05-06 09:00:16 +0000482
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000483 // Get the opcodes of the two Cast instructions
484 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
485 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner1d441ad2006-05-06 09:00:16 +0000486
Chris Lattner306813c2009-03-24 18:35:40 +0000487 unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
488 DstTy, TD->getIntPtrType());
489
490 // We don't want to form an inttoptr or ptrtoint that converts to an integer
491 // type that differs from the pointer size.
492 if ((Res == Instruction::IntToPtr && SrcTy != TD->getIntPtrType()) ||
493 (Res == Instruction::PtrToInt && DstTy != TD->getIntPtrType()))
494 Res = 0;
495
496 return Instruction::CastOps(Res);
Chris Lattner1d441ad2006-05-06 09:00:16 +0000497}
498
499/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
500/// in any code being generated. It does not require codegen if V is simple
501/// enough or if the cast can be folded into other casts.
Reid Spencer266e42b2006-12-23 06:05:41 +0000502static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
503 const Type *Ty, TargetData *TD) {
Chris Lattner1d441ad2006-05-06 09:00:16 +0000504 if (V->getType() == Ty || isa<Constant>(V)) return false;
505
Chris Lattner99155be2006-05-25 23:24:33 +0000506 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner1d441ad2006-05-06 09:00:16 +0000507 if (const CastInst *CI = dyn_cast<CastInst>(V))
Reid Spencer266e42b2006-12-23 06:05:41 +0000508 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner1d441ad2006-05-06 09:00:16 +0000509 return false;
510 return true;
511}
512
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000513// SimplifyCommutative - This performs a few simplifications for commutative
514// operators:
Chris Lattner260ab202002-04-18 17:39:14 +0000515//
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000516// 1. Order operands such that they are listed from right (least complex) to
517// left (most complex). This puts constants before unary operators before
518// binary operators.
519//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000520// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
521// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000522//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000523bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000524 bool Changed = false;
Owen Anderson53a52212009-07-13 04:09:18 +0000525 if (getComplexity(Context, I.getOperand(0)) <
526 getComplexity(Context, I.getOperand(1)))
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000527 Changed = !I.swapOperands();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000528
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000529 if (!I.isAssociative()) return Changed;
530 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattner7fb29e12003-03-11 00:12:48 +0000531 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
532 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
533 if (isa<Constant>(I.getOperand(1))) {
Owen Andersonb5618da2009-07-03 00:17:18 +0000534 Constant *Folded = Context->getConstantExpr(I.getOpcode(),
Chris Lattner34428442003-05-27 16:40:51 +0000535 cast<Constant>(I.getOperand(1)),
536 cast<Constant>(Op->getOperand(1)));
Chris Lattner7fb29e12003-03-11 00:12:48 +0000537 I.setOperand(0, Op->getOperand(0));
538 I.setOperand(1, Folded);
539 return true;
540 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
541 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
542 isOnlyUse(Op) && isOnlyUse(Op1)) {
543 Constant *C1 = cast<Constant>(Op->getOperand(1));
544 Constant *C2 = cast<Constant>(Op1->getOperand(1));
545
546 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Owen Andersonb5618da2009-07-03 00:17:18 +0000547 Constant *Folded = Context->getConstantExpr(I.getOpcode(), C1, C2);
Gabor Greife1f6e4b2008-05-16 19:29:10 +0000548 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Chris Lattner7fb29e12003-03-11 00:12:48 +0000549 Op1->getOperand(0),
550 Op1->getName(), &I);
Chris Lattnerb15e2b12007-03-02 21:28:56 +0000551 AddToWorkList(New);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000552 I.setOperand(0, New);
553 I.setOperand(1, Folded);
554 return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000555 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000556 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000557 return Changed;
Chris Lattner260ab202002-04-18 17:39:14 +0000558}
Chris Lattnerca081252001-12-14 16:52:21 +0000559
Reid Spencer266e42b2006-12-23 06:05:41 +0000560/// SimplifyCompare - For a CmpInst this function just orders the operands
561/// so that theyare listed from right (least complex) to left (most complex).
562/// This puts constants before unary operators before binary operators.
563bool InstCombiner::SimplifyCompare(CmpInst &I) {
Owen Anderson53a52212009-07-13 04:09:18 +0000564 if (getComplexity(Context, I.getOperand(0)) >=
565 getComplexity(Context, I.getOperand(1)))
Reid Spencer266e42b2006-12-23 06:05:41 +0000566 return false;
567 I.swapOperands();
568 // Compare instructions are not associative so there's nothing else we can do.
569 return true;
570}
571
Chris Lattnerbb74e222003-03-10 23:06:50 +0000572// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
573// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattner9fa53de2002-05-06 16:49:18 +0000574//
Owen Anderson38264b12009-07-06 23:00:19 +0000575static inline Value *dyn_castNegVal(Value *V, LLVMContext *Context) {
Owen Anderson53a52212009-07-13 04:09:18 +0000576 if (BinaryOperator::isNeg(*Context, V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000577 return BinaryOperator::getNegArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000578
Chris Lattner9ad0d552004-12-14 20:08:06 +0000579 // Constants can be considered to be negated values if they can be folded.
580 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Owen Andersonb5618da2009-07-03 00:17:18 +0000581 return Context->getConstantExprNeg(C);
Nick Lewycky3bf55122008-05-23 04:54:45 +0000582
583 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
584 if (C->getType()->getElementType()->isInteger())
Owen Andersonb5618da2009-07-03 00:17:18 +0000585 return Context->getConstantExprNeg(C);
Nick Lewycky3bf55122008-05-23 04:54:45 +0000586
Chris Lattnerbb74e222003-03-10 23:06:50 +0000587 return 0;
Chris Lattner9fa53de2002-05-06 16:49:18 +0000588}
589
Dan Gohmana5b96452009-06-04 22:49:04 +0000590// dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
591// instruction if the LHS is a constant negative zero (which is the 'negate'
592// form).
593//
Owen Anderson38264b12009-07-06 23:00:19 +0000594static inline Value *dyn_castFNegVal(Value *V, LLVMContext *Context) {
Owen Anderson53a52212009-07-13 04:09:18 +0000595 if (BinaryOperator::isFNeg(*Context, V))
Dan Gohmana5b96452009-06-04 22:49:04 +0000596 return BinaryOperator::getFNegArgument(V);
597
598 // Constants can be considered to be negated values if they can be folded.
599 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
Owen Andersonb5618da2009-07-03 00:17:18 +0000600 return Context->getConstantExprFNeg(C);
Dan Gohmana5b96452009-06-04 22:49:04 +0000601
602 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
603 if (C->getType()->getElementType()->isFloatingPoint())
Owen Andersonb5618da2009-07-03 00:17:18 +0000604 return Context->getConstantExprFNeg(C);
Dan Gohmana5b96452009-06-04 22:49:04 +0000605
606 return 0;
607}
608
Owen Anderson38264b12009-07-06 23:00:19 +0000609static inline Value *dyn_castNotVal(Value *V, LLVMContext *Context) {
Chris Lattnerbb74e222003-03-10 23:06:50 +0000610 if (BinaryOperator::isNot(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000611 return BinaryOperator::getNotArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000612
613 // Constants can be considered to be not'ed values...
Zhou Sheng75b871f2007-01-11 12:24:14 +0000614 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Owen Andersonb5618da2009-07-03 00:17:18 +0000615 return Context->getConstantInt(~C->getValue());
Chris Lattnerbb74e222003-03-10 23:06:50 +0000616 return 0;
617}
618
Chris Lattner7fb29e12003-03-11 00:12:48 +0000619// dyn_castFoldableMul - If this value is a multiply that can be folded into
620// other computations (because it has a constant operand), return the
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000621// non-constant operand of the multiply, and set CST to point to the multiplier.
622// Otherwise, return null.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000623//
Owen Andersonb5618da2009-07-03 00:17:18 +0000624static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST,
Owen Anderson38264b12009-07-06 23:00:19 +0000625 LLVMContext *Context) {
Chris Lattner03c49532007-01-15 02:27:26 +0000626 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000627 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattner7fb29e12003-03-11 00:12:48 +0000628 if (I->getOpcode() == Instruction::Mul)
Chris Lattner970136362004-11-15 05:54:07 +0000629 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattner7fb29e12003-03-11 00:12:48 +0000630 return I->getOperand(0);
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000631 if (I->getOpcode() == Instruction::Shl)
Chris Lattner970136362004-11-15 05:54:07 +0000632 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000633 // The multiplier is really 1 << CST.
Zhou Sheng4961cf12007-03-29 01:57:21 +0000634 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Zhou Shengb25806f2007-03-30 09:29:48 +0000635 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Owen Andersonb5618da2009-07-03 00:17:18 +0000636 CST = Context->getConstantInt(APInt(BitWidth, 1).shl(CSTVal));
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000637 return I->getOperand(0);
638 }
639 }
Chris Lattner7fb29e12003-03-11 00:12:48 +0000640 return 0;
Chris Lattner3082c5a2003-02-18 19:28:33 +0000641}
Chris Lattner31ae8632002-08-14 17:51:49 +0000642
Chris Lattner0798af32005-01-13 20:14:25 +0000643/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
644/// expression, return it.
645static User *dyn_castGetElementPtr(Value *V) {
646 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
647 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
648 if (CE->getOpcode() == Instruction::GetElementPtr)
649 return cast<User>(V);
650 return false;
651}
652
Dan Gohman99b7b3f2008-04-10 18:43:06 +0000653/// getOpcode - If this is an Instruction or a ConstantExpr, return the
654/// opcode value. Otherwise return UserOp1.
Dan Gohman86ff8532008-05-29 19:53:46 +0000655static unsigned getOpcode(const Value *V) {
656 if (const Instruction *I = dyn_cast<Instruction>(V))
Dan Gohman99b7b3f2008-04-10 18:43:06 +0000657 return I->getOpcode();
Dan Gohman86ff8532008-05-29 19:53:46 +0000658 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Dan Gohman99b7b3f2008-04-10 18:43:06 +0000659 return CE->getOpcode();
660 // Use UserOp1 to mean there's no opcode.
661 return Instruction::UserOp1;
662}
663
Reid Spencer80263aa2007-03-25 05:33:51 +0000664/// AddOne - Add one to a ConstantInt
Owen Anderson38264b12009-07-06 23:00:19 +0000665static Constant *AddOne(Constant *C, LLVMContext *Context) {
Owen Andersonb5618da2009-07-03 00:17:18 +0000666 return Context->getConstantExprAdd(C,
667 Context->getConstantInt(C->getType(), 1));
Chris Lattner623826c2004-09-28 21:48:02 +0000668}
Reid Spencer80263aa2007-03-25 05:33:51 +0000669/// SubOne - Subtract one from a ConstantInt
Owen Anderson38264b12009-07-06 23:00:19 +0000670static Constant *SubOne(ConstantInt *C, LLVMContext *Context) {
Owen Andersonb5618da2009-07-03 00:17:18 +0000671 return Context->getConstantExprSub(C,
672 Context->getConstantInt(C->getType(), 1));
Chris Lattner623826c2004-09-28 21:48:02 +0000673}
Nick Lewyckyfefd0202008-02-18 22:48:05 +0000674/// MultiplyOverflows - True if the multiply can not be expressed in an int
675/// this size.
Owen Andersonb5618da2009-07-03 00:17:18 +0000676static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign,
Owen Anderson38264b12009-07-06 23:00:19 +0000677 LLVMContext *Context) {
Nick Lewyckyfefd0202008-02-18 22:48:05 +0000678 uint32_t W = C1->getBitWidth();
679 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
680 if (sign) {
681 LHSExt.sext(W * 2);
682 RHSExt.sext(W * 2);
683 } else {
684 LHSExt.zext(W * 2);
685 RHSExt.zext(W * 2);
686 }
687
688 APInt MulExt = LHSExt * RHSExt;
689
690 if (sign) {
691 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
692 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
693 return MulExt.slt(Min) || MulExt.sgt(Max);
694 } else
695 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
696}
Chris Lattner623826c2004-09-28 21:48:02 +0000697
Reid Spencerbb5741f2007-03-08 01:52:58 +0000698
Chris Lattner0157e7f2006-02-11 09:31:47 +0000699/// ShrinkDemandedConstant - Check to see if the specified operand of the
700/// specified instruction is a constant integer. If so, check to see if there
701/// are any bits set in the constant that are not demanded. If so, shrink the
702/// constant and return true.
703static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Owen Anderson38264b12009-07-06 23:00:19 +0000704 APInt Demanded, LLVMContext *Context) {
Reid Spencerd9281782007-03-12 17:15:10 +0000705 assert(I && "No instruction?");
706 assert(OpNo < I->getNumOperands() && "Operand index too large");
707
708 // If the operand is not a constant integer, nothing to do.
709 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
710 if (!OpC) return false;
711
712 // If there are no bits set that aren't demanded, nothing to do.
713 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
714 if ((~Demanded & OpC->getValue()) == 0)
715 return false;
716
717 // This instruction is producing bits that are not demanded. Shrink the RHS.
718 Demanded &= OpC->getValue();
Owen Andersonb5618da2009-07-03 00:17:18 +0000719 I->setOperand(OpNo, Context->getConstantInt(Demanded));
Reid Spencerd9281782007-03-12 17:15:10 +0000720 return true;
721}
722
Chris Lattneree0f2802006-02-12 02:07:56 +0000723// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
724// set of known zero and one bits, compute the maximum and minimum values that
725// could have the specified known zero and known one bits, returning them in
726// min/max.
Dan Gohman5638e0d2009-04-25 17:12:48 +0000727static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
Reid Spencerc3e3b8a2007-03-22 20:36:03 +0000728 const APInt& KnownOne,
729 APInt& Min, APInt& Max) {
Dan Gohman5638e0d2009-04-25 17:12:48 +0000730 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
731 KnownZero.getBitWidth() == Min.getBitWidth() &&
732 KnownZero.getBitWidth() == Max.getBitWidth() &&
733 "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencercd99fbd2007-03-25 04:26:16 +0000734 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattneree0f2802006-02-12 02:07:56 +0000735
Chris Lattneree0f2802006-02-12 02:07:56 +0000736 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
737 // bit if it is unknown.
738 Min = KnownOne;
739 Max = KnownOne|UnknownBits;
740
Dan Gohman5638e0d2009-04-25 17:12:48 +0000741 if (UnknownBits.isNegative()) { // Sign bit is unknown
742 Min.set(Min.getBitWidth()-1);
743 Max.clear(Max.getBitWidth()-1);
Chris Lattneree0f2802006-02-12 02:07:56 +0000744 }
Chris Lattneree0f2802006-02-12 02:07:56 +0000745}
746
747// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
748// a set of known zero and one bits, compute the maximum and minimum values that
749// could have the specified known zero and known one bits, returning them in
750// min/max.
Dan Gohman5638e0d2009-04-25 17:12:48 +0000751static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
Chris Lattnerf0da7972007-08-05 08:47:58 +0000752 const APInt &KnownOne,
753 APInt &Min, APInt &Max) {
Dan Gohman5638e0d2009-04-25 17:12:48 +0000754 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
755 KnownZero.getBitWidth() == Min.getBitWidth() &&
756 KnownZero.getBitWidth() == Max.getBitWidth() &&
Reid Spencerc3e3b8a2007-03-22 20:36:03 +0000757 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencercd99fbd2007-03-25 04:26:16 +0000758 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattneree0f2802006-02-12 02:07:56 +0000759
760 // The minimum value is when the unknown bits are all zeros.
761 Min = KnownOne;
762 // The maximum value is when the unknown bits are all ones.
763 Max = KnownOne|UnknownBits;
764}
Chris Lattner0157e7f2006-02-11 09:31:47 +0000765
Chris Lattner83c6a142009-01-31 08:15:18 +0000766/// SimplifyDemandedInstructionBits - Inst is an integer instruction that
767/// SimplifyDemandedBits knows about. See if the instruction has any
768/// properties that allow us to simplify its operands.
769bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +0000770 unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
Chris Lattner83c6a142009-01-31 08:15:18 +0000771 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
772 APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
773
774 Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask,
775 KnownZero, KnownOne, 0);
776 if (V == 0) return false;
777 if (V == &Inst) return true;
778 ReplaceInstUsesWith(Inst, V);
779 return true;
780}
781
782/// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
783/// specified instruction operand if possible, updating it in place. It returns
784/// true if it made any change and false otherwise.
785bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask,
786 APInt &KnownZero, APInt &KnownOne,
787 unsigned Depth) {
788 Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
789 KnownZero, KnownOne, Depth);
790 if (NewVal == 0) return false;
791 U.set(NewVal);
792 return true;
793}
794
795
796/// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
797/// value based on the demanded bits. When this function is called, it is known
Reid Spencer1791f232007-03-12 17:25:59 +0000798/// that only the bits set in DemandedMask of the result of V are ever used
799/// downstream. Consequently, depending on the mask and V, it may be possible
800/// to replace V with a constant or one of its operands. In such cases, this
801/// function does the replacement and returns true. In all other cases, it
802/// returns false after analyzing the expression and setting KnownOne and known
Chris Lattner83c6a142009-01-31 08:15:18 +0000803/// to be one in the expression. KnownZero contains all the bits that are known
Reid Spencer1791f232007-03-12 17:25:59 +0000804/// to be zero in the expression. These are provided to potentially allow the
805/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
806/// the expression. KnownOne and KnownZero always follow the invariant that
807/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
808/// the bits in KnownOne and KnownZero may only be accurate for those bits set
809/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
810/// and KnownOne must all be the same.
Chris Lattner83c6a142009-01-31 08:15:18 +0000811///
812/// This returns null if it did not change anything and it permits no
813/// simplification. This returns V itself if it did some simplification of V's
814/// operands based on the information about what bits are demanded. This returns
815/// some other non-null value if it found out that V is equal to another value
816/// in the context where the specified bits are demanded, but not for all users.
817Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
818 APInt &KnownZero, APInt &KnownOne,
819 unsigned Depth) {
Reid Spencer1791f232007-03-12 17:25:59 +0000820 assert(V != 0 && "Null pointer of Value???");
821 assert(Depth <= 6 && "Limit Search Depth");
822 uint32_t BitWidth = DemandedMask.getBitWidth();
Dan Gohman5638e0d2009-04-25 17:12:48 +0000823 const Type *VTy = V->getType();
824 assert((TD || !isa<PointerType>(VTy)) &&
825 "SimplifyDemandedBits needs to know bit widths!");
Dan Gohman7ccc52f2009-06-15 22:12:54 +0000826 assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
827 (!VTy->isIntOrIntVector() ||
828 VTy->getScalarSizeInBits() == BitWidth) &&
Dan Gohman5638e0d2009-04-25 17:12:48 +0000829 KnownZero.getBitWidth() == BitWidth &&
Reid Spencer1791f232007-03-12 17:25:59 +0000830 KnownOne.getBitWidth() == BitWidth &&
Dan Gohman7ccc52f2009-06-15 22:12:54 +0000831 "Value *V, DemandedMask, KnownZero and KnownOne "
832 "must have same BitWidth");
Reid Spencer1791f232007-03-12 17:25:59 +0000833 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
834 // We know all of the bits for a constant!
835 KnownOne = CI->getValue() & DemandedMask;
836 KnownZero = ~KnownOne & DemandedMask;
Chris Lattner83c6a142009-01-31 08:15:18 +0000837 return 0;
Reid Spencer1791f232007-03-12 17:25:59 +0000838 }
Dan Gohman5638e0d2009-04-25 17:12:48 +0000839 if (isa<ConstantPointerNull>(V)) {
840 // We know all of the bits for a constant!
841 KnownOne.clear();
842 KnownZero = DemandedMask;
843 return 0;
844 }
845
Chris Lattner585cfb22009-01-31 07:26:06 +0000846 KnownZero.clear();
Zhou Shengb9128442007-03-14 03:21:24 +0000847 KnownOne.clear();
Chris Lattner83c6a142009-01-31 08:15:18 +0000848 if (DemandedMask == 0) { // Not demanding any bits from V.
849 if (isa<UndefValue>(V))
850 return 0;
Owen Andersonb5618da2009-07-03 00:17:18 +0000851 return Context->getUndef(VTy);
Reid Spencer1791f232007-03-12 17:25:59 +0000852 }
853
Chris Lattner3e2cb662009-01-31 08:24:16 +0000854 if (Depth == 6) // Limit search depth.
855 return 0;
856
Chris Lattner76a63ed2009-01-31 08:40:03 +0000857 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
858 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
859
Dan Gohman5638e0d2009-04-25 17:12:48 +0000860 Instruction *I = dyn_cast<Instruction>(V);
861 if (!I) {
862 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
863 return 0; // Only analyze instructions.
864 }
865
Chris Lattner3e2cb662009-01-31 08:24:16 +0000866 // If there are multiple uses of this value and we aren't at the root, then
867 // we can't do any simplifications of the operands, because DemandedMask
868 // only reflects the bits demanded by *one* of the users.
869 if (Depth != 0 && !I->hasOneUse()) {
Chris Lattner76a63ed2009-01-31 08:40:03 +0000870 // Despite the fact that we can't simplify this instruction in all User's
871 // context, we can at least compute the knownzero/knownone bits, and we can
872 // do simplifications that apply to *just* the one user if we know that
873 // this instruction has a simpler value in that context.
874 if (I->getOpcode() == Instruction::And) {
875 // If either the LHS or the RHS are Zero, the result is zero.
876 ComputeMaskedBits(I->getOperand(1), DemandedMask,
877 RHSKnownZero, RHSKnownOne, Depth+1);
878 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
879 LHSKnownZero, LHSKnownOne, Depth+1);
880
881 // If all of the demanded bits are known 1 on one side, return the other.
882 // These bits cannot contribute to the result of the 'and' in this
883 // context.
884 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
885 (DemandedMask & ~LHSKnownZero))
886 return I->getOperand(0);
887 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
888 (DemandedMask & ~RHSKnownZero))
889 return I->getOperand(1);
890
891 // If all of the demanded bits in the inputs are known zeros, return zero.
892 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersonb5618da2009-07-03 00:17:18 +0000893 return Context->getNullValue(VTy);
Chris Lattner76a63ed2009-01-31 08:40:03 +0000894
895 } else if (I->getOpcode() == Instruction::Or) {
896 // We can simplify (X|Y) -> X or Y in the user's context if we know that
897 // only bits from X or Y are demanded.
898
899 // If either the LHS or the RHS are One, the result is One.
900 ComputeMaskedBits(I->getOperand(1), DemandedMask,
901 RHSKnownZero, RHSKnownOne, Depth+1);
902 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
903 LHSKnownZero, LHSKnownOne, Depth+1);
904
905 // If all of the demanded bits are known zero on one side, return the
906 // other. These bits cannot contribute to the result of the 'or' in this
907 // context.
908 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
909 (DemandedMask & ~LHSKnownOne))
910 return I->getOperand(0);
911 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
912 (DemandedMask & ~RHSKnownOne))
913 return I->getOperand(1);
914
915 // If all of the potentially set bits on one side are known to be set on
916 // the other side, just use the 'other' side.
917 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
918 (DemandedMask & (~RHSKnownZero)))
919 return I->getOperand(0);
920 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
921 (DemandedMask & (~LHSKnownZero)))
922 return I->getOperand(1);
923 }
924
Chris Lattner3e2cb662009-01-31 08:24:16 +0000925 // Compute the KnownZero/KnownOne bits to simplify things downstream.
926 ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
927 return 0;
928 }
929
930 // If this is the root being simplified, allow it to have multiple uses,
931 // just set the DemandedMask to all bits so that we can try to simplify the
932 // operands. This allows visitTruncInst (for example) to simplify the
933 // operand of a trunc without duplicating all the logic below.
934 if (Depth == 0 && !V->hasOneUse())
935 DemandedMask = APInt::getAllOnesValue(BitWidth);
936
Reid Spencer1791f232007-03-12 17:25:59 +0000937 switch (I->getOpcode()) {
Dan Gohman72ec3f42008-04-28 17:02:21 +0000938 default:
Chris Lattner83c6a142009-01-31 08:15:18 +0000939 ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Dan Gohman72ec3f42008-04-28 17:02:21 +0000940 break;
Reid Spencer1791f232007-03-12 17:25:59 +0000941 case Instruction::And:
942 // If either the LHS or the RHS are Zero, the result is zero.
Chris Lattner83c6a142009-01-31 08:15:18 +0000943 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
944 RHSKnownZero, RHSKnownOne, Depth+1) ||
945 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
Reid Spencer1791f232007-03-12 17:25:59 +0000946 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner83c6a142009-01-31 08:15:18 +0000947 return I;
948 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
949 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer1791f232007-03-12 17:25:59 +0000950
951 // If all of the demanded bits are known 1 on one side, return the other.
952 // These bits cannot contribute to the result of the 'and'.
953 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
954 (DemandedMask & ~LHSKnownZero))
Chris Lattner83c6a142009-01-31 08:15:18 +0000955 return I->getOperand(0);
Reid Spencer1791f232007-03-12 17:25:59 +0000956 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
957 (DemandedMask & ~RHSKnownZero))
Chris Lattner83c6a142009-01-31 08:15:18 +0000958 return I->getOperand(1);
Reid Spencer1791f232007-03-12 17:25:59 +0000959
960 // If all of the demanded bits in the inputs are known zeros, return zero.
961 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersonb5618da2009-07-03 00:17:18 +0000962 return Context->getNullValue(VTy);
Reid Spencer1791f232007-03-12 17:25:59 +0000963
964 // If the RHS is a constant, see if we can simplify it.
Owen Andersonb5618da2009-07-03 00:17:18 +0000965 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero, Context))
Chris Lattner83c6a142009-01-31 08:15:18 +0000966 return I;
Reid Spencer1791f232007-03-12 17:25:59 +0000967
968 // Output known-1 bits are only known if set in both the LHS & RHS.
969 RHSKnownOne &= LHSKnownOne;
970 // Output known-0 are known to be clear if zero in either the LHS | RHS.
971 RHSKnownZero |= LHSKnownZero;
972 break;
973 case Instruction::Or:
974 // If either the LHS or the RHS are One, the result is One.
Chris Lattner83c6a142009-01-31 08:15:18 +0000975 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
976 RHSKnownZero, RHSKnownOne, Depth+1) ||
977 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne,
Reid Spencer1791f232007-03-12 17:25:59 +0000978 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner83c6a142009-01-31 08:15:18 +0000979 return I;
980 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
981 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer1791f232007-03-12 17:25:59 +0000982
983 // If all of the demanded bits are known zero on one side, return the other.
984 // These bits cannot contribute to the result of the 'or'.
985 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
986 (DemandedMask & ~LHSKnownOne))
Chris Lattner83c6a142009-01-31 08:15:18 +0000987 return I->getOperand(0);
Reid Spencer1791f232007-03-12 17:25:59 +0000988 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
989 (DemandedMask & ~RHSKnownOne))
Chris Lattner83c6a142009-01-31 08:15:18 +0000990 return I->getOperand(1);
Reid Spencer1791f232007-03-12 17:25:59 +0000991
992 // If all of the potentially set bits on one side are known to be set on
993 // the other side, just use the 'other' side.
994 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
995 (DemandedMask & (~RHSKnownZero)))
Chris Lattner83c6a142009-01-31 08:15:18 +0000996 return I->getOperand(0);
Reid Spencer1791f232007-03-12 17:25:59 +0000997 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
998 (DemandedMask & (~LHSKnownZero)))
Chris Lattner83c6a142009-01-31 08:15:18 +0000999 return I->getOperand(1);
Reid Spencer1791f232007-03-12 17:25:59 +00001000
1001 // If the RHS is a constant, see if we can simplify it.
Owen Andersonb5618da2009-07-03 00:17:18 +00001002 if (ShrinkDemandedConstant(I, 1, DemandedMask, Context))
Chris Lattner83c6a142009-01-31 08:15:18 +00001003 return I;
Reid Spencer1791f232007-03-12 17:25:59 +00001004
1005 // Output known-0 bits are only known if clear in both the LHS & RHS.
1006 RHSKnownZero &= LHSKnownZero;
1007 // Output known-1 are known to be set if set in either the LHS | RHS.
1008 RHSKnownOne |= LHSKnownOne;
1009 break;
1010 case Instruction::Xor: {
Chris Lattner83c6a142009-01-31 08:15:18 +00001011 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1012 RHSKnownZero, RHSKnownOne, Depth+1) ||
1013 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer1791f232007-03-12 17:25:59 +00001014 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner83c6a142009-01-31 08:15:18 +00001015 return I;
1016 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1017 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer1791f232007-03-12 17:25:59 +00001018
1019 // If all of the demanded bits are known zero on one side, return the other.
1020 // These bits cannot contribute to the result of the 'xor'.
1021 if ((DemandedMask & RHSKnownZero) == DemandedMask)
Chris Lattner83c6a142009-01-31 08:15:18 +00001022 return I->getOperand(0);
Reid Spencer1791f232007-03-12 17:25:59 +00001023 if ((DemandedMask & LHSKnownZero) == DemandedMask)
Chris Lattner83c6a142009-01-31 08:15:18 +00001024 return I->getOperand(1);
Reid Spencer1791f232007-03-12 17:25:59 +00001025
1026 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1027 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1028 (RHSKnownOne & LHSKnownOne);
1029 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1030 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1031 (RHSKnownOne & LHSKnownZero);
1032
1033 // If all of the demanded bits are known to be zero on one side or the
1034 // other, turn this into an *inclusive* or.
1035 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1036 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1037 Instruction *Or =
Gabor Greife1f6e4b2008-05-16 19:29:10 +00001038 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer1791f232007-03-12 17:25:59 +00001039 I->getName());
Chris Lattner83c6a142009-01-31 08:15:18 +00001040 return InsertNewInstBefore(Or, *I);
Reid Spencer1791f232007-03-12 17:25:59 +00001041 }
1042
1043 // If all of the demanded bits on one side are known, and all of the set
1044 // bits on that side are also known to be set on the other side, turn this
1045 // into an AND, as we know the bits will be cleared.
1046 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1047 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1048 // all known
1049 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
Owen Andersonb5618da2009-07-03 00:17:18 +00001050 Constant *AndC = Context->getConstantInt(~RHSKnownOne & DemandedMask);
Reid Spencer1791f232007-03-12 17:25:59 +00001051 Instruction *And =
Gabor Greife1f6e4b2008-05-16 19:29:10 +00001052 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
Chris Lattner83c6a142009-01-31 08:15:18 +00001053 return InsertNewInstBefore(And, *I);
Reid Spencer1791f232007-03-12 17:25:59 +00001054 }
1055 }
1056
1057 // If the RHS is a constant, see if we can simplify it.
1058 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
Owen Andersonb5618da2009-07-03 00:17:18 +00001059 if (ShrinkDemandedConstant(I, 1, DemandedMask, Context))
Chris Lattner83c6a142009-01-31 08:15:18 +00001060 return I;
Reid Spencer1791f232007-03-12 17:25:59 +00001061
1062 RHSKnownZero = KnownZeroOut;
1063 RHSKnownOne = KnownOneOut;
1064 break;
1065 }
1066 case Instruction::Select:
Chris Lattner83c6a142009-01-31 08:15:18 +00001067 if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1068 RHSKnownZero, RHSKnownOne, Depth+1) ||
1069 SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
Reid Spencer1791f232007-03-12 17:25:59 +00001070 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner83c6a142009-01-31 08:15:18 +00001071 return I;
1072 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1073 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer1791f232007-03-12 17:25:59 +00001074
1075 // If the operands are constants, see if we can simplify them.
Owen Andersonb5618da2009-07-03 00:17:18 +00001076 if (ShrinkDemandedConstant(I, 1, DemandedMask, Context) ||
1077 ShrinkDemandedConstant(I, 2, DemandedMask, Context))
Chris Lattner83c6a142009-01-31 08:15:18 +00001078 return I;
Reid Spencer1791f232007-03-12 17:25:59 +00001079
1080 // Only known if known in both the LHS and RHS.
1081 RHSKnownOne &= LHSKnownOne;
1082 RHSKnownZero &= LHSKnownZero;
1083 break;
1084 case Instruction::Trunc: {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001085 unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
Zhou Shenga4475572007-03-29 02:26:30 +00001086 DemandedMask.zext(truncBf);
1087 RHSKnownZero.zext(truncBf);
1088 RHSKnownOne.zext(truncBf);
Chris Lattner83c6a142009-01-31 08:15:18 +00001089 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Shenga4475572007-03-29 02:26:30 +00001090 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner83c6a142009-01-31 08:15:18 +00001091 return I;
Reid Spencer1791f232007-03-12 17:25:59 +00001092 DemandedMask.trunc(BitWidth);
1093 RHSKnownZero.trunc(BitWidth);
1094 RHSKnownOne.trunc(BitWidth);
Chris Lattner83c6a142009-01-31 08:15:18 +00001095 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer1791f232007-03-12 17:25:59 +00001096 break;
1097 }
1098 case Instruction::BitCast:
Dan Gohman83348f82009-07-01 21:38:46 +00001099 if (!I->getOperand(0)->getType()->isIntOrIntVector())
Chris Lattner83c6a142009-01-31 08:15:18 +00001100 return false; // vector->int or fp->int?
Dan Gohman83348f82009-07-01 21:38:46 +00001101
1102 if (const VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
1103 if (const VectorType *SrcVTy =
1104 dyn_cast<VectorType>(I->getOperand(0)->getType())) {
1105 if (DstVTy->getNumElements() != SrcVTy->getNumElements())
1106 // Don't touch a bitcast between vectors of different element counts.
1107 return false;
1108 } else
1109 // Don't touch a scalar-to-vector bitcast.
1110 return false;
1111 } else if (isa<VectorType>(I->getOperand(0)->getType()))
1112 // Don't touch a vector-to-scalar bitcast.
1113 return false;
1114
Chris Lattner83c6a142009-01-31 08:15:18 +00001115 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer1791f232007-03-12 17:25:59 +00001116 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner83c6a142009-01-31 08:15:18 +00001117 return I;
1118 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer1791f232007-03-12 17:25:59 +00001119 break;
1120 case Instruction::ZExt: {
1121 // Compute the bits in the result that are not present in the input.
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001122 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Reid Spencer1791f232007-03-12 17:25:59 +00001123
Zhou Sheng444af492007-03-29 04:45:55 +00001124 DemandedMask.trunc(SrcBitWidth);
1125 RHSKnownZero.trunc(SrcBitWidth);
1126 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner83c6a142009-01-31 08:15:18 +00001127 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Shenga4475572007-03-29 02:26:30 +00001128 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner83c6a142009-01-31 08:15:18 +00001129 return I;
Reid Spencer1791f232007-03-12 17:25:59 +00001130 DemandedMask.zext(BitWidth);
1131 RHSKnownZero.zext(BitWidth);
1132 RHSKnownOne.zext(BitWidth);
Chris Lattner83c6a142009-01-31 08:15:18 +00001133 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer1791f232007-03-12 17:25:59 +00001134 // The top bits are known to be zero.
Zhou Shenga4475572007-03-29 02:26:30 +00001135 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer1791f232007-03-12 17:25:59 +00001136 break;
1137 }
1138 case Instruction::SExt: {
1139 // Compute the bits in the result that are not present in the input.
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001140 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Reid Spencer1791f232007-03-12 17:25:59 +00001141
Reid Spencer1791f232007-03-12 17:25:59 +00001142 APInt InputDemandedBits = DemandedMask &
Zhou Shenga4475572007-03-29 02:26:30 +00001143 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
Reid Spencer1791f232007-03-12 17:25:59 +00001144
Zhou Shenga4475572007-03-29 02:26:30 +00001145 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
Reid Spencer1791f232007-03-12 17:25:59 +00001146 // If any of the sign extended bits are demanded, we know that the sign
1147 // bit is demanded.
1148 if ((NewBits & DemandedMask) != 0)
Zhou Sheng9bc8ab12007-04-02 13:45:30 +00001149 InputDemandedBits.set(SrcBitWidth-1);
Reid Spencer1791f232007-03-12 17:25:59 +00001150
Zhou Sheng444af492007-03-29 04:45:55 +00001151 InputDemandedBits.trunc(SrcBitWidth);
1152 RHSKnownZero.trunc(SrcBitWidth);
1153 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner83c6a142009-01-31 08:15:18 +00001154 if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
Zhou Shenga4475572007-03-29 02:26:30 +00001155 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner83c6a142009-01-31 08:15:18 +00001156 return I;
Reid Spencer1791f232007-03-12 17:25:59 +00001157 InputDemandedBits.zext(BitWidth);
1158 RHSKnownZero.zext(BitWidth);
1159 RHSKnownOne.zext(BitWidth);
Chris Lattner83c6a142009-01-31 08:15:18 +00001160 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer1791f232007-03-12 17:25:59 +00001161
1162 // If the sign bit of the input is known set or clear, then we know the
1163 // top bits of the result.
1164
1165 // If the input sign bit is known zero, or if the NewBits are not demanded
1166 // convert this into a zero extension.
Chris Lattner83c6a142009-01-31 08:15:18 +00001167 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
Reid Spencer1791f232007-03-12 17:25:59 +00001168 // Convert to ZExt cast
Chris Lattner83c6a142009-01-31 08:15:18 +00001169 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1170 return InsertNewInstBefore(NewCast, *I);
Zhou Shenga4475572007-03-29 02:26:30 +00001171 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
Reid Spencer1791f232007-03-12 17:25:59 +00001172 RHSKnownOne |= NewBits;
Reid Spencer1791f232007-03-12 17:25:59 +00001173 }
1174 break;
1175 }
1176 case Instruction::Add: {
1177 // Figure out what the input bits are. If the top bits of the and result
1178 // are not demanded, then the add doesn't demand them from its input
1179 // either.
Chris Lattner83c6a142009-01-31 08:15:18 +00001180 unsigned NLZ = DemandedMask.countLeadingZeros();
Reid Spencer1791f232007-03-12 17:25:59 +00001181
1182 // If there is a constant on the RHS, there are a variety of xformations
1183 // we can do.
1184 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1185 // If null, this should be simplified elsewhere. Some of the xforms here
1186 // won't work if the RHS is zero.
1187 if (RHS->isZero())
1188 break;
1189
1190 // If the top bit of the output is demanded, demand everything from the
1191 // input. Otherwise, we demand all the input bits except NLZ top bits.
Zhou Shenga4475572007-03-29 02:26:30 +00001192 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
Reid Spencer1791f232007-03-12 17:25:59 +00001193
1194 // Find information about known zero/one bits in the input.
Chris Lattner83c6a142009-01-31 08:15:18 +00001195 if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits,
Reid Spencer1791f232007-03-12 17:25:59 +00001196 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner83c6a142009-01-31 08:15:18 +00001197 return I;
Reid Spencer1791f232007-03-12 17:25:59 +00001198
1199 // If the RHS of the add has bits set that can't affect the input, reduce
1200 // the constant.
Owen Andersonb5618da2009-07-03 00:17:18 +00001201 if (ShrinkDemandedConstant(I, 1, InDemandedBits, Context))
Chris Lattner83c6a142009-01-31 08:15:18 +00001202 return I;
Reid Spencer1791f232007-03-12 17:25:59 +00001203
1204 // Avoid excess work.
1205 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1206 break;
1207
1208 // Turn it into OR if input bits are zero.
1209 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1210 Instruction *Or =
Gabor Greife1f6e4b2008-05-16 19:29:10 +00001211 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer1791f232007-03-12 17:25:59 +00001212 I->getName());
Chris Lattner83c6a142009-01-31 08:15:18 +00001213 return InsertNewInstBefore(Or, *I);
Reid Spencer1791f232007-03-12 17:25:59 +00001214 }
1215
1216 // We can say something about the output known-zero and known-one bits,
1217 // depending on potential carries from the input constant and the
1218 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1219 // bits set and the RHS constant is 0x01001, then we know we have a known
1220 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1221
1222 // To compute this, we first compute the potential carry bits. These are
1223 // the bits which may be modified. I'm not aware of a better way to do
1224 // this scan.
Chris Lattner83c6a142009-01-31 08:15:18 +00001225 const APInt &RHSVal = RHS->getValue();
Zhou Sheng4f164022007-03-31 02:38:39 +00001226 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
Reid Spencer1791f232007-03-12 17:25:59 +00001227
1228 // Now that we know which bits have carries, compute the known-1/0 sets.
1229
1230 // Bits are known one if they are known zero in one operand and one in the
1231 // other, and there is no input carry.
1232 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1233 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1234
1235 // Bits are known zero if they are known zero in both operands and there
1236 // is no input carry.
1237 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1238 } else {
1239 // If the high-bits of this ADD are not demanded, then it does not demand
1240 // the high bits of its LHS or RHS.
Zhou Shenga4475572007-03-29 02:26:30 +00001241 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer1791f232007-03-12 17:25:59 +00001242 // Right fill the mask of bits for this ADD to demand the most
1243 // significant bit and all those below it.
Zhou Shenga4475572007-03-29 02:26:30 +00001244 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner83c6a142009-01-31 08:15:18 +00001245 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1246 LHSKnownZero, LHSKnownOne, Depth+1) ||
1247 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer1791f232007-03-12 17:25:59 +00001248 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner83c6a142009-01-31 08:15:18 +00001249 return I;
Reid Spencer1791f232007-03-12 17:25:59 +00001250 }
1251 }
1252 break;
1253 }
1254 case Instruction::Sub:
1255 // If the high-bits of this SUB are not demanded, then it does not demand
1256 // the high bits of its LHS or RHS.
Zhou Shenga4475572007-03-29 02:26:30 +00001257 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer1791f232007-03-12 17:25:59 +00001258 // Right fill the mask of bits for this SUB to demand the most
1259 // significant bit and all those below it.
Zhou Sheng56cda952007-04-02 08:20:41 +00001260 uint32_t NLZ = DemandedMask.countLeadingZeros();
Zhou Shenga4475572007-03-29 02:26:30 +00001261 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner83c6a142009-01-31 08:15:18 +00001262 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1263 LHSKnownZero, LHSKnownOne, Depth+1) ||
1264 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer1791f232007-03-12 17:25:59 +00001265 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner83c6a142009-01-31 08:15:18 +00001266 return I;
Reid Spencer1791f232007-03-12 17:25:59 +00001267 }
Dan Gohman72ec3f42008-04-28 17:02:21 +00001268 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1269 // the known zeros and ones.
1270 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Reid Spencer1791f232007-03-12 17:25:59 +00001271 break;
1272 case Instruction::Shl:
1273 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Shengb25806f2007-03-30 09:29:48 +00001274 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Zhou Shenga4475572007-03-29 02:26:30 +00001275 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
Chris Lattner83c6a142009-01-31 08:15:18 +00001276 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer1791f232007-03-12 17:25:59 +00001277 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner83c6a142009-01-31 08:15:18 +00001278 return I;
1279 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer1791f232007-03-12 17:25:59 +00001280 RHSKnownZero <<= ShiftAmt;
1281 RHSKnownOne <<= ShiftAmt;
1282 // low bits known zero.
Zhou Shengd8c645b2007-03-14 09:07:33 +00001283 if (ShiftAmt)
Zhou Sheng23f7a1c2007-03-28 15:02:20 +00001284 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
Reid Spencer1791f232007-03-12 17:25:59 +00001285 }
1286 break;
1287 case Instruction::LShr:
1288 // For a logical shift right
1289 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Shengb25806f2007-03-30 09:29:48 +00001290 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer1791f232007-03-12 17:25:59 +00001291
Reid Spencer1791f232007-03-12 17:25:59 +00001292 // Unsigned shift right.
Zhou Shenga4475572007-03-29 02:26:30 +00001293 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Chris Lattner83c6a142009-01-31 08:15:18 +00001294 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer1791f232007-03-12 17:25:59 +00001295 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner83c6a142009-01-31 08:15:18 +00001296 return I;
1297 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer1791f232007-03-12 17:25:59 +00001298 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1299 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
Zhou Shengd8c645b2007-03-14 09:07:33 +00001300 if (ShiftAmt) {
1301 // Compute the new bits that are at the top now.
Zhou Shenga4475572007-03-29 02:26:30 +00001302 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Zhou Shengd8c645b2007-03-14 09:07:33 +00001303 RHSKnownZero |= HighBits; // high bits known zero.
1304 }
Reid Spencer1791f232007-03-12 17:25:59 +00001305 }
1306 break;
1307 case Instruction::AShr:
1308 // If this is an arithmetic shift right and only the low-bit is set, we can
1309 // always convert this into a logical shr, even if the shift amount is
1310 // variable. The low bit of the shift cannot be an input sign bit unless
1311 // the shift amount is >= the size of the datatype, which is undefined.
1312 if (DemandedMask == 1) {
1313 // Perform the logical shift right.
Chris Lattner83c6a142009-01-31 08:15:18 +00001314 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer1791f232007-03-12 17:25:59 +00001315 I->getOperand(0), I->getOperand(1), I->getName());
Chris Lattner83c6a142009-01-31 08:15:18 +00001316 return InsertNewInstBefore(NewVal, *I);
Reid Spencer1791f232007-03-12 17:25:59 +00001317 }
Chris Lattnerd4fef8d2007-07-15 20:54:51 +00001318
1319 // If the sign bit is the only bit demanded by this ashr, then there is no
1320 // need to do it, the shift doesn't change the high bit.
1321 if (DemandedMask.isSignBit())
Chris Lattner83c6a142009-01-31 08:15:18 +00001322 return I->getOperand(0);
Reid Spencer1791f232007-03-12 17:25:59 +00001323
1324 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Shengfd28a332007-03-30 17:20:39 +00001325 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer1791f232007-03-12 17:25:59 +00001326
Reid Spencer1791f232007-03-12 17:25:59 +00001327 // Signed shift right.
Zhou Shenga4475572007-03-29 02:26:30 +00001328 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Lauro Ramos Venancio368e8872007-06-06 17:08:48 +00001329 // If any of the "high bits" are demanded, we should set the sign bit as
1330 // demanded.
1331 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1332 DemandedMaskIn.set(BitWidth-1);
Chris Lattner83c6a142009-01-31 08:15:18 +00001333 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer1791f232007-03-12 17:25:59 +00001334 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner83c6a142009-01-31 08:15:18 +00001335 return I;
1336 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer1791f232007-03-12 17:25:59 +00001337 // Compute the new bits that are at the top now.
Zhou Shenga4475572007-03-29 02:26:30 +00001338 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Reid Spencer1791f232007-03-12 17:25:59 +00001339 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1340 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1341
1342 // Handle the sign bits.
1343 APInt SignBit(APInt::getSignBit(BitWidth));
1344 // Adjust to where it is now in the mask.
1345 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1346
1347 // If the input sign bit is known to be zero, or if none of the top bits
1348 // are demanded, turn this into an unsigned shift right.
Zhou Sheng1152ca92008-06-06 08:32:05 +00001349 if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] ||
Reid Spencer1791f232007-03-12 17:25:59 +00001350 (HighBits & ~DemandedMask) == HighBits) {
1351 // Perform the logical shift right.
Chris Lattner83c6a142009-01-31 08:15:18 +00001352 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer1791f232007-03-12 17:25:59 +00001353 I->getOperand(0), SA, I->getName());
Chris Lattner83c6a142009-01-31 08:15:18 +00001354 return InsertNewInstBefore(NewVal, *I);
Reid Spencer1791f232007-03-12 17:25:59 +00001355 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1356 RHSKnownOne |= HighBits;
1357 }
1358 }
1359 break;
Nick Lewyckyd0b62a12008-03-06 06:48:30 +00001360 case Instruction::SRem:
1361 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Nick Lewycky8d8acf32008-11-02 02:41:50 +00001362 APInt RA = Rem->getValue().abs();
1363 if (RA.isPowerOf2()) {
Eli Friedmana0fba532009-06-17 02:57:36 +00001364 if (DemandedMask.ult(RA)) // srem won't affect demanded bits
Chris Lattner83c6a142009-01-31 08:15:18 +00001365 return I->getOperand(0);
Nick Lewyckyf76aa232008-07-12 05:04:38 +00001366
Nick Lewycky8d8acf32008-11-02 02:41:50 +00001367 APInt LowBits = RA - 1;
Nick Lewyckyd0b62a12008-03-06 06:48:30 +00001368 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
Chris Lattner83c6a142009-01-31 08:15:18 +00001369 if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
Nick Lewyckyd0b62a12008-03-06 06:48:30 +00001370 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner83c6a142009-01-31 08:15:18 +00001371 return I;
Nick Lewyckyd0b62a12008-03-06 06:48:30 +00001372
1373 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1374 LHSKnownZero |= ~LowBits;
Nick Lewyckyd0b62a12008-03-06 06:48:30 +00001375
1376 KnownZero |= LHSKnownZero & DemandedMask;
Nick Lewyckyd0b62a12008-03-06 06:48:30 +00001377
Chris Lattner83c6a142009-01-31 08:15:18 +00001378 assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
Nick Lewyckyd0b62a12008-03-06 06:48:30 +00001379 }
1380 }
1381 break;
Dan Gohman72ec3f42008-04-28 17:02:21 +00001382 case Instruction::URem: {
Dan Gohman72ec3f42008-04-28 17:02:21 +00001383 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1384 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Chris Lattner83c6a142009-01-31 08:15:18 +00001385 if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1386 KnownZero2, KnownOne2, Depth+1) ||
1387 SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
Dan Gohman4be6ae42008-05-01 19:13:24 +00001388 KnownZero2, KnownOne2, Depth+1))
Chris Lattner83c6a142009-01-31 08:15:18 +00001389 return I;
Dan Gohman4be6ae42008-05-01 19:13:24 +00001390
Chris Lattner77527f52009-01-21 18:09:24 +00001391 unsigned Leaders = KnownZero2.countLeadingOnes();
Dan Gohman72ec3f42008-04-28 17:02:21 +00001392 Leaders = std::max(Leaders,
1393 KnownZero2.countLeadingOnes());
1394 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyd0b62a12008-03-06 06:48:30 +00001395 break;
Reid Spencer1791f232007-03-12 17:25:59 +00001396 }
Chris Lattneref36dcd2008-06-18 04:33:20 +00001397 case Instruction::Call:
1398 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1399 switch (II->getIntrinsicID()) {
1400 default: break;
1401 case Intrinsic::bswap: {
1402 // If the only bits demanded come from one byte of the bswap result,
1403 // just shift the input byte into position to eliminate the bswap.
1404 unsigned NLZ = DemandedMask.countLeadingZeros();
1405 unsigned NTZ = DemandedMask.countTrailingZeros();
1406
1407 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
1408 // we need all the bits down to bit 8. Likewise, round NLZ. If we
1409 // have 14 leading zeros, round to 8.
1410 NLZ &= ~7;
1411 NTZ &= ~7;
1412 // If we need exactly one byte, we can do this transformation.
1413 if (BitWidth-NLZ-NTZ == 8) {
1414 unsigned ResultBit = NTZ;
1415 unsigned InputBit = BitWidth-NTZ-8;
1416
1417 // Replace this with either a left or right shift to get the byte into
1418 // the right place.
1419 Instruction *NewVal;
1420 if (InputBit > ResultBit)
1421 NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
Owen Andersonb5618da2009-07-03 00:17:18 +00001422 Context->getConstantInt(I->getType(), InputBit-ResultBit));
Chris Lattneref36dcd2008-06-18 04:33:20 +00001423 else
1424 NewVal = BinaryOperator::CreateShl(I->getOperand(1),
Owen Andersonb5618da2009-07-03 00:17:18 +00001425 Context->getConstantInt(I->getType(), ResultBit-InputBit));
Chris Lattneref36dcd2008-06-18 04:33:20 +00001426 NewVal->takeName(I);
Chris Lattner83c6a142009-01-31 08:15:18 +00001427 return InsertNewInstBefore(NewVal, *I);
Chris Lattneref36dcd2008-06-18 04:33:20 +00001428 }
1429
1430 // TODO: Could compute known zero/one bits based on the input.
1431 break;
1432 }
1433 }
1434 }
Chris Lattner78119b42008-06-18 18:11:55 +00001435 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Chris Lattneref36dcd2008-06-18 04:33:20 +00001436 break;
Dan Gohman72ec3f42008-04-28 17:02:21 +00001437 }
Reid Spencer1791f232007-03-12 17:25:59 +00001438
1439 // If the client is only demanding bits that we know, return the known
1440 // constant.
Dan Gohman5638e0d2009-04-25 17:12:48 +00001441 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
Owen Andersonb5618da2009-07-03 00:17:18 +00001442 Constant *C = Context->getConstantInt(RHSKnownOne);
Dan Gohman5638e0d2009-04-25 17:12:48 +00001443 if (isa<PointerType>(V->getType()))
Owen Andersonb5618da2009-07-03 00:17:18 +00001444 C = Context->getConstantExprIntToPtr(C, V->getType());
Dan Gohman5638e0d2009-04-25 17:12:48 +00001445 return C;
1446 }
Reid Spencer1791f232007-03-12 17:25:59 +00001447 return false;
1448}
1449
Chris Lattner2deeaea2006-10-05 06:55:50 +00001450
Mon P Wang25f01062008-11-10 04:46:22 +00001451/// SimplifyDemandedVectorElts - The specified value produces a vector with
Evan Cheng8542caa2009-02-03 10:05:09 +00001452/// any number of elements. DemandedElts contains the set of elements that are
Chris Lattner2deeaea2006-10-05 06:55:50 +00001453/// actually used by the caller. This method analyzes which elements of the
1454/// operand are undef and returns that information in UndefElts.
1455///
1456/// If the information about demanded elements can be used to simplify the
1457/// operation, the operation is simplified, then the resultant value is
1458/// returned. This returns null if no change was made.
Evan Cheng8542caa2009-02-03 10:05:09 +00001459Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1460 APInt& UndefElts,
Chris Lattner2deeaea2006-10-05 06:55:50 +00001461 unsigned Depth) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00001462 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Evan Cheng8542caa2009-02-03 10:05:09 +00001463 APInt EltMask(APInt::getAllOnesValue(VWidth));
Dan Gohman86fb5b42008-09-09 18:11:14 +00001464 assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
Chris Lattner2deeaea2006-10-05 06:55:50 +00001465
1466 if (isa<UndefValue>(V)) {
1467 // If the entire vector is undefined, just return this info.
1468 UndefElts = EltMask;
1469 return 0;
1470 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1471 UndefElts = EltMask;
Owen Andersonb5618da2009-07-03 00:17:18 +00001472 return Context->getUndef(V->getType());
Chris Lattner2deeaea2006-10-05 06:55:50 +00001473 }
Mon P Wang25f01062008-11-10 04:46:22 +00001474
Chris Lattner2deeaea2006-10-05 06:55:50 +00001475 UndefElts = 0;
Reid Spencerd84d35b2007-02-15 02:26:10 +00001476 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1477 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Andersonb5618da2009-07-03 00:17:18 +00001478 Constant *Undef = Context->getUndef(EltTy);
Chris Lattner2deeaea2006-10-05 06:55:50 +00001479
1480 std::vector<Constant*> Elts;
1481 for (unsigned i = 0; i != VWidth; ++i)
Evan Cheng8542caa2009-02-03 10:05:09 +00001482 if (!DemandedElts[i]) { // If not demanded, set to undef.
Chris Lattner2deeaea2006-10-05 06:55:50 +00001483 Elts.push_back(Undef);
Evan Cheng8542caa2009-02-03 10:05:09 +00001484 UndefElts.set(i);
Chris Lattner2deeaea2006-10-05 06:55:50 +00001485 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1486 Elts.push_back(Undef);
Evan Cheng8542caa2009-02-03 10:05:09 +00001487 UndefElts.set(i);
Chris Lattner2deeaea2006-10-05 06:55:50 +00001488 } else { // Otherwise, defined.
1489 Elts.push_back(CP->getOperand(i));
1490 }
Mon P Wang25f01062008-11-10 04:46:22 +00001491
Chris Lattner2deeaea2006-10-05 06:55:50 +00001492 // If we changed the constant, return it.
Owen Andersonb5618da2009-07-03 00:17:18 +00001493 Constant *NewCP = Context->getConstantVector(Elts);
Chris Lattner2deeaea2006-10-05 06:55:50 +00001494 return NewCP != CP ? NewCP : 0;
1495 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00001496 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner2deeaea2006-10-05 06:55:50 +00001497 // set to undef.
Mon P Wang5ca2ec62008-11-06 22:52:21 +00001498
1499 // Check if this is identity. If so, return 0 since we are not simplifying
1500 // anything.
1501 if (DemandedElts == ((1ULL << VWidth) -1))
1502 return 0;
1503
Reid Spencerd84d35b2007-02-15 02:26:10 +00001504 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Andersonb5618da2009-07-03 00:17:18 +00001505 Constant *Zero = Context->getNullValue(EltTy);
1506 Constant *Undef = Context->getUndef(EltTy);
Chris Lattner2deeaea2006-10-05 06:55:50 +00001507 std::vector<Constant*> Elts;
Evan Cheng8542caa2009-02-03 10:05:09 +00001508 for (unsigned i = 0; i != VWidth; ++i) {
1509 Constant *Elt = DemandedElts[i] ? Zero : Undef;
1510 Elts.push_back(Elt);
1511 }
Chris Lattner2deeaea2006-10-05 06:55:50 +00001512 UndefElts = DemandedElts ^ EltMask;
Owen Andersonb5618da2009-07-03 00:17:18 +00001513 return Context->getConstantVector(Elts);
Chris Lattner2deeaea2006-10-05 06:55:50 +00001514 }
1515
Dan Gohman86fb5b42008-09-09 18:11:14 +00001516 // Limit search depth.
1517 if (Depth == 10)
Dan Gohman1b5055a2009-04-25 17:28:45 +00001518 return 0;
Dan Gohman86fb5b42008-09-09 18:11:14 +00001519
1520 // If multiple users are using the root value, procede with
1521 // simplification conservatively assuming that all elements
1522 // are needed.
1523 if (!V->hasOneUse()) {
1524 // Quit if we find multiple users of a non-root value though.
1525 // They'll be handled when it's their turn to be visited by
1526 // the main instcombine process.
1527 if (Depth != 0)
Chris Lattner2deeaea2006-10-05 06:55:50 +00001528 // TODO: Just compute the UndefElts information recursively.
Dan Gohman1b5055a2009-04-25 17:28:45 +00001529 return 0;
Dan Gohman86fb5b42008-09-09 18:11:14 +00001530
1531 // Conservatively assume that all elements are needed.
1532 DemandedElts = EltMask;
Chris Lattner2deeaea2006-10-05 06:55:50 +00001533 }
1534
1535 Instruction *I = dyn_cast<Instruction>(V);
Dan Gohman1b5055a2009-04-25 17:28:45 +00001536 if (!I) return 0; // Only analyze instructions.
Chris Lattner2deeaea2006-10-05 06:55:50 +00001537
1538 bool MadeChange = false;
Evan Cheng8542caa2009-02-03 10:05:09 +00001539 APInt UndefElts2(VWidth, 0);
Chris Lattner2deeaea2006-10-05 06:55:50 +00001540 Value *TmpV;
1541 switch (I->getOpcode()) {
1542 default: break;
1543
1544 case Instruction::InsertElement: {
1545 // If this is a variable index, we don't know which element it overwrites.
1546 // demand exactly the same input as we produce.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001547 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner2deeaea2006-10-05 06:55:50 +00001548 if (Idx == 0) {
1549 // Note that we can't propagate undef elt info, because we don't know
1550 // which elt is getting updated.
1551 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1552 UndefElts2, Depth+1);
1553 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1554 break;
1555 }
1556
1557 // If this is inserting an element that isn't demanded, remove this
1558 // insertelement.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001559 unsigned IdxNo = Idx->getZExtValue();
Evan Cheng8542caa2009-02-03 10:05:09 +00001560 if (IdxNo >= VWidth || !DemandedElts[IdxNo])
Chris Lattner2deeaea2006-10-05 06:55:50 +00001561 return AddSoonDeadInstToWorklist(*I, 0);
1562
1563 // Otherwise, the element inserted overwrites whatever was there, so the
1564 // input demanded set is simpler than the output set.
Evan Cheng8542caa2009-02-03 10:05:09 +00001565 APInt DemandedElts2 = DemandedElts;
1566 DemandedElts2.clear(IdxNo);
1567 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
Chris Lattner2deeaea2006-10-05 06:55:50 +00001568 UndefElts, Depth+1);
1569 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1570
1571 // The inserted element is defined.
Evan Cheng8542caa2009-02-03 10:05:09 +00001572 UndefElts.clear(IdxNo);
Dan Gohman86fb5b42008-09-09 18:11:14 +00001573 break;
1574 }
1575 case Instruction::ShuffleVector: {
1576 ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
Mon P Wang25f01062008-11-10 04:46:22 +00001577 uint64_t LHSVWidth =
1578 cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
Evan Cheng8542caa2009-02-03 10:05:09 +00001579 APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
Dan Gohman86fb5b42008-09-09 18:11:14 +00001580 for (unsigned i = 0; i < VWidth; i++) {
Evan Cheng8542caa2009-02-03 10:05:09 +00001581 if (DemandedElts[i]) {
Dan Gohman86fb5b42008-09-09 18:11:14 +00001582 unsigned MaskVal = Shuffle->getMaskValue(i);
1583 if (MaskVal != -1u) {
Mon P Wang25f01062008-11-10 04:46:22 +00001584 assert(MaskVal < LHSVWidth * 2 &&
Dan Gohman86fb5b42008-09-09 18:11:14 +00001585 "shufflevector mask index out of range!");
Mon P Wang25f01062008-11-10 04:46:22 +00001586 if (MaskVal < LHSVWidth)
Evan Cheng8542caa2009-02-03 10:05:09 +00001587 LeftDemanded.set(MaskVal);
Dan Gohman86fb5b42008-09-09 18:11:14 +00001588 else
Evan Cheng8542caa2009-02-03 10:05:09 +00001589 RightDemanded.set(MaskVal - LHSVWidth);
Dan Gohman86fb5b42008-09-09 18:11:14 +00001590 }
1591 }
1592 }
1593
Nate Begeman318aea92009-02-11 22:36:25 +00001594 APInt UndefElts4(LHSVWidth, 0);
Dan Gohman86fb5b42008-09-09 18:11:14 +00001595 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
Nate Begeman318aea92009-02-11 22:36:25 +00001596 UndefElts4, Depth+1);
Dan Gohman86fb5b42008-09-09 18:11:14 +00001597 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1598
Nate Begeman318aea92009-02-11 22:36:25 +00001599 APInt UndefElts3(LHSVWidth, 0);
Dan Gohman86fb5b42008-09-09 18:11:14 +00001600 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1601 UndefElts3, Depth+1);
1602 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1603
1604 bool NewUndefElts = false;
1605 for (unsigned i = 0; i < VWidth; i++) {
1606 unsigned MaskVal = Shuffle->getMaskValue(i);
Dan Gohman97f0a0f2008-09-10 01:09:32 +00001607 if (MaskVal == -1u) {
Evan Cheng8542caa2009-02-03 10:05:09 +00001608 UndefElts.set(i);
Mon P Wang25f01062008-11-10 04:46:22 +00001609 } else if (MaskVal < LHSVWidth) {
Nate Begeman318aea92009-02-11 22:36:25 +00001610 if (UndefElts4[MaskVal]) {
Evan Cheng8542caa2009-02-03 10:05:09 +00001611 NewUndefElts = true;
1612 UndefElts.set(i);
1613 }
Dan Gohman86fb5b42008-09-09 18:11:14 +00001614 } else {
Evan Cheng8542caa2009-02-03 10:05:09 +00001615 if (UndefElts3[MaskVal - LHSVWidth]) {
1616 NewUndefElts = true;
1617 UndefElts.set(i);
1618 }
Dan Gohman86fb5b42008-09-09 18:11:14 +00001619 }
1620 }
1621
1622 if (NewUndefElts) {
1623 // Add additional discovered undefs.
1624 std::vector<Constant*> Elts;
1625 for (unsigned i = 0; i < VWidth; ++i) {
Evan Cheng8542caa2009-02-03 10:05:09 +00001626 if (UndefElts[i])
Owen Andersonb5618da2009-07-03 00:17:18 +00001627 Elts.push_back(Context->getUndef(Type::Int32Ty));
Dan Gohman86fb5b42008-09-09 18:11:14 +00001628 else
Owen Andersonb5618da2009-07-03 00:17:18 +00001629 Elts.push_back(Context->getConstantInt(Type::Int32Ty,
Dan Gohman86fb5b42008-09-09 18:11:14 +00001630 Shuffle->getMaskValue(i)));
1631 }
Owen Andersonb5618da2009-07-03 00:17:18 +00001632 I->setOperand(2, Context->getConstantVector(Elts));
Dan Gohman86fb5b42008-09-09 18:11:14 +00001633 MadeChange = true;
1634 }
Chris Lattner2deeaea2006-10-05 06:55:50 +00001635 break;
1636 }
Chris Lattnerb37fb6a2007-04-14 22:29:23 +00001637 case Instruction::BitCast: {
Dan Gohman06c60b62007-07-16 14:29:03 +00001638 // Vector->vector casts only.
Chris Lattnerb37fb6a2007-04-14 22:29:23 +00001639 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1640 if (!VTy) break;
1641 unsigned InVWidth = VTy->getNumElements();
Evan Cheng8542caa2009-02-03 10:05:09 +00001642 APInt InputDemandedElts(InVWidth, 0);
Chris Lattnerb37fb6a2007-04-14 22:29:23 +00001643 unsigned Ratio;
1644
1645 if (VWidth == InVWidth) {
Dan Gohman06c60b62007-07-16 14:29:03 +00001646 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
Chris Lattnerb37fb6a2007-04-14 22:29:23 +00001647 // elements as are demanded of us.
1648 Ratio = 1;
1649 InputDemandedElts = DemandedElts;
1650 } else if (VWidth > InVWidth) {
1651 // Untested so far.
1652 break;
1653
1654 // If there are more elements in the result than there are in the source,
1655 // then an input element is live if any of the corresponding output
1656 // elements are live.
1657 Ratio = VWidth/InVWidth;
1658 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
Evan Cheng8542caa2009-02-03 10:05:09 +00001659 if (DemandedElts[OutIdx])
1660 InputDemandedElts.set(OutIdx/Ratio);
Chris Lattnerb37fb6a2007-04-14 22:29:23 +00001661 }
1662 } else {
1663 // Untested so far.
1664 break;
1665
1666 // If there are more elements in the source than there are in the result,
1667 // then an input element is live if the corresponding output element is
1668 // live.
1669 Ratio = InVWidth/VWidth;
1670 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng8542caa2009-02-03 10:05:09 +00001671 if (DemandedElts[InIdx/Ratio])
1672 InputDemandedElts.set(InIdx);
Chris Lattnerb37fb6a2007-04-14 22:29:23 +00001673 }
Chris Lattner2deeaea2006-10-05 06:55:50 +00001674
Chris Lattnerb37fb6a2007-04-14 22:29:23 +00001675 // div/rem demand all inputs, because they don't want divide by zero.
1676 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1677 UndefElts2, Depth+1);
1678 if (TmpV) {
1679 I->setOperand(0, TmpV);
1680 MadeChange = true;
1681 }
1682
1683 UndefElts = UndefElts2;
1684 if (VWidth > InVWidth) {
Torok Edwin56d06592009-07-11 20:10:48 +00001685 LLVM_UNREACHABLE("Unimp");
Chris Lattnerb37fb6a2007-04-14 22:29:23 +00001686 // If there are more elements in the result than there are in the source,
1687 // then an output element is undef if the corresponding input element is
1688 // undef.
1689 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
Evan Cheng8542caa2009-02-03 10:05:09 +00001690 if (UndefElts2[OutIdx/Ratio])
1691 UndefElts.set(OutIdx);
Chris Lattnerb37fb6a2007-04-14 22:29:23 +00001692 } else if (VWidth < InVWidth) {
Torok Edwin56d06592009-07-11 20:10:48 +00001693 LLVM_UNREACHABLE("Unimp");
Chris Lattnerb37fb6a2007-04-14 22:29:23 +00001694 // If there are more elements in the source than there are in the result,
1695 // then a result element is undef if all of the corresponding input
1696 // elements are undef.
1697 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1698 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng8542caa2009-02-03 10:05:09 +00001699 if (!UndefElts2[InIdx]) // Not undef?
1700 UndefElts.clear(InIdx/Ratio); // Clear undef bit.
Chris Lattnerb37fb6a2007-04-14 22:29:23 +00001701 }
1702 break;
1703 }
Chris Lattner2deeaea2006-10-05 06:55:50 +00001704 case Instruction::And:
1705 case Instruction::Or:
1706 case Instruction::Xor:
1707 case Instruction::Add:
1708 case Instruction::Sub:
1709 case Instruction::Mul:
1710 // div/rem demand all inputs, because they don't want divide by zero.
1711 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1712 UndefElts, Depth+1);
1713 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1714 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1715 UndefElts2, Depth+1);
1716 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1717
1718 // Output elements are undefined if both are undefined. Consider things
1719 // like undef&0. The result is known zero, not undef.
1720 UndefElts &= UndefElts2;
1721 break;
1722
1723 case Instruction::Call: {
1724 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1725 if (!II) break;
1726 switch (II->getIntrinsicID()) {
1727 default: break;
1728
1729 // Binary vector operations that work column-wise. A dest element is a
1730 // function of the corresponding input elements from the two inputs.
1731 case Intrinsic::x86_sse_sub_ss:
1732 case Intrinsic::x86_sse_mul_ss:
1733 case Intrinsic::x86_sse_min_ss:
1734 case Intrinsic::x86_sse_max_ss:
1735 case Intrinsic::x86_sse2_sub_sd:
1736 case Intrinsic::x86_sse2_mul_sd:
1737 case Intrinsic::x86_sse2_min_sd:
1738 case Intrinsic::x86_sse2_max_sd:
1739 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1740 UndefElts, Depth+1);
1741 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1742 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1743 UndefElts2, Depth+1);
1744 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1745
1746 // If only the low elt is demanded and this is a scalarizable intrinsic,
1747 // scalarize it now.
1748 if (DemandedElts == 1) {
1749 switch (II->getIntrinsicID()) {
1750 default: break;
1751 case Intrinsic::x86_sse_sub_ss:
1752 case Intrinsic::x86_sse_mul_ss:
1753 case Intrinsic::x86_sse2_sub_sd:
1754 case Intrinsic::x86_sse2_mul_sd:
1755 // TODO: Lower MIN/MAX/ABS/etc
1756 Value *LHS = II->getOperand(1);
1757 Value *RHS = II->getOperand(2);
1758 // Extract the element as scalars.
1759 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1760 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1761
1762 switch (II->getIntrinsicID()) {
Torok Edwin56d06592009-07-11 20:10:48 +00001763 default: LLVM_UNREACHABLE("Case stmts out of sync!");
Chris Lattner2deeaea2006-10-05 06:55:50 +00001764 case Intrinsic::x86_sse_sub_ss:
1765 case Intrinsic::x86_sse2_sub_sd:
Dan Gohmana5b96452009-06-04 22:49:04 +00001766 TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
Chris Lattner2deeaea2006-10-05 06:55:50 +00001767 II->getName()), *II);
1768 break;
1769 case Intrinsic::x86_sse_mul_ss:
1770 case Intrinsic::x86_sse2_mul_sd:
Dan Gohmana5b96452009-06-04 22:49:04 +00001771 TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
Chris Lattner2deeaea2006-10-05 06:55:50 +00001772 II->getName()), *II);
1773 break;
1774 }
1775
1776 Instruction *New =
Owen Andersonb5618da2009-07-03 00:17:18 +00001777 InsertElementInst::Create(
1778 Context->getUndef(II->getType()), TmpV, 0U, II->getName());
Chris Lattner2deeaea2006-10-05 06:55:50 +00001779 InsertNewInstBefore(New, *II);
1780 AddSoonDeadInstToWorklist(*II, 0);
1781 return New;
1782 }
1783 }
1784
1785 // Output elements are undefined if both are undefined. Consider things
1786 // like undef&0. The result is known zero, not undef.
1787 UndefElts &= UndefElts2;
1788 break;
1789 }
1790 break;
1791 }
1792 }
1793 return MadeChange ? I : 0;
1794}
1795
Dan Gohman123438c2008-05-19 22:14:15 +00001796
Chris Lattnerb8b97502003-08-13 19:01:45 +00001797/// AssociativeOpt - Perform an optimization on an associative operator. This
1798/// function is designed to check a chain of associative operators for a
1799/// potential to apply a certain optimization. Since the optimization may be
1800/// applicable if the expression was reassociated, this checks the chain, then
1801/// reassociates the expression as necessary to expose the optimization
1802/// opportunity. This makes use of a special Functor, which must define
1803/// 'shouldApply' and 'apply' methods.
1804///
1805template<typename Functor>
Owen Andersonb5618da2009-07-03 00:17:18 +00001806static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F,
Owen Anderson38264b12009-07-06 23:00:19 +00001807 LLVMContext *Context) {
Chris Lattnerb8b97502003-08-13 19:01:45 +00001808 unsigned Opcode = Root.getOpcode();
1809 Value *LHS = Root.getOperand(0);
1810
1811 // Quick check, see if the immediate LHS matches...
1812 if (F.shouldApply(LHS))
1813 return F.apply(Root);
1814
1815 // Otherwise, if the LHS is not of the same opcode as the root, return.
1816 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001817 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +00001818 // Should we apply this transform to the RHS?
1819 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1820
1821 // If not to the RHS, check to see if we should apply to the LHS...
1822 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1823 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1824 ShouldApply = true;
1825 }
1826
1827 // If the functor wants to apply the optimization to the RHS of LHSI,
1828 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1829 if (ShouldApply) {
Chris Lattnerb8b97502003-08-13 19:01:45 +00001830 // Now all of the instructions are in the current basic block, go ahead
1831 // and perform the reassociation.
1832 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1833
1834 // First move the selected RHS to the LHS of the root...
1835 Root.setOperand(0, LHSI->getOperand(1));
1836
1837 // Make what used to be the LHS of the root be the user of the root...
1838 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner284d3b02004-04-16 18:08:07 +00001839 if (&Root == TmpLHSI) {
Owen Andersonb5618da2009-07-03 00:17:18 +00001840 Root.replaceAllUsesWith(Context->getNullValue(TmpLHSI->getType()));
Chris Lattner8953b902004-04-05 02:10:19 +00001841 return 0;
1842 }
Chris Lattner284d3b02004-04-16 18:08:07 +00001843 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattnerb8b97502003-08-13 19:01:45 +00001844 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner284d3b02004-04-16 18:08:07 +00001845 BasicBlock::iterator ARI = &Root; ++ARI;
Dan Gohmaned225092008-06-19 17:47:47 +00001846 TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root
Chris Lattner284d3b02004-04-16 18:08:07 +00001847 ARI = Root;
Chris Lattnerb8b97502003-08-13 19:01:45 +00001848
1849 // Now propagate the ExtraOperand down the chain of instructions until we
1850 // get to LHSI.
1851 while (TmpLHSI != LHSI) {
1852 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner284d3b02004-04-16 18:08:07 +00001853 // Move the instruction to immediately before the chain we are
1854 // constructing to avoid breaking dominance properties.
Dan Gohmaned225092008-06-19 17:47:47 +00001855 NextLHSI->moveBefore(ARI);
Chris Lattner284d3b02004-04-16 18:08:07 +00001856 ARI = NextLHSI;
1857
Chris Lattnerb8b97502003-08-13 19:01:45 +00001858 Value *NextOp = NextLHSI->getOperand(1);
1859 NextLHSI->setOperand(1, ExtraOperand);
1860 TmpLHSI = NextLHSI;
1861 ExtraOperand = NextOp;
1862 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001863
Chris Lattnerb8b97502003-08-13 19:01:45 +00001864 // Now that the instructions are reassociated, have the functor perform
1865 // the transformation...
1866 return F.apply(Root);
1867 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001868
Chris Lattnerb8b97502003-08-13 19:01:45 +00001869 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1870 }
1871 return 0;
1872}
1873
Dan Gohmand78c4002008-05-13 00:00:25 +00001874namespace {
Chris Lattnerb8b97502003-08-13 19:01:45 +00001875
Nick Lewycky4f3d8782008-05-23 04:34:58 +00001876// AddRHS - Implements: X + X --> X << 1
Chris Lattnerb8b97502003-08-13 19:01:45 +00001877struct AddRHS {
1878 Value *RHS;
Owen Anderson38264b12009-07-06 23:00:19 +00001879 LLVMContext *Context;
1880 AddRHS(Value *rhs, LLVMContext *C) : RHS(rhs), Context(C) {}
Chris Lattnerb8b97502003-08-13 19:01:45 +00001881 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1882 Instruction *apply(BinaryOperator &Add) const {
Nick Lewycky4f3d8782008-05-23 04:34:58 +00001883 return BinaryOperator::CreateShl(Add.getOperand(0),
Owen Andersonb5618da2009-07-03 00:17:18 +00001884 Context->getConstantInt(Add.getType(), 1));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001885 }
1886};
1887
1888// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1889// iff C1&C2 == 0
1890struct AddMaskingAnd {
1891 Constant *C2;
Owen Anderson38264b12009-07-06 23:00:19 +00001892 LLVMContext *Context;
1893 AddMaskingAnd(Constant *c, LLVMContext *C) : C2(c), Context(C) {}
Chris Lattnerb8b97502003-08-13 19:01:45 +00001894 bool shouldApply(Value *LHS) const {
Chris Lattnerd4252a72004-07-30 07:50:03 +00001895 ConstantInt *C1;
Owen Anderson16e76742009-07-10 17:35:01 +00001896 return match(LHS, m_And(m_Value(), m_ConstantInt(C1)), *Context) &&
Owen Andersonb5618da2009-07-03 00:17:18 +00001897 Context->getConstantExprAnd(C1, C2)->isNullValue();
Chris Lattnerb8b97502003-08-13 19:01:45 +00001898 }
1899 Instruction *apply(BinaryOperator &Add) const {
Gabor Greife1f6e4b2008-05-16 19:29:10 +00001900 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001901 }
1902};
1903
Dan Gohmand78c4002008-05-13 00:00:25 +00001904}
1905
Chris Lattner86102b82005-01-01 16:22:27 +00001906static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner183b3362004-04-09 19:05:30 +00001907 InstCombiner *IC) {
Owen Anderson38264b12009-07-06 23:00:19 +00001908 LLVMContext *Context = IC->getContext();
Owen Andersonb5618da2009-07-03 00:17:18 +00001909
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001910 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Eli Friedman55e4bec2008-11-30 21:09:11 +00001911 return IC->InsertCastBefore(CI->getOpcode(), SO, I.getType(), I);
Chris Lattner86102b82005-01-01 16:22:27 +00001912 }
1913
Chris Lattner183b3362004-04-09 19:05:30 +00001914 // Figure out if the constant is the left or the right argument.
Chris Lattner86102b82005-01-01 16:22:27 +00001915 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1916 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001917
Chris Lattner183b3362004-04-09 19:05:30 +00001918 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1919 if (ConstIsRHS)
Owen Andersonb5618da2009-07-03 00:17:18 +00001920 return Context->getConstantExpr(I.getOpcode(), SOC, ConstOperand);
1921 return Context->getConstantExpr(I.getOpcode(), ConstOperand, SOC);
Chris Lattner183b3362004-04-09 19:05:30 +00001922 }
1923
1924 Value *Op0 = SO, *Op1 = ConstOperand;
1925 if (!ConstIsRHS)
1926 std::swap(Op0, Op1);
1927 Instruction *New;
Chris Lattner86102b82005-01-01 16:22:27 +00001928 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greife1f6e4b2008-05-16 19:29:10 +00001929 New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Reid Spencer266e42b2006-12-23 06:05:41 +00001930 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Anderson1e5f00e2009-07-09 23:48:35 +00001931 New = CmpInst::Create(*Context, CI->getOpcode(), CI->getPredicate(),
1932 Op0, Op1, SO->getName()+".cmp");
Chris Lattnerf9d96652004-04-10 19:15:56 +00001933 else {
Torok Edwinccb29cd2009-07-11 13:10:19 +00001934 LLVM_UNREACHABLE("Unknown binary instruction type!");
Chris Lattnerf9d96652004-04-10 19:15:56 +00001935 }
Chris Lattner86102b82005-01-01 16:22:27 +00001936 return IC->InsertNewInstBefore(New, I);
1937}
1938
1939// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1940// constant as the other operand, try to fold the binary operator into the
1941// select arguments. This also works for Cast instructions, which obviously do
1942// not have a second operand.
1943static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1944 InstCombiner *IC) {
1945 // Don't modify shared select instructions
1946 if (!SI->hasOneUse()) return 0;
1947 Value *TV = SI->getOperand(1);
1948 Value *FV = SI->getOperand(2);
1949
1950 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner374e6592005-04-21 05:43:13 +00001951 // Bool selects with constant operands can be folded to logical ops.
Reid Spencer542964f2007-01-11 18:21:29 +00001952 if (SI->getType() == Type::Int1Ty) return 0;
Chris Lattner374e6592005-04-21 05:43:13 +00001953
Chris Lattner86102b82005-01-01 16:22:27 +00001954 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1955 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1956
Gabor Greife9ecc682008-04-06 20:25:17 +00001957 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1958 SelectFalseVal);
Chris Lattner86102b82005-01-01 16:22:27 +00001959 }
1960 return 0;
Chris Lattner183b3362004-04-09 19:05:30 +00001961}
1962
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001963
1964/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1965/// node as operand #0, see if we can fold the instruction into the PHI (which
1966/// is only possible if all operands to the PHI are constants).
1967Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1968 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00001969 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner04689872006-09-09 22:02:56 +00001970 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001971
Chris Lattner04689872006-09-09 22:02:56 +00001972 // Check to see if all of the operands of the PHI are constants. If there is
1973 // one non-constant value, remember the BB it is. If there is more than one
Chris Lattnerc4d8e7e2007-02-24 01:03:45 +00001974 // or if *it* is a PHI, bail out.
Chris Lattner04689872006-09-09 22:02:56 +00001975 BasicBlock *NonConstBB = 0;
1976 for (unsigned i = 0; i != NumPHIValues; ++i)
1977 if (!isa<Constant>(PN->getIncomingValue(i))) {
1978 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerc4d8e7e2007-02-24 01:03:45 +00001979 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner04689872006-09-09 22:02:56 +00001980 NonConstBB = PN->getIncomingBlock(i);
1981
1982 // If the incoming non-constant value is in I's block, we have an infinite
1983 // loop.
1984 if (NonConstBB == I.getParent())
1985 return 0;
1986 }
1987
1988 // If there is exactly one non-constant value, we can insert a copy of the
1989 // operation in that block. However, if this is a critical edge, we would be
1990 // inserting the computation one some other paths (e.g. inside a loop). Only
1991 // do this if the pred block is unconditionally branching into the phi block.
1992 if (NonConstBB) {
1993 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1994 if (!BI || !BI->isUnconditional()) return 0;
1995 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001996
1997 // Okay, we can do the transformation: create the new PHI node.
Gabor Greife9ecc682008-04-06 20:25:17 +00001998 PHINode *NewPN = PHINode::Create(I.getType(), "");
Chris Lattnerd8e20182005-01-29 00:39:08 +00001999 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002000 InsertNewInstBefore(NewPN, *PN);
Chris Lattner6e0123b2007-02-11 01:23:03 +00002001 NewPN->takeName(PN);
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002002
2003 // Next, add all of the operands to the PHI.
2004 if (I.getNumOperands() == 2) {
2005 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattner7515cab2004-11-14 19:13:23 +00002006 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnerf0da7972007-08-05 08:47:58 +00002007 Value *InV = 0;
Chris Lattner04689872006-09-09 22:02:56 +00002008 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer266e42b2006-12-23 06:05:41 +00002009 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Andersonb5618da2009-07-03 00:17:18 +00002010 InV = Context->getConstantExprCompare(CI->getPredicate(), InC, C);
Reid Spencer266e42b2006-12-23 06:05:41 +00002011 else
Owen Andersonb5618da2009-07-03 00:17:18 +00002012 InV = Context->getConstantExpr(I.getOpcode(), InC, C);
Chris Lattner04689872006-09-09 22:02:56 +00002013 } else {
2014 assert(PN->getIncomingBlock(i) == NonConstBB);
2015 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greife1f6e4b2008-05-16 19:29:10 +00002016 InV = BinaryOperator::Create(BO->getOpcode(),
Chris Lattner04689872006-09-09 22:02:56 +00002017 PN->getIncomingValue(i), C, "phitmp",
2018 NonConstBB->getTerminator());
Reid Spencer266e42b2006-12-23 06:05:41 +00002019 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Anderson1e5f00e2009-07-09 23:48:35 +00002020 InV = CmpInst::Create(*Context, CI->getOpcode(),
Reid Spencer266e42b2006-12-23 06:05:41 +00002021 CI->getPredicate(),
2022 PN->getIncomingValue(i), C, "phitmp",
2023 NonConstBB->getTerminator());
Chris Lattner04689872006-09-09 22:02:56 +00002024 else
Torok Edwin56d06592009-07-11 20:10:48 +00002025 LLVM_UNREACHABLE("Unknown binop!");
Chris Lattner04689872006-09-09 22:02:56 +00002026
Chris Lattnerb15e2b12007-03-02 21:28:56 +00002027 AddToWorkList(cast<Instruction>(InV));
Chris Lattner04689872006-09-09 22:02:56 +00002028 }
2029 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002030 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002031 } else {
2032 CastInst *CI = cast<CastInst>(&I);
2033 const Type *RetTy = CI->getType();
Chris Lattner7515cab2004-11-14 19:13:23 +00002034 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner04689872006-09-09 22:02:56 +00002035 Value *InV;
2036 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Owen Andersonb5618da2009-07-03 00:17:18 +00002037 InV = Context->getConstantExprCast(CI->getOpcode(), InC, RetTy);
Chris Lattner04689872006-09-09 22:02:56 +00002038 } else {
2039 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00002040 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002041 I.getType(), "phitmp",
2042 NonConstBB->getTerminator());
Chris Lattnerb15e2b12007-03-02 21:28:56 +00002043 AddToWorkList(cast<Instruction>(InV));
Chris Lattner04689872006-09-09 22:02:56 +00002044 }
2045 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002046 }
2047 }
2048 return ReplaceInstUsesWith(I, NewPN);
2049}
2050
Chris Lattner17819d92008-01-29 06:52:45 +00002051
Chris Lattner7ac943f2008-05-20 05:46:13 +00002052/// WillNotOverflowSignedAdd - Return true if we can prove that:
2053/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
2054/// This basically requires proving that the add in the original type would not
2055/// overflow to change the sign bit or have a carry out.
2056bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2057 // There are different heuristics we can use for this. Here are some simple
2058 // ones.
2059
2060 // Add has the property that adding any two 2's complement numbers can only
2061 // have one carry bit which can change a sign. As such, if LHS and RHS each
2062 // have at least two sign bits, we know that the addition of the two values will
2063 // sign extend fine.
2064 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2065 return true;
2066
2067
2068 // If one of the operands only has one non-zero bit, and if the other operand
2069 // has a known-zero bit in a more significant place than it (not including the
2070 // sign bit) the ripple may go up to and fill the zero, but won't change the
2071 // sign. For example, (X & ~4) + 1.
2072
2073 // TODO: Implement.
2074
2075 return false;
2076}
2077
Chris Lattner17819d92008-01-29 06:52:45 +00002078
Chris Lattner113f4f42002-06-25 16:13:24 +00002079Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002080 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00002081 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattner9fa53de2002-05-06 16:49:18 +00002082
Chris Lattnercf4a9962004-04-10 22:01:55 +00002083 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattner81a7a232004-10-16 18:11:37 +00002084 // X + undef -> undef
2085 if (isa<UndefValue>(RHS))
2086 return ReplaceInstUsesWith(I, RHS);
2087
Chris Lattnercf4a9962004-04-10 22:01:55 +00002088 // X + 0 --> X
Dan Gohmana5b96452009-06-04 22:49:04 +00002089 if (RHSC->isNullValue())
2090 return ReplaceInstUsesWith(I, LHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002091
Chris Lattnercf4a9962004-04-10 22:01:55 +00002092 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattner6e2c15c2006-11-09 05:12:27 +00002093 // X + (signbit) --> X ^ signbit
Zhou Sheng150f3bb2007-04-01 17:13:37 +00002094 const APInt& Val = CI->getValue();
Zhou Sheng56cda952007-04-02 08:20:41 +00002095 uint32_t BitWidth = Val.getBitWidth();
Reid Spencer959a21d2007-03-23 21:24:59 +00002096 if (Val == APInt::getSignBit(BitWidth))
Gabor Greife1f6e4b2008-05-16 19:29:10 +00002097 return BinaryOperator::CreateXor(LHS, RHS);
Chris Lattner6e2c15c2006-11-09 05:12:27 +00002098
2099 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2100 // (X & 254)+1 -> (X&254)|1
Dan Gohman7ccc52f2009-06-15 22:12:54 +00002101 if (SimplifyDemandedInstructionBits(I))
Chris Lattner83c6a142009-01-31 08:15:18 +00002102 return &I;
Dan Gohman13cbcf1c182008-10-30 20:40:10 +00002103
2104 // zext(i1) - 1 -> select i1, 0, -1
2105 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
2106 if (CI->isAllOnesValue() &&
2107 ZI->getOperand(0)->getType() == Type::Int1Ty)
2108 return SelectInst::Create(ZI->getOperand(0),
Owen Andersonb5618da2009-07-03 00:17:18 +00002109 Context->getNullValue(I.getType()),
Owen Anderson542619e2009-07-13 20:58:05 +00002110 Context->getAllOnesValue(I.getType()));
Chris Lattnercf4a9962004-04-10 22:01:55 +00002111 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002112
2113 if (isa<PHINode>(LHS))
2114 if (Instruction *NV = FoldOpIntoPhi(I))
2115 return NV;
Chris Lattner0b3557f2005-09-24 23:43:33 +00002116
Chris Lattner330628a2006-01-06 17:59:59 +00002117 ConstantInt *XorRHS = 0;
2118 Value *XorLHS = 0;
Chris Lattner4284f642007-01-30 22:32:46 +00002119 if (isa<ConstantInt>(RHSC) &&
Owen Anderson16e76742009-07-10 17:35:01 +00002120 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)), *Context)) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00002121 uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
Zhou Sheng150f3bb2007-04-01 17:13:37 +00002122 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner0b3557f2005-09-24 23:43:33 +00002123
Zhou Sheng56cda952007-04-02 08:20:41 +00002124 uint32_t Size = TySizeBits / 2;
Reid Spencer959a21d2007-03-23 21:24:59 +00002125 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2126 APInt CFF80Val(-C0080Val);
Chris Lattner0b3557f2005-09-24 23:43:33 +00002127 do {
2128 if (TySizeBits > Size) {
Chris Lattner0b3557f2005-09-24 23:43:33 +00002129 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2130 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer959a21d2007-03-23 21:24:59 +00002131 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2132 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner0b3557f2005-09-24 23:43:33 +00002133 // This is a sign extend if the top bits are known zero.
Zhou Shengb3a80b12007-03-29 08:15:12 +00002134 if (!MaskedValueIsZero(XorLHS,
2135 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner0b3557f2005-09-24 23:43:33 +00002136 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer959a21d2007-03-23 21:24:59 +00002137 break;
Chris Lattner0b3557f2005-09-24 23:43:33 +00002138 }
2139 }
2140 Size >>= 1;
Reid Spencer959a21d2007-03-23 21:24:59 +00002141 C0080Val = APIntOps::lshr(C0080Val, Size);
2142 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2143 } while (Size >= 1);
Chris Lattner0b3557f2005-09-24 23:43:33 +00002144
Reid Spencera5c18bf2007-03-28 01:36:16 +00002145 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattnere35fe0f2008-05-19 20:25:04 +00002146 // with funny bit widths then this switch statement should be removed. It
2147 // is just here to get the size of the "middle" type back up to something
2148 // that the back ends can handle.
Reid Spencera5c18bf2007-03-28 01:36:16 +00002149 const Type *MiddleType = 0;
2150 switch (Size) {
2151 default: break;
2152 case 32: MiddleType = Type::Int32Ty; break;
2153 case 16: MiddleType = Type::Int16Ty; break;
2154 case 8: MiddleType = Type::Int8Ty; break;
2155 }
2156 if (MiddleType) {
Reid Spencerbb65ebf2006-12-12 23:36:14 +00002157 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
Chris Lattner0b3557f2005-09-24 23:43:33 +00002158 InsertNewInstBefore(NewTrunc, I);
Reid Spencera5c18bf2007-03-28 01:36:16 +00002159 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner0b3557f2005-09-24 23:43:33 +00002160 }
2161 }
Chris Lattnercf4a9962004-04-10 22:01:55 +00002162 }
Chris Lattner9fa53de2002-05-06 16:49:18 +00002163
Nick Lewycky26b8cd82008-05-31 17:59:52 +00002164 if (I.getType() == Type::Int1Ty)
2165 return BinaryOperator::CreateXor(LHS, RHS);
2166
Nick Lewycky8f3127c2008-05-23 04:39:38 +00002167 // X + X --> X << 1
Nick Lewycky26b8cd82008-05-31 17:59:52 +00002168 if (I.getType()->isInteger()) {
Owen Andersonb5618da2009-07-03 00:17:18 +00002169 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS, Context), Context))
2170 return Result;
Chris Lattner47060462005-04-07 17:14:51 +00002171
2172 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2173 if (RHSI->getOpcode() == Instruction::Sub)
2174 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2175 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2176 }
2177 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2178 if (LHSI->getOpcode() == Instruction::Sub)
2179 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2180 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2181 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00002182 }
Chris Lattnerede3fe02003-08-13 04:18:28 +00002183
Chris Lattner147e9752002-05-08 22:46:53 +00002184 // -A + B --> B - A
Chris Lattnercc226012008-02-17 21:03:36 +00002185 // -A + -B --> -(A + B)
Owen Andersonb5618da2009-07-03 00:17:18 +00002186 if (Value *LHSV = dyn_castNegVal(LHS, Context)) {
Chris Lattner1e3c5012008-02-18 17:50:16 +00002187 if (LHS->getType()->isIntOrIntVector()) {
Owen Andersonb5618da2009-07-03 00:17:18 +00002188 if (Value *RHSV = dyn_castNegVal(RHS, Context)) {
Gabor Greife1f6e4b2008-05-16 19:29:10 +00002189 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
Chris Lattner1e3c5012008-02-18 17:50:16 +00002190 InsertNewInstBefore(NewAdd, I);
Owen Anderson53a52212009-07-13 04:09:18 +00002191 return BinaryOperator::CreateNeg(*Context, NewAdd);
Chris Lattner1e3c5012008-02-18 17:50:16 +00002192 }
Chris Lattnercc226012008-02-17 21:03:36 +00002193 }
2194
Gabor Greife1f6e4b2008-05-16 19:29:10 +00002195 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattnercc226012008-02-17 21:03:36 +00002196 }
Chris Lattner9fa53de2002-05-06 16:49:18 +00002197
2198 // A + -B --> A - B
Chris Lattnerbb74e222003-03-10 23:06:50 +00002199 if (!isa<Constant>(RHS))
Owen Andersonb5618da2009-07-03 00:17:18 +00002200 if (Value *V = dyn_castNegVal(RHS, Context))
Gabor Greife1f6e4b2008-05-16 19:29:10 +00002201 return BinaryOperator::CreateSub(LHS, V);
Chris Lattner260ab202002-04-18 17:39:14 +00002202
Misha Brukmanb1c93172005-04-21 23:48:37 +00002203
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002204 ConstantInt *C2;
Owen Andersonb5618da2009-07-03 00:17:18 +00002205 if (Value *X = dyn_castFoldableMul(LHS, C2, Context)) {
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002206 if (X == RHS) // X*C + X --> X * (C+1)
Owen Andersonb5618da2009-07-03 00:17:18 +00002207 return BinaryOperator::CreateMul(RHS, AddOne(C2, Context));
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002208
2209 // X*C1 + X*C2 --> X * (C1+C2)
2210 ConstantInt *C1;
Owen Andersonb5618da2009-07-03 00:17:18 +00002211 if (X == dyn_castFoldableMul(RHS, C1, Context))
2212 return BinaryOperator::CreateMul(X, Context->getConstantExprAdd(C1, C2));
Chris Lattner57c8d992003-02-18 19:57:07 +00002213 }
2214
2215 // X + X*C --> X * (C+1)
Owen Andersonb5618da2009-07-03 00:17:18 +00002216 if (dyn_castFoldableMul(RHS, C2, Context) == LHS)
2217 return BinaryOperator::CreateMul(LHS, AddOne(C2, Context));
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002218
Chris Lattner23eb8ec2007-01-05 02:17:46 +00002219 // X + ~X --> -1 since ~X = -X-1
Owen Andersonb5618da2009-07-03 00:17:18 +00002220 if (dyn_castNotVal(LHS, Context) == RHS ||
2221 dyn_castNotVal(RHS, Context) == LHS)
2222 return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
Chris Lattner23eb8ec2007-01-05 02:17:46 +00002223
Chris Lattner57c8d992003-02-18 19:57:07 +00002224
Chris Lattnerb8b97502003-08-13 19:01:45 +00002225 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Owen Anderson16e76742009-07-10 17:35:01 +00002226 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2)), *Context))
Owen Andersonb5618da2009-07-03 00:17:18 +00002227 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2, Context), Context))
Chris Lattner23eb8ec2007-01-05 02:17:46 +00002228 return R;
Chris Lattnerfc365b62008-05-19 20:01:56 +00002229
2230 // A+B --> A|B iff A and B have no bits set in common.
2231 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2232 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2233 APInt LHSKnownOne(IT->getBitWidth(), 0);
2234 APInt LHSKnownZero(IT->getBitWidth(), 0);
2235 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2236 if (LHSKnownZero != 0) {
2237 APInt RHSKnownOne(IT->getBitWidth(), 0);
2238 APInt RHSKnownZero(IT->getBitWidth(), 0);
2239 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2240
2241 // No bits in common -> bitwise or.
Chris Lattner6e708302008-05-19 20:03:53 +00002242 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattnerfc365b62008-05-19 20:01:56 +00002243 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattnerfc365b62008-05-19 20:01:56 +00002244 }
2245 }
Chris Lattner7fb29e12003-03-11 00:12:48 +00002246
Nick Lewyckye6e3a7f2008-02-03 07:42:09 +00002247 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewyckyc7a4ba02008-02-03 08:19:11 +00002248 if (I.getType()->isIntOrIntVector()) {
Nick Lewyckye6e3a7f2008-02-03 07:42:09 +00002249 Value *W, *X, *Y, *Z;
Owen Anderson16e76742009-07-10 17:35:01 +00002250 if (match(LHS, m_Mul(m_Value(W), m_Value(X)), *Context) &&
2251 match(RHS, m_Mul(m_Value(Y), m_Value(Z)), *Context)) {
Nick Lewyckye6e3a7f2008-02-03 07:42:09 +00002252 if (W != Y) {
2253 if (W == Z) {
Bill Wendlingd188e032008-02-26 10:53:30 +00002254 std::swap(Y, Z);
Nick Lewyckye6e3a7f2008-02-03 07:42:09 +00002255 } else if (Y == X) {
Bill Wendlingd188e032008-02-26 10:53:30 +00002256 std::swap(W, X);
2257 } else if (X == Z) {
Nick Lewyckye6e3a7f2008-02-03 07:42:09 +00002258 std::swap(Y, Z);
2259 std::swap(W, X);
2260 }
2261 }
2262
2263 if (W == Y) {
Gabor Greife1f6e4b2008-05-16 19:29:10 +00002264 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
Nick Lewyckye6e3a7f2008-02-03 07:42:09 +00002265 LHS->getName()), I);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00002266 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewyckye6e3a7f2008-02-03 07:42:09 +00002267 }
2268 }
2269 }
2270
Chris Lattnerb9cde762003-10-02 15:11:26 +00002271 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner330628a2006-01-06 17:59:59 +00002272 Value *X = 0;
Owen Anderson16e76742009-07-10 17:35:01 +00002273 if (match(LHS, m_Not(m_Value(X)), *Context)) // ~X + C --> (C-1) - X
Owen Andersonb5618da2009-07-03 00:17:18 +00002274 return BinaryOperator::CreateSub(SubOne(CRHS, Context), X);
Chris Lattnerd4252a72004-07-30 07:50:03 +00002275
Chris Lattnerbff91d92004-10-08 05:07:56 +00002276 // (X & FF00) + xx00 -> (X+xx00) & FF00
Owen Anderson16e76742009-07-10 17:35:01 +00002277 if (LHS->hasOneUse() &&
2278 match(LHS, m_And(m_Value(X), m_ConstantInt(C2)), *Context)) {
Owen Andersonb5618da2009-07-03 00:17:18 +00002279 Constant *Anded = Context->getConstantExprAnd(CRHS, C2);
Chris Lattnerbff91d92004-10-08 05:07:56 +00002280 if (Anded == CRHS) {
2281 // See if all bits from the first bit set in the Add RHS up are included
2282 // in the mask. First, get the rightmost bit.
Zhou Sheng150f3bb2007-04-01 17:13:37 +00002283 const APInt& AddRHSV = CRHS->getValue();
Chris Lattnerbff91d92004-10-08 05:07:56 +00002284
2285 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng150f3bb2007-04-01 17:13:37 +00002286 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerbff91d92004-10-08 05:07:56 +00002287
2288 // See if the and mask includes all of these bits.
Zhou Sheng150f3bb2007-04-01 17:13:37 +00002289 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanb1c93172005-04-21 23:48:37 +00002290
Chris Lattnerbff91d92004-10-08 05:07:56 +00002291 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2292 // Okay, the xform is safe. Insert the new add pronto.
Gabor Greife1f6e4b2008-05-16 19:29:10 +00002293 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
Chris Lattnerbff91d92004-10-08 05:07:56 +00002294 LHS->getName()), I);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00002295 return BinaryOperator::CreateAnd(NewAdd, C2);
Chris Lattnerbff91d92004-10-08 05:07:56 +00002296 }
2297 }
2298 }
2299
Chris Lattnerd4252a72004-07-30 07:50:03 +00002300 // Try to fold constant add into select arguments.
2301 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner86102b82005-01-01 16:22:27 +00002302 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerd4252a72004-07-30 07:50:03 +00002303 return R;
Chris Lattnerb9cde762003-10-02 15:11:26 +00002304 }
2305
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002306 // add (cast *A to intptrtype) B ->
Dan Gohman4fe64de2009-06-14 23:30:43 +00002307 // cast (GEP (cast *A to i8*) B) --> intptrtype
Andrew Lenharth4f339be2006-09-19 18:24:51 +00002308 {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002309 CastInst *CI = dyn_cast<CastInst>(LHS);
2310 Value *Other = RHS;
Andrew Lenharth4f339be2006-09-19 18:24:51 +00002311 if (!CI) {
2312 CI = dyn_cast<CastInst>(RHS);
2313 Other = LHS;
2314 }
Andrew Lenharth44cb67a2006-09-20 15:37:57 +00002315 if (CI && CI->getType()->isSized() &&
Dan Gohman7ccc52f2009-06-15 22:12:54 +00002316 (CI->getType()->getScalarSizeInBits() ==
Reid Spencer8f166b02007-01-08 16:32:00 +00002317 TD->getIntPtrType()->getPrimitiveSizeInBits())
Andrew Lenharth44cb67a2006-09-20 15:37:57 +00002318 && isa<PointerType>(CI->getOperand(0)->getType())) {
Christopher Lambedf07882007-12-17 01:12:55 +00002319 unsigned AS =
2320 cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
Chris Lattner5a866122008-01-13 22:23:22 +00002321 Value *I2 = InsertBitCastBefore(CI->getOperand(0),
Owen Andersonb5618da2009-07-03 00:17:18 +00002322 Context->getPointerType(Type::Int8Ty, AS), I);
Gabor Greife9ecc682008-04-06 20:25:17 +00002323 I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002324 return new PtrToIntInst(I2, CI->getType());
Andrew Lenharth4f339be2006-09-19 18:24:51 +00002325 }
2326 }
Christopher Lamb8b09a462007-12-18 09:34:41 +00002327
Chris Lattner16a51da2007-12-20 01:56:58 +00002328 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb8b09a462007-12-18 09:34:41 +00002329 {
2330 SelectInst *SI = dyn_cast<SelectInst>(LHS);
Chris Lattnerf1be2852008-11-16 04:46:19 +00002331 Value *A = RHS;
Christopher Lamb8b09a462007-12-18 09:34:41 +00002332 if (!SI) {
2333 SI = dyn_cast<SelectInst>(RHS);
Chris Lattnerf1be2852008-11-16 04:46:19 +00002334 A = LHS;
Christopher Lamb8b09a462007-12-18 09:34:41 +00002335 }
Chris Lattner16a51da2007-12-20 01:56:58 +00002336 if (SI && SI->hasOneUse()) {
Christopher Lamb8b09a462007-12-18 09:34:41 +00002337 Value *TV = SI->getTrueValue();
2338 Value *FV = SI->getFalseValue();
Chris Lattnerf1be2852008-11-16 04:46:19 +00002339 Value *N;
Christopher Lamb8b09a462007-12-18 09:34:41 +00002340
2341 // Can we fold the add into the argument of the select?
2342 // We check both true and false select arguments for a matching subtract.
Owen Anderson16e76742009-07-10 17:35:01 +00002343 if (match(FV, m_Zero(), *Context) &&
2344 match(TV, m_Sub(m_Value(N), m_Specific(A)), *Context))
Chris Lattnerf1be2852008-11-16 04:46:19 +00002345 // Fold the add into the true select value.
Gabor Greife9ecc682008-04-06 20:25:17 +00002346 return SelectInst::Create(SI->getCondition(), N, A);
Owen Anderson16e76742009-07-10 17:35:01 +00002347 if (match(TV, m_Zero(), *Context) &&
2348 match(FV, m_Sub(m_Value(N), m_Specific(A)), *Context))
Chris Lattnerf1be2852008-11-16 04:46:19 +00002349 // Fold the add into the false select value.
Gabor Greife9ecc682008-04-06 20:25:17 +00002350 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb8b09a462007-12-18 09:34:41 +00002351 }
2352 }
Andrew Lenharth4f339be2006-09-19 18:24:51 +00002353
Chris Lattner7ac943f2008-05-20 05:46:13 +00002354 // Check for (add (sext x), y), see if we can merge this into an
2355 // integer add followed by a sext.
2356 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2357 // (add (sext x), cst) --> (sext (add x, cst'))
2358 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2359 Constant *CI =
Owen Andersonb5618da2009-07-03 00:17:18 +00002360 Context->getConstantExprTrunc(RHSC, LHSConv->getOperand(0)->getType());
Chris Lattner7ac943f2008-05-20 05:46:13 +00002361 if (LHSConv->hasOneUse() &&
Owen Andersonb5618da2009-07-03 00:17:18 +00002362 Context->getConstantExprSExt(CI, I.getType()) == RHSC &&
Chris Lattner7ac943f2008-05-20 05:46:13 +00002363 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2364 // Insert the new, smaller add.
2365 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2366 CI, "addconv");
2367 InsertNewInstBefore(NewAdd, I);
2368 return new SExtInst(NewAdd, I.getType());
2369 }
2370 }
2371
2372 // (add (sext x), (sext y)) --> (sext (add int x, y))
2373 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2374 // Only do this if x/y have the same type, if at last one of them has a
2375 // single use (so we don't increase the number of sexts), and if the
2376 // integer add will not overflow.
2377 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2378 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2379 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2380 RHSConv->getOperand(0))) {
2381 // Insert the new integer add.
2382 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2383 RHSConv->getOperand(0),
2384 "addconv");
2385 InsertNewInstBefore(NewAdd, I);
2386 return new SExtInst(NewAdd, I.getType());
2387 }
2388 }
2389 }
Dan Gohmana5b96452009-06-04 22:49:04 +00002390
2391 return Changed ? &I : 0;
2392}
2393
2394Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2395 bool Changed = SimplifyCommutative(I);
2396 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2397
2398 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2399 // X + 0 --> X
2400 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Owen Andersonb5618da2009-07-03 00:17:18 +00002401 if (CFP->isExactlyValue(Context->getConstantFPNegativeZero
Dan Gohmana5b96452009-06-04 22:49:04 +00002402 (I.getType())->getValueAPF()))
2403 return ReplaceInstUsesWith(I, LHS);
2404 }
2405
2406 if (isa<PHINode>(LHS))
2407 if (Instruction *NV = FoldOpIntoPhi(I))
2408 return NV;
2409 }
2410
2411 // -A + B --> B - A
2412 // -A + -B --> -(A + B)
Owen Andersonb5618da2009-07-03 00:17:18 +00002413 if (Value *LHSV = dyn_castFNegVal(LHS, Context))
Dan Gohmana5b96452009-06-04 22:49:04 +00002414 return BinaryOperator::CreateFSub(RHS, LHSV);
2415
2416 // A + -B --> A - B
2417 if (!isa<Constant>(RHS))
Owen Andersonb5618da2009-07-03 00:17:18 +00002418 if (Value *V = dyn_castFNegVal(RHS, Context))
Dan Gohmana5b96452009-06-04 22:49:04 +00002419 return BinaryOperator::CreateFSub(LHS, V);
2420
2421 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2422 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2423 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2424 return ReplaceInstUsesWith(I, LHS);
2425
Chris Lattner7ac943f2008-05-20 05:46:13 +00002426 // Check for (add double (sitofp x), y), see if we can merge this into an
2427 // integer add followed by a promotion.
2428 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2429 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2430 // ... if the constant fits in the integer value. This is useful for things
2431 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2432 // requires a constant pool load, and generally allows the add to be better
2433 // instcombined.
2434 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2435 Constant *CI =
Owen Andersonb5618da2009-07-03 00:17:18 +00002436 Context->getConstantExprFPToSI(CFP, LHSConv->getOperand(0)->getType());
Chris Lattner7ac943f2008-05-20 05:46:13 +00002437 if (LHSConv->hasOneUse() &&
Owen Andersonb5618da2009-07-03 00:17:18 +00002438 Context->getConstantExprSIToFP(CI, I.getType()) == CFP &&
Chris Lattner7ac943f2008-05-20 05:46:13 +00002439 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2440 // Insert the new integer add.
2441 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2442 CI, "addconv");
2443 InsertNewInstBefore(NewAdd, I);
2444 return new SIToFPInst(NewAdd, I.getType());
2445 }
2446 }
2447
2448 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2449 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2450 // Only do this if x/y have the same type, if at last one of them has a
2451 // single use (so we don't increase the number of int->fp conversions),
2452 // and if the integer add will not overflow.
2453 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2454 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2455 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2456 RHSConv->getOperand(0))) {
2457 // Insert the new integer add.
2458 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2459 RHSConv->getOperand(0),
2460 "addconv");
2461 InsertNewInstBefore(NewAdd, I);
2462 return new SIToFPInst(NewAdd, I.getType());
2463 }
2464 }
2465 }
2466
Chris Lattner113f4f42002-06-25 16:13:24 +00002467 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00002468}
2469
Chris Lattner113f4f42002-06-25 16:13:24 +00002470Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00002471 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002472
Dan Gohmana5b96452009-06-04 22:49:04 +00002473 if (Op0 == Op1) // sub X, X -> 0
Owen Andersonb5618da2009-07-03 00:17:18 +00002474 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattner260ab202002-04-18 17:39:14 +00002475
Chris Lattnere6794492002-08-12 21:17:25 +00002476 // If this is a 'B = x-(-A)', change to B = x+A...
Owen Andersonb5618da2009-07-03 00:17:18 +00002477 if (Value *V = dyn_castNegVal(Op1, Context))
Gabor Greife1f6e4b2008-05-16 19:29:10 +00002478 return BinaryOperator::CreateAdd(Op0, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +00002479
Chris Lattner81a7a232004-10-16 18:11:37 +00002480 if (isa<UndefValue>(Op0))
2481 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2482 if (isa<UndefValue>(Op1))
2483 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2484
Chris Lattner8f2f5982003-11-05 01:06:05 +00002485 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2486 // Replace (-1 - A) with (~A)...
Chris Lattner3082c5a2003-02-18 19:28:33 +00002487 if (C->isAllOnesValue())
Owen Anderson542619e2009-07-13 20:58:05 +00002488 return BinaryOperator::CreateNot(*Context, Op1);
Chris Lattnerad3c4952002-05-09 01:29:19 +00002489
Chris Lattner8f2f5982003-11-05 01:06:05 +00002490 // C - ~X == X + (1+C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00002491 Value *X = 0;
Owen Anderson16e76742009-07-10 17:35:01 +00002492 if (match(Op1, m_Not(m_Value(X)), *Context))
Owen Andersonb5618da2009-07-03 00:17:18 +00002493 return BinaryOperator::CreateAdd(X, AddOne(C, Context));
Reid Spencer80263aa2007-03-25 05:33:51 +00002494
Chris Lattner27df1db2007-01-15 07:02:54 +00002495 // -(X >>u 31) -> (X >>s 31)
2496 // -(X >>s 31) -> (X >>u 31)
Zhou Shengfd28a332007-03-30 17:20:39 +00002497 if (C->isZero()) {
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +00002498 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Reid Spencerfdff9382006-11-08 06:47:33 +00002499 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002500 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner92295c52004-03-12 23:53:13 +00002501 // Check to see if we are shifting out everything but the sign bit.
Zhou Shengfd28a332007-03-30 17:20:39 +00002502 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencere0fc4df2006-10-20 07:07:24 +00002503 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerfdff9382006-11-08 06:47:33 +00002504 // Ok, the transformation is safe. Insert AShr.
Gabor Greife1f6e4b2008-05-16 19:29:10 +00002505 return BinaryOperator::Create(Instruction::AShr,
Reid Spencer2341c222007-02-02 02:16:23 +00002506 SI->getOperand(0), CU, SI->getName());
Chris Lattner92295c52004-03-12 23:53:13 +00002507 }
2508 }
Reid Spencerfdff9382006-11-08 06:47:33 +00002509 }
2510 else if (SI->getOpcode() == Instruction::AShr) {
2511 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2512 // Check to see if we are shifting out everything but the sign bit.
Zhou Shengfd28a332007-03-30 17:20:39 +00002513 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerfdff9382006-11-08 06:47:33 +00002514 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc635f472006-12-31 05:48:39 +00002515 // Ok, the transformation is safe. Insert LShr.
Gabor Greife1f6e4b2008-05-16 19:29:10 +00002516 return BinaryOperator::CreateLShr(
Reid Spencer2341c222007-02-02 02:16:23 +00002517 SI->getOperand(0), CU, SI->getName());
Reid Spencerfdff9382006-11-08 06:47:33 +00002518 }
2519 }
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +00002520 }
2521 }
Chris Lattner022167f2004-03-13 00:11:49 +00002522 }
Chris Lattner183b3362004-04-09 19:05:30 +00002523
2524 // Try to fold constant sub into select arguments.
2525 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00002526 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002527 return R;
Chris Lattner8f2f5982003-11-05 01:06:05 +00002528 }
2529
Nick Lewycky26b8cd82008-05-31 17:59:52 +00002530 if (I.getType() == Type::Int1Ty)
2531 return BinaryOperator::CreateXor(Op0, Op1);
2532
Chris Lattnera9be4492005-04-07 16:15:25 +00002533 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohmana5b96452009-06-04 22:49:04 +00002534 if (Op1I->getOpcode() == Instruction::Add) {
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00002535 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Owen Anderson53a52212009-07-13 04:09:18 +00002536 return BinaryOperator::CreateNeg(*Context, Op1I->getOperand(1),
2537 I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00002538 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Owen Anderson53a52212009-07-13 04:09:18 +00002539 return BinaryOperator::CreateNeg(*Context, Op1I->getOperand(0),
2540 I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00002541 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2542 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2543 // C1-(X+C2) --> (C1-C2)-X
Owen Andersonb5618da2009-07-03 00:17:18 +00002544 return BinaryOperator::CreateSub(
2545 Context->getConstantExprSub(CI1, CI2), Op1I->getOperand(0));
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00002546 }
Chris Lattnera9be4492005-04-07 16:15:25 +00002547 }
2548
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002549 if (Op1I->hasOneUse()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002550 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2551 // is not used by anyone else...
2552 //
Dan Gohmana5b96452009-06-04 22:49:04 +00002553 if (Op1I->getOpcode() == Instruction::Sub) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002554 // Swap the two operands of the subexpr...
2555 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2556 Op1I->setOperand(0, IIOp1);
2557 Op1I->setOperand(1, IIOp0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002558
Chris Lattner3082c5a2003-02-18 19:28:33 +00002559 // Create the new top level add instruction...
Gabor Greife1f6e4b2008-05-16 19:29:10 +00002560 return BinaryOperator::CreateAdd(Op0, Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002561 }
2562
2563 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2564 //
2565 if (Op1I->getOpcode() == Instruction::And &&
2566 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2567 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2568
Chris Lattner396dbfe2004-06-09 05:08:07 +00002569 Value *NewNot =
Owen Anderson542619e2009-07-13 20:58:05 +00002570 InsertNewInstBefore(BinaryOperator::CreateNot(*Context,
2571 OtherOp, "B.not"), I);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00002572 return BinaryOperator::CreateAnd(Op0, NewNot);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002573 }
Chris Lattner57c8d992003-02-18 19:57:07 +00002574
Reid Spencer3c514952006-10-16 23:08:08 +00002575 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002576 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencere0fc4df2006-10-20 07:07:24 +00002577 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Zhou Shengaafe4e22007-04-19 05:39:12 +00002578 if (CSI->isZero())
Chris Lattner0aee4b72004-10-06 15:08:25 +00002579 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greife1f6e4b2008-05-16 19:29:10 +00002580 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Owen Andersonb5618da2009-07-03 00:17:18 +00002581 Context->getConstantExprNeg(DivRHS));
Chris Lattner0aee4b72004-10-06 15:08:25 +00002582
Chris Lattner57c8d992003-02-18 19:57:07 +00002583 // X - X*C --> X * (1-C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00002584 ConstantInt *C2 = 0;
Owen Andersonb5618da2009-07-03 00:17:18 +00002585 if (dyn_castFoldableMul(Op1I, C2, Context) == Op0) {
2586 Constant *CP1 =
2587 Context->getConstantExprSub(Context->getConstantInt(I.getType(), 1),
Dan Gohman7ccc52f2009-06-15 22:12:54 +00002588 C2);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00002589 return BinaryOperator::CreateMul(Op0, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +00002590 }
Chris Lattnerad3c4952002-05-09 01:29:19 +00002591 }
Chris Lattnera9be4492005-04-07 16:15:25 +00002592 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00002593
Dan Gohmana5b96452009-06-04 22:49:04 +00002594 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2595 if (Op0I->getOpcode() == Instruction::Add) {
2596 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2597 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2598 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2599 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2600 } else if (Op0I->getOpcode() == Instruction::Sub) {
2601 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Owen Anderson53a52212009-07-13 04:09:18 +00002602 return BinaryOperator::CreateNeg(*Context, Op0I->getOperand(1),
2603 I.getName());
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +00002604 }
Dan Gohmana5b96452009-06-04 22:49:04 +00002605 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002606
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002607 ConstantInt *C1;
Owen Andersonb5618da2009-07-03 00:17:18 +00002608 if (Value *X = dyn_castFoldableMul(Op0, C1, Context)) {
Reid Spencer80263aa2007-03-25 05:33:51 +00002609 if (X == Op1) // X*C - X --> X * (C-1)
Owen Andersonb5618da2009-07-03 00:17:18 +00002610 return BinaryOperator::CreateMul(Op1, SubOne(C1, Context));
Chris Lattner57c8d992003-02-18 19:57:07 +00002611
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002612 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
Owen Andersonb5618da2009-07-03 00:17:18 +00002613 if (X == dyn_castFoldableMul(Op1, C2, Context))
2614 return BinaryOperator::CreateMul(X, Context->getConstantExprSub(C1, C2));
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002615 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002616 return 0;
Chris Lattner260ab202002-04-18 17:39:14 +00002617}
2618
Dan Gohmana5b96452009-06-04 22:49:04 +00002619Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2620 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2621
2622 // If this is a 'B = x-(-A)', change to B = x+A...
Owen Andersonb5618da2009-07-03 00:17:18 +00002623 if (Value *V = dyn_castFNegVal(Op1, Context))
Dan Gohmana5b96452009-06-04 22:49:04 +00002624 return BinaryOperator::CreateFAdd(Op0, V);
2625
2626 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2627 if (Op1I->getOpcode() == Instruction::FAdd) {
2628 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Owen Anderson53a52212009-07-13 04:09:18 +00002629 return BinaryOperator::CreateFNeg(*Context, Op1I->getOperand(1),
2630 I.getName());
Dan Gohmana5b96452009-06-04 22:49:04 +00002631 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Owen Anderson53a52212009-07-13 04:09:18 +00002632 return BinaryOperator::CreateFNeg(*Context, Op1I->getOperand(0),
2633 I.getName());
Dan Gohmana5b96452009-06-04 22:49:04 +00002634 }
Dan Gohmana5b96452009-06-04 22:49:04 +00002635 }
2636
2637 return 0;
2638}
2639
Chris Lattner06205d52007-07-15 20:42:37 +00002640/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2641/// comparison only checks the sign bit. If it only checks the sign bit, set
2642/// TrueIfSigned if the result of the comparison is true when the input value is
2643/// signed.
2644static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2645 bool &TrueIfSigned) {
Reid Spencer266e42b2006-12-23 06:05:41 +00002646 switch (pred) {
Chris Lattner06205d52007-07-15 20:42:37 +00002647 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2648 TrueIfSigned = true;
2649 return RHS->isZero();
Chris Lattner640fd512007-07-16 04:15:34 +00002650 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2651 TrueIfSigned = true;
2652 return RHS->isAllOnesValue();
Chris Lattner06205d52007-07-15 20:42:37 +00002653 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2654 TrueIfSigned = false;
2655 return RHS->isAllOnesValue();
Chris Lattner640fd512007-07-16 04:15:34 +00002656 case ICmpInst::ICMP_UGT:
2657 // True if LHS u> RHS and RHS == high-bit-mask - 1
2658 TrueIfSigned = true;
2659 return RHS->getValue() ==
2660 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2661 case ICmpInst::ICMP_UGE:
2662 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2663 TrueIfSigned = true;
Chris Lattnera12a6de2008-06-02 01:29:46 +00002664 return RHS->getValue().isSignBit();
Chris Lattner06205d52007-07-15 20:42:37 +00002665 default:
2666 return false;
Chris Lattnere79e8542004-02-23 06:38:22 +00002667 }
Chris Lattnere79e8542004-02-23 06:38:22 +00002668}
2669
Chris Lattner113f4f42002-06-25 16:13:24 +00002670Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002671 bool Changed = SimplifyCommutative(I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002672 Value *Op0 = I.getOperand(0);
Chris Lattner260ab202002-04-18 17:39:14 +00002673
Dan Gohman7b6b5dd2009-06-04 17:12:12 +00002674 // TODO: If Op1 is undef and Op0 is finite, return zero.
2675 if (!I.getType()->isFPOrFPVector() &&
2676 isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
Owen Andersonb5618da2009-07-03 00:17:18 +00002677 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattner81a7a232004-10-16 18:11:37 +00002678
Chris Lattnere6794492002-08-12 21:17:25 +00002679 // Simplify mul instructions with a constant RHS...
Chris Lattner3082c5a2003-02-18 19:28:33 +00002680 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2681 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerede3fe02003-08-13 04:18:28 +00002682
2683 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer2341c222007-02-02 02:16:23 +00002684 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnerede3fe02003-08-13 04:18:28 +00002685 if (SI->getOpcode() == Instruction::Shl)
2686 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greife1f6e4b2008-05-16 19:29:10 +00002687 return BinaryOperator::CreateMul(SI->getOperand(0),
Owen Andersonb5618da2009-07-03 00:17:18 +00002688 Context->getConstantExprShl(CI, ShOp));
Misha Brukmanb1c93172005-04-21 23:48:37 +00002689
Zhou Shengaafe4e22007-04-19 05:39:12 +00002690 if (CI->isZero())
Chris Lattnercce81be2003-09-11 22:24:54 +00002691 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2692 if (CI->equalsInt(1)) // X * 1 == X
2693 return ReplaceInstUsesWith(I, Op0);
2694 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Owen Anderson53a52212009-07-13 04:09:18 +00002695 return BinaryOperator::CreateNeg(*Context, Op0, I.getName());
Chris Lattner31ba1292002-04-29 22:24:47 +00002696
Zhou Sheng4961cf12007-03-29 01:57:21 +00002697 const APInt& Val = cast<ConstantInt>(CI)->getValue();
Reid Spencer6d392062007-03-23 20:05:17 +00002698 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greife1f6e4b2008-05-16 19:29:10 +00002699 return BinaryOperator::CreateShl(Op0,
Owen Andersonb5618da2009-07-03 00:17:18 +00002700 Context->getConstantInt(Op0->getType(), Val.logBase2()));
Chris Lattner22d00a82005-08-02 19:16:58 +00002701 }
Chris Lattner2aa0ff22008-08-11 22:06:05 +00002702 } else if (isa<VectorType>(Op1->getType())) {
Dan Gohman7b6b5dd2009-06-04 17:12:12 +00002703 // TODO: If Op1 is all zeros and Op0 is all finite, return all zeros.
Nick Lewycky69941fd2008-11-27 20:21:08 +00002704
2705 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2706 if (Op1V->isAllOnesValue()) // X * -1 == 0 - X
Owen Anderson53a52212009-07-13 04:09:18 +00002707 return BinaryOperator::CreateNeg(*Context, Op0, I.getName());
Nick Lewycky69941fd2008-11-27 20:21:08 +00002708
2709 // As above, vector X*splat(1.0) -> X in all defined cases.
2710 if (Constant *Splat = Op1V->getSplatValue()) {
Nick Lewycky69941fd2008-11-27 20:21:08 +00002711 if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2712 if (CI->equalsInt(1))
2713 return ReplaceInstUsesWith(I, Op0);
2714 }
2715 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00002716 }
Chris Lattner32c01df2006-03-04 06:04:02 +00002717
2718 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2719 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattner4b2a7242008-05-18 04:11:26 +00002720 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
Chris Lattner32c01df2006-03-04 06:04:02 +00002721 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Gabor Greife1f6e4b2008-05-16 19:29:10 +00002722 Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
Chris Lattner32c01df2006-03-04 06:04:02 +00002723 Op1, "tmp");
2724 InsertNewInstBefore(Add, I);
Owen Andersonb5618da2009-07-03 00:17:18 +00002725 Value *C1C2 = Context->getConstantExprMul(Op1,
Chris Lattner32c01df2006-03-04 06:04:02 +00002726 cast<Constant>(Op0I->getOperand(1)));
Gabor Greife1f6e4b2008-05-16 19:29:10 +00002727 return BinaryOperator::CreateAdd(Add, C1C2);
Chris Lattner32c01df2006-03-04 06:04:02 +00002728
2729 }
Chris Lattner183b3362004-04-09 19:05:30 +00002730
2731 // Try to fold constant mul into select arguments.
2732 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00002733 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002734 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002735
2736 if (isa<PHINode>(Op0))
2737 if (Instruction *NV = FoldOpIntoPhi(I))
2738 return NV;
Chris Lattner260ab202002-04-18 17:39:14 +00002739 }
2740
Owen Andersonb5618da2009-07-03 00:17:18 +00002741 if (Value *Op0v = dyn_castNegVal(Op0, Context)) // -X * -Y = X*Y
2742 if (Value *Op1v = dyn_castNegVal(I.getOperand(1), Context))
Gabor Greife1f6e4b2008-05-16 19:29:10 +00002743 return BinaryOperator::CreateMul(Op0v, Op1v);
Chris Lattner934a64cf2003-03-10 23:23:04 +00002744
Nick Lewycky07d726e2008-11-21 07:33:58 +00002745 // (X / Y) * Y = X - (X % Y)
2746 // (X / Y) * -Y = (X % Y) - X
2747 {
2748 Value *Op1 = I.getOperand(1);
2749 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2750 if (!BO ||
2751 (BO->getOpcode() != Instruction::UDiv &&
2752 BO->getOpcode() != Instruction::SDiv)) {
2753 Op1 = Op0;
2754 BO = dyn_cast<BinaryOperator>(I.getOperand(1));
2755 }
Owen Andersonb5618da2009-07-03 00:17:18 +00002756 Value *Neg = dyn_castNegVal(Op1, Context);
Nick Lewycky07d726e2008-11-21 07:33:58 +00002757 if (BO && BO->hasOneUse() &&
2758 (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) &&
2759 (BO->getOpcode() == Instruction::UDiv ||
2760 BO->getOpcode() == Instruction::SDiv)) {
2761 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2762
2763 Instruction *Rem;
2764 if (BO->getOpcode() == Instruction::UDiv)
2765 Rem = BinaryOperator::CreateURem(Op0BO, Op1BO);
2766 else
2767 Rem = BinaryOperator::CreateSRem(Op0BO, Op1BO);
2768
2769 InsertNewInstBefore(Rem, I);
2770 Rem->takeName(BO);
2771
2772 if (Op1BO == Op1)
2773 return BinaryOperator::CreateSub(Op0BO, Rem);
2774 else
2775 return BinaryOperator::CreateSub(Rem, Op0BO);
2776 }
2777 }
2778
Nick Lewycky26b8cd82008-05-31 17:59:52 +00002779 if (I.getType() == Type::Int1Ty)
2780 return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2781
Chris Lattner2635b522004-02-23 05:39:21 +00002782 // If one of the operands of the multiply is a cast from a boolean value, then
2783 // we know the bool is either zero or one, so this is a 'masking' multiply.
2784 // See if we can simplify things based on how the boolean was originally
2785 // formed.
2786 CastInst *BoolCast = 0;
Nick Lewycky26b8cd82008-05-31 17:59:52 +00002787 if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
Reid Spencer542964f2007-01-11 18:21:29 +00002788 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattner2635b522004-02-23 05:39:21 +00002789 BoolCast = CI;
2790 if (!BoolCast)
Reid Spencer74a528b2006-12-13 18:21:21 +00002791 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
Reid Spencer542964f2007-01-11 18:21:29 +00002792 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattner2635b522004-02-23 05:39:21 +00002793 BoolCast = CI;
2794 if (BoolCast) {
Reid Spencer266e42b2006-12-23 06:05:41 +00002795 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattner2635b522004-02-23 05:39:21 +00002796 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2797 const Type *SCOpTy = SCIOp0->getType();
Chris Lattner06205d52007-07-15 20:42:37 +00002798 bool TIS = false;
2799
Reid Spencer266e42b2006-12-23 06:05:41 +00002800 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattnere79e8542004-02-23 06:38:22 +00002801 // multiply into a shift/and combination.
2802 if (isa<ConstantInt>(SCIOp1) &&
Chris Lattner06205d52007-07-15 20:42:37 +00002803 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2804 TIS) {
Chris Lattner2635b522004-02-23 05:39:21 +00002805 // Shift the X value right to turn it into "all signbits".
Owen Andersonb5618da2009-07-03 00:17:18 +00002806 Constant *Amt = Context->getConstantInt(SCIOp0->getType(),
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002807 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattnere79e8542004-02-23 06:38:22 +00002808 Value *V =
Reid Spencer2341c222007-02-02 02:16:23 +00002809 InsertNewInstBefore(
Gabor Greife1f6e4b2008-05-16 19:29:10 +00002810 BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
Chris Lattnere79e8542004-02-23 06:38:22 +00002811 BoolCast->getOperand(0)->getName()+
2812 ".mask"), I);
Chris Lattner2635b522004-02-23 05:39:21 +00002813
2814 // If the multiply type is not the same as the source type, sign extend
2815 // or truncate to the multiply type.
Reid Spencer13bc5d72006-12-12 09:18:51 +00002816 if (I.getType() != V->getType()) {
Zhou Sheng56cda952007-04-02 08:20:41 +00002817 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2818 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
Reid Spencer13bc5d72006-12-12 09:18:51 +00002819 Instruction::CastOps opcode =
2820 (SrcBits == DstBits ? Instruction::BitCast :
2821 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2822 V = InsertCastBefore(opcode, V, I.getType(), I);
2823 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002824
Chris Lattner2635b522004-02-23 05:39:21 +00002825 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Gabor Greife1f6e4b2008-05-16 19:29:10 +00002826 return BinaryOperator::CreateAnd(V, OtherOp);
Chris Lattner2635b522004-02-23 05:39:21 +00002827 }
2828 }
2829 }
2830
Chris Lattner113f4f42002-06-25 16:13:24 +00002831 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00002832}
2833
Dan Gohmana5b96452009-06-04 22:49:04 +00002834Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
2835 bool Changed = SimplifyCommutative(I);
2836 Value *Op0 = I.getOperand(0);
2837
2838 // Simplify mul instructions with a constant RHS...
2839 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2840 if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2841 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2842 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2843 if (Op1F->isExactlyValue(1.0))
2844 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2845 } else if (isa<VectorType>(Op1->getType())) {
2846 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2847 // As above, vector X*splat(1.0) -> X in all defined cases.
2848 if (Constant *Splat = Op1V->getSplatValue()) {
2849 if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2850 if (F->isExactlyValue(1.0))
2851 return ReplaceInstUsesWith(I, Op0);
2852 }
2853 }
2854 }
2855
2856 // Try to fold constant mul into select arguments.
2857 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2858 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2859 return R;
2860
2861 if (isa<PHINode>(Op0))
2862 if (Instruction *NV = FoldOpIntoPhi(I))
2863 return NV;
2864 }
2865
Owen Andersonb5618da2009-07-03 00:17:18 +00002866 if (Value *Op0v = dyn_castFNegVal(Op0, Context)) // -X * -Y = X*Y
2867 if (Value *Op1v = dyn_castFNegVal(I.getOperand(1), Context))
Dan Gohmana5b96452009-06-04 22:49:04 +00002868 return BinaryOperator::CreateFMul(Op0v, Op1v);
2869
2870 return Changed ? &I : 0;
2871}
2872
Chris Lattner16395e52008-07-14 00:15:52 +00002873/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2874/// instruction.
2875bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2876 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2877
2878 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2879 int NonNullOperand = -1;
2880 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2881 if (ST->isNullValue())
2882 NonNullOperand = 2;
2883 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2884 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2885 if (ST->isNullValue())
2886 NonNullOperand = 1;
2887
2888 if (NonNullOperand == -1)
2889 return false;
2890
2891 Value *SelectCond = SI->getOperand(0);
2892
2893 // Change the div/rem to use 'Y' instead of the select.
2894 I.setOperand(1, SI->getOperand(NonNullOperand));
2895
2896 // Okay, we know we replace the operand of the div/rem with 'Y' with no
2897 // problem. However, the select, or the condition of the select may have
2898 // multiple uses. Based on our knowledge that the operand must be non-zero,
2899 // propagate the known value for the select into other uses of it, and
2900 // propagate a known value of the condition into its other users.
2901
2902 // If the select and condition only have a single use, don't bother with this,
2903 // early exit.
2904 if (SI->use_empty() && SelectCond->hasOneUse())
2905 return true;
2906
2907 // Scan the current block backward, looking for other uses of SI.
2908 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2909
2910 while (BBI != BBFront) {
2911 --BBI;
2912 // If we found a call to a function, we can't assume it will return, so
2913 // information from below it cannot be propagated above it.
2914 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2915 break;
2916
2917 // Replace uses of the select or its condition with the known values.
2918 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2919 I != E; ++I) {
2920 if (*I == SI) {
2921 *I = SI->getOperand(NonNullOperand);
2922 AddToWorkList(BBI);
2923 } else if (*I == SelectCond) {
Owen Andersonb5618da2009-07-03 00:17:18 +00002924 *I = NonNullOperand == 1 ? Context->getConstantIntTrue() :
2925 Context->getConstantIntFalse();
Chris Lattner16395e52008-07-14 00:15:52 +00002926 AddToWorkList(BBI);
2927 }
2928 }
2929
2930 // If we past the instruction, quit looking for it.
2931 if (&*BBI == SI)
2932 SI = 0;
2933 if (&*BBI == SelectCond)
2934 SelectCond = 0;
2935
2936 // If we ran out of things to eliminate, break out of the loop.
2937 if (SelectCond == 0 && SI == 0)
2938 break;
2939
2940 }
2941 return true;
2942}
2943
2944
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002945/// This function implements the transforms on div instructions that work
2946/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2947/// used by the visitors to those instructions.
2948/// @brief Transforms common to all three div instructions
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002949Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002950 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner81a7a232004-10-16 18:11:37 +00002951
Chris Lattner0fe6bce2008-02-19 06:12:18 +00002952 // undef / X -> 0 for integer.
2953 // undef / X -> undef for FP (the undef could be a snan).
2954 if (isa<UndefValue>(Op0)) {
2955 if (Op0->getType()->isFPOrFPVector())
2956 return ReplaceInstUsesWith(I, Op0);
Owen Andersonb5618da2009-07-03 00:17:18 +00002957 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattner0fe6bce2008-02-19 06:12:18 +00002958 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002959
2960 // X / undef -> undef
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002961 if (isa<UndefValue>(Op1))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002962 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002963
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002964 return 0;
2965}
Misha Brukmanb1c93172005-04-21 23:48:37 +00002966
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002967/// This function implements the transforms common to both integer division
2968/// instructions (udiv and sdiv). It is called by the visitors to those integer
2969/// division instructions.
2970/// @brief Common integer divide transforms
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002971Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002972 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2973
Chris Lattner5c953b72008-05-16 02:59:42 +00002974 // (sdiv X, X) --> 1 (udiv X, X) --> 1
Nick Lewycky2ec9a012008-05-23 03:26:47 +00002975 if (Op0 == Op1) {
2976 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
Owen Andersonb5618da2009-07-03 00:17:18 +00002977 Constant *CI = Context->getConstantInt(Ty->getElementType(), 1);
Nick Lewycky2ec9a012008-05-23 03:26:47 +00002978 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
Owen Andersonb5618da2009-07-03 00:17:18 +00002979 return ReplaceInstUsesWith(I, Context->getConstantVector(Elts));
Nick Lewycky2ec9a012008-05-23 03:26:47 +00002980 }
2981
Owen Andersonb5618da2009-07-03 00:17:18 +00002982 Constant *CI = Context->getConstantInt(I.getType(), 1);
Nick Lewycky2ec9a012008-05-23 03:26:47 +00002983 return ReplaceInstUsesWith(I, CI);
2984 }
Chris Lattner5c953b72008-05-16 02:59:42 +00002985
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002986 if (Instruction *Common = commonDivTransforms(I))
2987 return Common;
Chris Lattner16395e52008-07-14 00:15:52 +00002988
2989 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2990 // This does not apply for fdiv.
2991 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2992 return &I;
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002993
2994 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2995 // div X, 1 == X
2996 if (RHS->equalsInt(1))
2997 return ReplaceInstUsesWith(I, Op0);
2998
2999 // (X / C1) / C2 -> X / (C1*C2)
3000 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
3001 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
3002 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Owen Andersonb5618da2009-07-03 00:17:18 +00003003 if (MultiplyOverflows(RHS, LHSRHS,
3004 I.getOpcode()==Instruction::SDiv, Context))
3005 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Nick Lewyckyfefd0202008-02-18 22:48:05 +00003006 else
Gabor Greife1f6e4b2008-05-16 19:29:10 +00003007 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Owen Andersonb5618da2009-07-03 00:17:18 +00003008 Context->getConstantExprMul(RHS, LHSRHS));
Chris Lattner42362612005-04-08 04:03:26 +00003009 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00003010
Reid Spencer6d392062007-03-23 20:05:17 +00003011 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer7e80b0b2006-10-26 06:15:43 +00003012 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3013 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3014 return R;
3015 if (isa<PHINode>(Op0))
3016 if (Instruction *NV = FoldOpIntoPhi(I))
3017 return NV;
3018 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00003019 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003020
Chris Lattner3082c5a2003-02-18 19:28:33 +00003021 // 0 / X == 0, we don't need to preserve faults!
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00003022 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattner3082c5a2003-02-18 19:28:33 +00003023 if (LHS->equalsInt(0))
Owen Andersonb5618da2009-07-03 00:17:18 +00003024 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattner3082c5a2003-02-18 19:28:33 +00003025
Nick Lewycky26b8cd82008-05-31 17:59:52 +00003026 // It can't be division by zero, hence it must be division by one.
3027 if (I.getType() == Type::Int1Ty)
3028 return ReplaceInstUsesWith(I, Op0);
3029
Nick Lewycky69941fd2008-11-27 20:21:08 +00003030 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
3031 if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
3032 // div X, 1 == X
3033 if (X->isOne())
3034 return ReplaceInstUsesWith(I, Op0);
3035 }
3036
Reid Spencer7e80b0b2006-10-26 06:15:43 +00003037 return 0;
3038}
3039
3040Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3041 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3042
3043 // Handle the integer div common cases
3044 if (Instruction *Common = commonIDivTransforms(I))
3045 return Common;
3046
Reid Spencer7e80b0b2006-10-26 06:15:43 +00003047 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky4ab50b92008-11-27 22:41:10 +00003048 // X udiv C^2 -> X >> C
3049 // Check to see if this is an unsigned division with an exact power of 2,
3050 // if so, convert to a right shift.
Reid Spencer54d5b1b2007-03-26 23:58:26 +00003051 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greife1f6e4b2008-05-16 19:29:10 +00003052 return BinaryOperator::CreateLShr(Op0,
Owen Andersonb5618da2009-07-03 00:17:18 +00003053 Context->getConstantInt(Op0->getType(), C->getValue().logBase2()));
Nick Lewycky4ab50b92008-11-27 22:41:10 +00003054
3055 // X udiv C, where C >= signbit
3056 if (C->getValue().isNegative()) {
Owen Anderson1e5f00e2009-07-09 23:48:35 +00003057 Value *IC = InsertNewInstBefore(new ICmpInst(*Context,
3058 ICmpInst::ICMP_ULT, Op0, C),
Nick Lewycky4ab50b92008-11-27 22:41:10 +00003059 I);
Owen Andersonb5618da2009-07-03 00:17:18 +00003060 return SelectInst::Create(IC, Context->getNullValue(I.getType()),
3061 Context->getConstantInt(I.getType(), 1));
Nick Lewycky4ab50b92008-11-27 22:41:10 +00003062 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00003063 }
3064
3065 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer2341c222007-02-02 02:16:23 +00003066 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00003067 if (RHSI->getOpcode() == Instruction::Shl &&
3068 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng150f3bb2007-04-01 17:13:37 +00003069 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencer6d392062007-03-23 20:05:17 +00003070 if (C1.isPowerOf2()) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00003071 Value *N = RHSI->getOperand(1);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003072 const Type *NTy = N->getType();
Reid Spencer959a21d2007-03-23 21:24:59 +00003073 if (uint32_t C2 = C1.logBase2()) {
Owen Andersonb5618da2009-07-03 00:17:18 +00003074 Constant *C2V = Context->getConstantInt(NTy, C2);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00003075 N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
Chris Lattner2e90b732006-02-05 07:54:04 +00003076 }
Gabor Greife1f6e4b2008-05-16 19:29:10 +00003077 return BinaryOperator::CreateLShr(Op0, N);
Chris Lattner2e90b732006-02-05 07:54:04 +00003078 }
3079 }
Chris Lattnerdd0c1742005-11-05 07:40:31 +00003080 }
3081
Reid Spencer7e80b0b2006-10-26 06:15:43 +00003082 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3083 // where C1&C2 are powers of two.
Reid Spencer3939b1a2007-03-05 23:36:13 +00003084 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00003085 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencer3939b1a2007-03-05 23:36:13 +00003086 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng150f3bb2007-04-01 17:13:37 +00003087 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencer6d392062007-03-23 20:05:17 +00003088 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencer3939b1a2007-03-05 23:36:13 +00003089 // Compute the shift amounts
Reid Spencer6d392062007-03-23 20:05:17 +00003090 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencer3939b1a2007-03-05 23:36:13 +00003091 // Construct the "on true" case of the select
Owen Andersonb5618da2009-07-03 00:17:18 +00003092 Constant *TC = Context->getConstantInt(Op0->getType(), TSA);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00003093 Instruction *TSI = BinaryOperator::CreateLShr(
Reid Spencer3939b1a2007-03-05 23:36:13 +00003094 Op0, TC, SI->getName()+".t");
3095 TSI = InsertNewInstBefore(TSI, I);
3096
3097 // Construct the "on false" case of the select
Owen Andersonb5618da2009-07-03 00:17:18 +00003098 Constant *FC = Context->getConstantInt(Op0->getType(), FSA);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00003099 Instruction *FSI = BinaryOperator::CreateLShr(
Reid Spencer3939b1a2007-03-05 23:36:13 +00003100 Op0, FC, SI->getName()+".f");
3101 FSI = InsertNewInstBefore(FSI, I);
Reid Spencer7e80b0b2006-10-26 06:15:43 +00003102
Reid Spencer3939b1a2007-03-05 23:36:13 +00003103 // construct the select instruction and return it.
Gabor Greife9ecc682008-04-06 20:25:17 +00003104 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer7e80b0b2006-10-26 06:15:43 +00003105 }
Reid Spencer3939b1a2007-03-05 23:36:13 +00003106 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003107 return 0;
3108}
3109
Reid Spencer7e80b0b2006-10-26 06:15:43 +00003110Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3111 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3112
3113 // Handle the integer div common cases
3114 if (Instruction *Common = commonIDivTransforms(I))
3115 return Common;
3116
3117 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3118 // sdiv X, -1 == -X
3119 if (RHS->isAllOnesValue())
Owen Anderson53a52212009-07-13 04:09:18 +00003120 return BinaryOperator::CreateNeg(*Context, Op0);
Reid Spencer7e80b0b2006-10-26 06:15:43 +00003121 }
3122
3123 // If the sign bits of both operands are zero (i.e. we can prove they are
3124 // unsigned inputs), turn this into a udiv.
Chris Lattner03c49532007-01-15 02:27:26 +00003125 if (I.getType()->isInteger()) {
Reid Spencer6d392062007-03-23 20:05:17 +00003126 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00003127 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Dan Gohman4decbc52007-11-05 23:16:33 +00003128 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
Gabor Greife1f6e4b2008-05-16 19:29:10 +00003129 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
Reid Spencer7e80b0b2006-10-26 06:15:43 +00003130 }
3131 }
3132
3133 return 0;
3134}
3135
3136Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3137 return commonDivTransforms(I);
3138}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003139
Reid Spencer7eb55b32006-11-02 01:53:59 +00003140/// This function implements the transforms on rem instructions that work
3141/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3142/// is used by the visitors to those instructions.
3143/// @brief Transforms common to all three rem instructions
3144Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00003145 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer7eb55b32006-11-02 01:53:59 +00003146
Chris Lattner0fe6bce2008-02-19 06:12:18 +00003147 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3148 if (I.getType()->isFPOrFPVector())
3149 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Owen Andersonb5618da2009-07-03 00:17:18 +00003150 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattner0fe6bce2008-02-19 06:12:18 +00003151 }
Chris Lattner0de4a8d2006-02-28 05:30:45 +00003152 if (isa<UndefValue>(Op1))
3153 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer7eb55b32006-11-02 01:53:59 +00003154
3155 // Handle cases involving: rem X, (select Cond, Y, Z)
Chris Lattner16395e52008-07-14 00:15:52 +00003156 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3157 return &I;
Chris Lattner7fd5f072004-07-06 07:01:22 +00003158
Reid Spencer7eb55b32006-11-02 01:53:59 +00003159 return 0;
3160}
3161
3162/// This function implements the transforms common to both integer remainder
3163/// instructions (urem and srem). It is called by the visitors to those integer
3164/// remainder instructions.
3165/// @brief Common integer remainder transforms
3166Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3167 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3168
3169 if (Instruction *common = commonRemTransforms(I))
3170 return common;
3171
Dale Johannesenb5721632009-01-21 00:35:19 +00003172 // 0 % X == 0 for integer, we don't need to preserve faults!
3173 if (Constant *LHS = dyn_cast<Constant>(Op0))
3174 if (LHS->isNullValue())
Owen Andersonb5618da2009-07-03 00:17:18 +00003175 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Dale Johannesenb5721632009-01-21 00:35:19 +00003176
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00003177 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner0de4a8d2006-02-28 05:30:45 +00003178 // X % 0 == undef, we don't need to preserve faults!
3179 if (RHS->equalsInt(0))
Owen Andersonb5618da2009-07-03 00:17:18 +00003180 return ReplaceInstUsesWith(I, Context->getUndef(I.getType()));
Chris Lattner0de4a8d2006-02-28 05:30:45 +00003181
Chris Lattner3082c5a2003-02-18 19:28:33 +00003182 if (RHS->equalsInt(1)) // X % 1 == 0
Owen Andersonb5618da2009-07-03 00:17:18 +00003183 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattner3082c5a2003-02-18 19:28:33 +00003184
Chris Lattnerb70f1412006-02-28 05:49:21 +00003185 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3186 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3187 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3188 return R;
3189 } else if (isa<PHINode>(Op0I)) {
3190 if (Instruction *NV = FoldOpIntoPhi(I))
3191 return NV;
Chris Lattnerb70f1412006-02-28 05:49:21 +00003192 }
Nick Lewyckyd0b62a12008-03-06 06:48:30 +00003193
3194 // See if we can fold away this rem instruction.
Chris Lattner83c6a142009-01-31 08:15:18 +00003195 if (SimplifyDemandedInstructionBits(I))
Nick Lewyckyd0b62a12008-03-06 06:48:30 +00003196 return &I;
Chris Lattnerb70f1412006-02-28 05:49:21 +00003197 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00003198 }
3199
Reid Spencer7eb55b32006-11-02 01:53:59 +00003200 return 0;
3201}
3202
3203Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3204 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3205
3206 if (Instruction *common = commonIRemTransforms(I))
3207 return common;
3208
3209 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3210 // X urem C^2 -> X and C
3211 // Check to see if this is an unsigned remainder with an exact power of 2,
3212 // if so, convert to a bitwise and.
3213 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencer6d392062007-03-23 20:05:17 +00003214 if (C->getValue().isPowerOf2())
Owen Andersonb5618da2009-07-03 00:17:18 +00003215 return BinaryOperator::CreateAnd(Op0, SubOne(C, Context));
Reid Spencer7eb55b32006-11-02 01:53:59 +00003216 }
3217
Chris Lattner2e90b732006-02-05 07:54:04 +00003218 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00003219 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3220 if (RHSI->getOpcode() == Instruction::Shl &&
3221 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng222d5eb2007-03-25 05:01:29 +00003222 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Owen Anderson542619e2009-07-13 20:58:05 +00003223 Constant *N1 = Context->getAllOnesValue(I.getType());
Gabor Greife1f6e4b2008-05-16 19:29:10 +00003224 Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
Chris Lattner2e90b732006-02-05 07:54:04 +00003225 "tmp"), I);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00003226 return BinaryOperator::CreateAnd(Op0, Add);
Chris Lattner2e90b732006-02-05 07:54:04 +00003227 }
3228 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00003229 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00003230
Reid Spencer7eb55b32006-11-02 01:53:59 +00003231 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3232 // where C1&C2 are powers of two.
3233 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3234 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3235 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3236 // STO == 0 and SFO == 0 handled above.
Reid Spencer6d392062007-03-23 20:05:17 +00003237 if ((STO->getValue().isPowerOf2()) &&
3238 (SFO->getValue().isPowerOf2())) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00003239 Value *TrueAnd = InsertNewInstBefore(
Owen Andersonb5618da2009-07-03 00:17:18 +00003240 BinaryOperator::CreateAnd(Op0, SubOne(STO, Context),
3241 SI->getName()+".t"), I);
Reid Spencer7eb55b32006-11-02 01:53:59 +00003242 Value *FalseAnd = InsertNewInstBefore(
Owen Andersonb5618da2009-07-03 00:17:18 +00003243 BinaryOperator::CreateAnd(Op0, SubOne(SFO, Context),
3244 SI->getName()+".f"), I);
Gabor Greife9ecc682008-04-06 20:25:17 +00003245 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Reid Spencer7eb55b32006-11-02 01:53:59 +00003246 }
3247 }
Chris Lattner2e90b732006-02-05 07:54:04 +00003248 }
3249
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003250 return 0;
3251}
3252
Reid Spencer7eb55b32006-11-02 01:53:59 +00003253Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3254 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3255
Dan Gohman4decbc52007-11-05 23:16:33 +00003256 // Handle the integer rem common cases
Reid Spencer7eb55b32006-11-02 01:53:59 +00003257 if (Instruction *common = commonIRemTransforms(I))
3258 return common;
3259
Owen Andersonb5618da2009-07-03 00:17:18 +00003260 if (Value *RHSNeg = dyn_castNegVal(Op1, Context))
Nick Lewycky2fcb26c2008-09-03 06:24:21 +00003261 if (!isa<Constant>(RHSNeg) ||
3262 (isa<ConstantInt>(RHSNeg) &&
3263 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00003264 // X % -Y -> X % Y
3265 AddUsesToWorkList(I);
3266 I.setOperand(1, RHSNeg);
3267 return &I;
3268 }
Nick Lewyckye8ced3e2008-09-30 06:08:34 +00003269
Dan Gohman4decbc52007-11-05 23:16:33 +00003270 // If the sign bits of both operands are zero (i.e. we can prove they are
Reid Spencer7eb55b32006-11-02 01:53:59 +00003271 // unsigned inputs), turn this into a urem.
Dan Gohman4decbc52007-11-05 23:16:33 +00003272 if (I.getType()->isInteger()) {
3273 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3274 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3275 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greife1f6e4b2008-05-16 19:29:10 +00003276 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohman4decbc52007-11-05 23:16:33 +00003277 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00003278 }
3279
Nick Lewycky0f0e63f2008-12-18 06:31:11 +00003280 // If it's a constant vector, flip any negative values positive.
Nick Lewycky4bc10c92008-12-20 16:48:00 +00003281 if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3282 unsigned VWidth = RHSV->getNumOperands();
Nick Lewycky0f0e63f2008-12-18 06:31:11 +00003283
Nick Lewycky4bc10c92008-12-20 16:48:00 +00003284 bool hasNegative = false;
3285 for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3286 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3287 if (RHS->getValue().isNegative())
3288 hasNegative = true;
3289
3290 if (hasNegative) {
3291 std::vector<Constant *> Elts(VWidth);
Nick Lewycky0f0e63f2008-12-18 06:31:11 +00003292 for (unsigned i = 0; i != VWidth; ++i) {
3293 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3294 if (RHS->getValue().isNegative())
Owen Andersonb5618da2009-07-03 00:17:18 +00003295 Elts[i] = cast<ConstantInt>(Context->getConstantExprNeg(RHS));
Nick Lewycky0f0e63f2008-12-18 06:31:11 +00003296 else
3297 Elts[i] = RHS;
3298 }
3299 }
3300
Owen Andersonb5618da2009-07-03 00:17:18 +00003301 Constant *NewRHSV = Context->getConstantVector(Elts);
Nick Lewycky0f0e63f2008-12-18 06:31:11 +00003302 if (NewRHSV != RHSV) {
Nick Lewyckyc3a70ad2008-12-18 06:42:28 +00003303 AddUsesToWorkList(I);
Nick Lewycky0f0e63f2008-12-18 06:31:11 +00003304 I.setOperand(1, NewRHSV);
3305 return &I;
3306 }
3307 }
3308 }
3309
Reid Spencer7eb55b32006-11-02 01:53:59 +00003310 return 0;
3311}
3312
3313Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00003314 return commonRemTransforms(I);
3315}
3316
Chris Lattner35167c32004-06-09 07:59:58 +00003317// isOneBitSet - Return true if there is exactly one bit set in the specified
3318// constant.
3319static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer66827212007-03-20 00:16:52 +00003320 return CI->getValue().isPowerOf2();
Chris Lattner35167c32004-06-09 07:59:58 +00003321}
3322
Chris Lattner8fc5af42004-09-23 21:46:38 +00003323// isHighOnes - Return true if the constant is of the form 1+0+.
3324// This is the same as lowones(~X).
3325static bool isHighOnes(const ConstantInt *CI) {
Zhou Shengb3949342007-03-20 12:49:06 +00003326 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattner8fc5af42004-09-23 21:46:38 +00003327}
3328
Reid Spencer266e42b2006-12-23 06:05:41 +00003329/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattner3ac7c262003-08-13 20:16:26 +00003330/// are carefully arranged to allow folding of expressions such as:
3331///
3332/// (A < B) | (A > B) --> (A != B)
3333///
Reid Spencer266e42b2006-12-23 06:05:41 +00003334/// Note that this is only valid if the first and second predicates have the
3335/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattner3ac7c262003-08-13 20:16:26 +00003336///
Reid Spencer266e42b2006-12-23 06:05:41 +00003337/// Three bits are used to represent the condition, as follows:
3338/// 0 A > B
3339/// 1 A == B
3340/// 2 A < B
3341///
3342/// <=> Value Definition
3343/// 000 0 Always false
3344/// 001 1 A > B
3345/// 010 2 A == B
3346/// 011 3 A >= B
3347/// 100 4 A < B
3348/// 101 5 A != B
3349/// 110 6 A <= B
3350/// 111 7 Always true
3351///
3352static unsigned getICmpCode(const ICmpInst *ICI) {
3353 switch (ICI->getPredicate()) {
Chris Lattner3ac7c262003-08-13 20:16:26 +00003354 // False -> 0
Reid Spencer266e42b2006-12-23 06:05:41 +00003355 case ICmpInst::ICMP_UGT: return 1; // 001
3356 case ICmpInst::ICMP_SGT: return 1; // 001
3357 case ICmpInst::ICMP_EQ: return 2; // 010
3358 case ICmpInst::ICMP_UGE: return 3; // 011
3359 case ICmpInst::ICMP_SGE: return 3; // 011
3360 case ICmpInst::ICMP_ULT: return 4; // 100
3361 case ICmpInst::ICMP_SLT: return 4; // 100
3362 case ICmpInst::ICMP_NE: return 5; // 101
3363 case ICmpInst::ICMP_ULE: return 6; // 110
3364 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattner3ac7c262003-08-13 20:16:26 +00003365 // True -> 7
3366 default:
Torok Edwin56d06592009-07-11 20:10:48 +00003367 LLVM_UNREACHABLE("Invalid ICmp predicate!");
Chris Lattner3ac7c262003-08-13 20:16:26 +00003368 return 0;
3369 }
3370}
3371
Evan Cheng67786cc2008-10-14 17:15:11 +00003372/// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3373/// predicate into a three bit mask. It also returns whether it is an ordered
3374/// predicate by reference.
3375static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3376 isOrdered = false;
3377 switch (CC) {
3378 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
3379 case FCmpInst::FCMP_UNO: return 0; // 000
Evan Chengce707522008-10-14 18:13:38 +00003380 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
3381 case FCmpInst::FCMP_UGT: return 1; // 001
3382 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
3383 case FCmpInst::FCMP_UEQ: return 2; // 010
Evan Cheng67786cc2008-10-14 17:15:11 +00003384 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
3385 case FCmpInst::FCMP_UGE: return 3; // 011
3386 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
3387 case FCmpInst::FCMP_ULT: return 4; // 100
Evan Chengce707522008-10-14 18:13:38 +00003388 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
3389 case FCmpInst::FCMP_UNE: return 5; // 101
Evan Cheng67786cc2008-10-14 17:15:11 +00003390 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
3391 case FCmpInst::FCMP_ULE: return 6; // 110
Evan Chengd885f6e2008-10-14 18:44:08 +00003392 // True -> 7
Evan Cheng67786cc2008-10-14 17:15:11 +00003393 default:
3394 // Not expecting FCMP_FALSE and FCMP_TRUE;
Torok Edwin56d06592009-07-11 20:10:48 +00003395 LLVM_UNREACHABLE("Unexpected FCmp predicate!");
Evan Cheng67786cc2008-10-14 17:15:11 +00003396 return 0;
3397 }
3398}
3399
Reid Spencer266e42b2006-12-23 06:05:41 +00003400/// getICmpValue - This is the complement of getICmpCode, which turns an
3401/// opcode and two operands into either a constant true or false, or a brand
Dan Gohman2ac26522007-09-17 17:31:57 +00003402/// new ICmp instruction. The sign is passed in to determine which kind
Evan Cheng67786cc2008-10-14 17:15:11 +00003403/// of predicate to use in the new icmp instruction.
Owen Andersonb5618da2009-07-03 00:17:18 +00003404static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
Owen Anderson38264b12009-07-06 23:00:19 +00003405 LLVMContext *Context) {
Reid Spencer266e42b2006-12-23 06:05:41 +00003406 switch (code) {
Torok Edwin56d06592009-07-11 20:10:48 +00003407 default: LLVM_UNREACHABLE("Illegal ICmp code!");
Owen Andersonb5618da2009-07-03 00:17:18 +00003408 case 0: return Context->getConstantIntFalse();
Reid Spencer266e42b2006-12-23 06:05:41 +00003409 case 1:
3410 if (sign)
Owen Anderson1e5f00e2009-07-09 23:48:35 +00003411 return new ICmpInst(*Context, ICmpInst::ICMP_SGT, LHS, RHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003412 else
Owen Anderson1e5f00e2009-07-09 23:48:35 +00003413 return new ICmpInst(*Context, ICmpInst::ICMP_UGT, LHS, RHS);
3414 case 2: return new ICmpInst(*Context, ICmpInst::ICMP_EQ, LHS, RHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003415 case 3:
3416 if (sign)
Owen Anderson1e5f00e2009-07-09 23:48:35 +00003417 return new ICmpInst(*Context, ICmpInst::ICMP_SGE, LHS, RHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003418 else
Owen Anderson1e5f00e2009-07-09 23:48:35 +00003419 return new ICmpInst(*Context, ICmpInst::ICMP_UGE, LHS, RHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003420 case 4:
3421 if (sign)
Owen Anderson1e5f00e2009-07-09 23:48:35 +00003422 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, LHS, RHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003423 else
Owen Anderson1e5f00e2009-07-09 23:48:35 +00003424 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, LHS, RHS);
3425 case 5: return new ICmpInst(*Context, ICmpInst::ICMP_NE, LHS, RHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003426 case 6:
3427 if (sign)
Owen Anderson1e5f00e2009-07-09 23:48:35 +00003428 return new ICmpInst(*Context, ICmpInst::ICMP_SLE, LHS, RHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003429 else
Owen Anderson1e5f00e2009-07-09 23:48:35 +00003430 return new ICmpInst(*Context, ICmpInst::ICMP_ULE, LHS, RHS);
Owen Andersonb5618da2009-07-03 00:17:18 +00003431 case 7: return Context->getConstantIntTrue();
Chris Lattner3ac7c262003-08-13 20:16:26 +00003432 }
3433}
3434
Evan Cheng67786cc2008-10-14 17:15:11 +00003435/// getFCmpValue - This is the complement of getFCmpCode, which turns an
3436/// opcode and two operands into either a FCmp instruction. isordered is passed
3437/// in to determine which kind of predicate to use in the new fcmp instruction.
3438static Value *getFCmpValue(bool isordered, unsigned code,
Owen Anderson38264b12009-07-06 23:00:19 +00003439 Value *LHS, Value *RHS, LLVMContext *Context) {
Evan Cheng67786cc2008-10-14 17:15:11 +00003440 switch (code) {
Torok Edwin56d06592009-07-11 20:10:48 +00003441 default: LLVM_UNREACHABLE("Illegal FCmp code!");
Evan Cheng67786cc2008-10-14 17:15:11 +00003442 case 0:
3443 if (isordered)
Owen Anderson1e5f00e2009-07-09 23:48:35 +00003444 return new FCmpInst(*Context, FCmpInst::FCMP_ORD, LHS, RHS);
Evan Cheng67786cc2008-10-14 17:15:11 +00003445 else
Owen Anderson1e5f00e2009-07-09 23:48:35 +00003446 return new FCmpInst(*Context, FCmpInst::FCMP_UNO, LHS, RHS);
Evan Cheng67786cc2008-10-14 17:15:11 +00003447 case 1:
3448 if (isordered)
Owen Anderson1e5f00e2009-07-09 23:48:35 +00003449 return new FCmpInst(*Context, FCmpInst::FCMP_OGT, LHS, RHS);
Evan Cheng67786cc2008-10-14 17:15:11 +00003450 else
Owen Anderson1e5f00e2009-07-09 23:48:35 +00003451 return new FCmpInst(*Context, FCmpInst::FCMP_UGT, LHS, RHS);
Evan Chengce707522008-10-14 18:13:38 +00003452 case 2:
3453 if (isordered)
Owen Anderson1e5f00e2009-07-09 23:48:35 +00003454 return new FCmpInst(*Context, FCmpInst::FCMP_OEQ, LHS, RHS);
Evan Chengce707522008-10-14 18:13:38 +00003455 else
Owen Anderson1e5f00e2009-07-09 23:48:35 +00003456 return new FCmpInst(*Context, FCmpInst::FCMP_UEQ, LHS, RHS);
Evan Cheng67786cc2008-10-14 17:15:11 +00003457 case 3:
3458 if (isordered)
Owen Anderson1e5f00e2009-07-09 23:48:35 +00003459 return new FCmpInst(*Context, FCmpInst::FCMP_OGE, LHS, RHS);
Evan Cheng67786cc2008-10-14 17:15:11 +00003460 else
Owen Anderson1e5f00e2009-07-09 23:48:35 +00003461 return new FCmpInst(*Context, FCmpInst::FCMP_UGE, LHS, RHS);
Evan Cheng67786cc2008-10-14 17:15:11 +00003462 case 4:
3463 if (isordered)
Owen Anderson1e5f00e2009-07-09 23:48:35 +00003464 return new FCmpInst(*Context, FCmpInst::FCMP_OLT, LHS, RHS);
Evan Cheng67786cc2008-10-14 17:15:11 +00003465 else
Owen Anderson1e5f00e2009-07-09 23:48:35 +00003466 return new FCmpInst(*Context, FCmpInst::FCMP_ULT, LHS, RHS);
Evan Cheng67786cc2008-10-14 17:15:11 +00003467 case 5:
3468 if (isordered)
Owen Anderson1e5f00e2009-07-09 23:48:35 +00003469 return new FCmpInst(*Context, FCmpInst::FCMP_ONE, LHS, RHS);
Evan Chengce707522008-10-14 18:13:38 +00003470 else
Owen Anderson1e5f00e2009-07-09 23:48:35 +00003471 return new FCmpInst(*Context, FCmpInst::FCMP_UNE, LHS, RHS);
Evan Chengce707522008-10-14 18:13:38 +00003472 case 6:
3473 if (isordered)
Owen Anderson1e5f00e2009-07-09 23:48:35 +00003474 return new FCmpInst(*Context, FCmpInst::FCMP_OLE, LHS, RHS);
Evan Cheng67786cc2008-10-14 17:15:11 +00003475 else
Owen Anderson1e5f00e2009-07-09 23:48:35 +00003476 return new FCmpInst(*Context, FCmpInst::FCMP_ULE, LHS, RHS);
Owen Andersonb5618da2009-07-03 00:17:18 +00003477 case 7: return Context->getConstantIntTrue();
Evan Cheng67786cc2008-10-14 17:15:11 +00003478 }
3479}
3480
Chris Lattnerb37b6e72008-11-16 04:55:20 +00003481/// PredicatesFoldable - Return true if both predicates match sign or if at
3482/// least one of them is an equality comparison (which is signless).
Reid Spencer266e42b2006-12-23 06:05:41 +00003483static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3484 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
Chris Lattnerb37b6e72008-11-16 04:55:20 +00003485 (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3486 (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
Reid Spencer266e42b2006-12-23 06:05:41 +00003487}
3488
3489namespace {
3490// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3491struct FoldICmpLogical {
Chris Lattner3ac7c262003-08-13 20:16:26 +00003492 InstCombiner &IC;
3493 Value *LHS, *RHS;
Reid Spencer266e42b2006-12-23 06:05:41 +00003494 ICmpInst::Predicate pred;
3495 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3496 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3497 pred(ICI->getPredicate()) {}
Chris Lattner3ac7c262003-08-13 20:16:26 +00003498 bool shouldApply(Value *V) const {
Reid Spencer266e42b2006-12-23 06:05:41 +00003499 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3500 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +00003501 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3502 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Chris Lattner3ac7c262003-08-13 20:16:26 +00003503 return false;
3504 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003505 Instruction *apply(Instruction &Log) const {
3506 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3507 if (ICI->getOperand(0) != LHS) {
3508 assert(ICI->getOperand(1) == LHS);
3509 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattner3ac7c262003-08-13 20:16:26 +00003510 }
3511
Chris Lattnerd1bce952007-03-13 14:27:42 +00003512 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencer266e42b2006-12-23 06:05:41 +00003513 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerd1bce952007-03-13 14:27:42 +00003514 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattner3ac7c262003-08-13 20:16:26 +00003515 unsigned Code;
3516 switch (Log.getOpcode()) {
3517 case Instruction::And: Code = LHSCode & RHSCode; break;
3518 case Instruction::Or: Code = LHSCode | RHSCode; break;
3519 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Torok Edwin56d06592009-07-11 20:10:48 +00003520 default: LLVM_UNREACHABLE("Illegal logical opcode!"); return 0;
Chris Lattner3ac7c262003-08-13 20:16:26 +00003521 }
3522
Chris Lattnerd1bce952007-03-13 14:27:42 +00003523 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3524 ICmpInst::isSignedPredicate(ICI->getPredicate());
3525
Owen Andersonb5618da2009-07-03 00:17:18 +00003526 Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
Chris Lattner3ac7c262003-08-13 20:16:26 +00003527 if (Instruction *I = dyn_cast<Instruction>(RV))
3528 return I;
3529 // Otherwise, it's a constant boolean value...
3530 return IC.ReplaceInstUsesWith(Log, RV);
3531 }
3532};
Chris Lattnere3a63d12006-11-15 04:53:24 +00003533} // end anonymous namespace
Chris Lattner3ac7c262003-08-13 20:16:26 +00003534
Chris Lattnerba1cb382003-09-19 17:17:26 +00003535// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3536// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer2341c222007-02-02 02:16:23 +00003537// guaranteed to be a binary operator.
Chris Lattnerba1cb382003-09-19 17:17:26 +00003538Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng75b871f2007-01-11 12:24:14 +00003539 ConstantInt *OpRHS,
3540 ConstantInt *AndRHS,
Chris Lattnerba1cb382003-09-19 17:17:26 +00003541 BinaryOperator &TheAnd) {
3542 Value *X = Op->getOperand(0);
Chris Lattnerfcf21a72004-01-12 19:47:05 +00003543 Constant *Together = 0;
Reid Spencer2341c222007-02-02 02:16:23 +00003544 if (!Op->isShift())
Owen Andersonb5618da2009-07-03 00:17:18 +00003545 Together = Context->getConstantExprAnd(AndRHS, OpRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003546
Chris Lattnerba1cb382003-09-19 17:17:26 +00003547 switch (Op->getOpcode()) {
3548 case Instruction::Xor:
Chris Lattner86102b82005-01-01 16:22:27 +00003549 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00003550 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Gabor Greife1f6e4b2008-05-16 19:29:10 +00003551 Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00003552 InsertNewInstBefore(And, TheAnd);
Chris Lattner6e0123b2007-02-11 01:23:03 +00003553 And->takeName(Op);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00003554 return BinaryOperator::CreateXor(And, Together);
Chris Lattnerba1cb382003-09-19 17:17:26 +00003555 }
3556 break;
3557 case Instruction::Or:
Chris Lattner86102b82005-01-01 16:22:27 +00003558 if (Together == AndRHS) // (X | C) & C --> C
3559 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003560
Chris Lattner86102b82005-01-01 16:22:27 +00003561 if (Op->hasOneUse() && Together != OpRHS) {
3562 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Gabor Greife1f6e4b2008-05-16 19:29:10 +00003563 Instruction *Or = BinaryOperator::CreateOr(X, Together);
Chris Lattner86102b82005-01-01 16:22:27 +00003564 InsertNewInstBefore(Or, TheAnd);
Chris Lattner6e0123b2007-02-11 01:23:03 +00003565 Or->takeName(Op);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00003566 return BinaryOperator::CreateAnd(Or, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00003567 }
3568 break;
3569 case Instruction::Add:
Chris Lattnerf95d9b92003-10-15 16:48:29 +00003570 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00003571 // Adding a one to a single bit bit-field should be turned into an XOR
3572 // of the bit. First thing to check is to see if this AND is with a
3573 // single bit constant.
Zhou Sheng150f3bb2007-04-01 17:13:37 +00003574 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00003575
3576 // If there is only one bit set...
Chris Lattner35167c32004-06-09 07:59:58 +00003577 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00003578 // Ok, at this point, we know that we are masking the result of the
3579 // ADD down to exactly one bit. If the constant we are adding has
3580 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng150f3bb2007-04-01 17:13:37 +00003581 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00003582
Chris Lattnerba1cb382003-09-19 17:17:26 +00003583 // Check to see if any bits below the one bit set in AndRHSV are set.
3584 if ((AddRHS & (AndRHSV-1)) == 0) {
3585 // If not, the only thing that can effect the output of the AND is
3586 // the bit specified by AndRHSV. If that bit is set, the effect of
3587 // the XOR is to toggle the bit. If it is clear, then the ADD has
3588 // no effect.
3589 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3590 TheAnd.setOperand(0, X);
3591 return &TheAnd;
3592 } else {
Chris Lattnerba1cb382003-09-19 17:17:26 +00003593 // Pull the XOR out of the AND.
Gabor Greife1f6e4b2008-05-16 19:29:10 +00003594 Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00003595 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner6e0123b2007-02-11 01:23:03 +00003596 NewAnd->takeName(Op);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00003597 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00003598 }
3599 }
3600 }
3601 }
3602 break;
Chris Lattner2da29172003-09-19 19:05:02 +00003603
3604 case Instruction::Shl: {
3605 // We know that the AND will not produce any of the bits shifted in, so if
3606 // the anded constant includes them, clear them now!
3607 //
Zhou Shengb3a80b12007-03-29 08:15:12 +00003608 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Shengb25806f2007-03-30 09:29:48 +00003609 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Shengb3a80b12007-03-29 08:15:12 +00003610 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
Owen Andersonb5618da2009-07-03 00:17:18 +00003611 ConstantInt *CI = Context->getConstantInt(AndRHS->getValue() & ShlMask);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003612
Zhou Shengb3a80b12007-03-29 08:15:12 +00003613 if (CI->getValue() == ShlMask) {
3614 // Masking out bits that the shift already masks
Chris Lattner7e794272004-09-24 15:21:34 +00003615 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3616 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner2da29172003-09-19 19:05:02 +00003617 TheAnd.setOperand(1, CI);
3618 return &TheAnd;
3619 }
3620 break;
Misha Brukmanb1c93172005-04-21 23:48:37 +00003621 }
Reid Spencerfdff9382006-11-08 06:47:33 +00003622 case Instruction::LShr:
3623 {
Chris Lattner2da29172003-09-19 19:05:02 +00003624 // We know that the AND will not produce any of the bits shifted in, so if
3625 // the anded constant includes them, clear them now! This only applies to
3626 // unsigned shifts, because a signed shr may bring in set bits!
3627 //
Zhou Shengb3a80b12007-03-29 08:15:12 +00003628 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Shengb25806f2007-03-30 09:29:48 +00003629 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Shengb3a80b12007-03-29 08:15:12 +00003630 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersonb5618da2009-07-03 00:17:18 +00003631 ConstantInt *CI = Context->getConstantInt(AndRHS->getValue() & ShrMask);
Chris Lattner7e794272004-09-24 15:21:34 +00003632
Zhou Shengb3a80b12007-03-29 08:15:12 +00003633 if (CI->getValue() == ShrMask) {
3634 // Masking out bits that the shift already masks.
Reid Spencerfdff9382006-11-08 06:47:33 +00003635 return ReplaceInstUsesWith(TheAnd, Op);
3636 } else if (CI != AndRHS) {
3637 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3638 return &TheAnd;
3639 }
3640 break;
3641 }
3642 case Instruction::AShr:
3643 // Signed shr.
3644 // See if this is shifting in some sign extension, then masking it out
3645 // with an and.
3646 if (Op->hasOneUse()) {
Zhou Shengb3a80b12007-03-29 08:15:12 +00003647 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Shengb25806f2007-03-30 09:29:48 +00003648 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Shengb3a80b12007-03-29 08:15:12 +00003649 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersonb5618da2009-07-03 00:17:18 +00003650 Constant *C = Context->getConstantInt(AndRHS->getValue() & ShrMask);
Reid Spencer2a499b02006-12-13 17:19:09 +00003651 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer13bc5d72006-12-12 09:18:51 +00003652 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencerfdff9382006-11-08 06:47:33 +00003653 // Make the argument unsigned.
3654 Value *ShVal = Op->getOperand(0);
Reid Spencer2341c222007-02-02 02:16:23 +00003655 ShVal = InsertNewInstBefore(
Gabor Greife1f6e4b2008-05-16 19:29:10 +00003656 BinaryOperator::CreateLShr(ShVal, OpRHS,
Reid Spencer2341c222007-02-02 02:16:23 +00003657 Op->getName()), TheAnd);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00003658 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner7e794272004-09-24 15:21:34 +00003659 }
Chris Lattner2da29172003-09-19 19:05:02 +00003660 }
3661 break;
Chris Lattnerba1cb382003-09-19 17:17:26 +00003662 }
3663 return 0;
3664}
3665
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003666
Chris Lattner6862fbd2004-09-29 17:40:11 +00003667/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3668/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencer266e42b2006-12-23 06:05:41 +00003669/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3670/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattner6862fbd2004-09-29 17:40:11 +00003671/// insert new instructions.
3672Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencer266e42b2006-12-23 06:05:41 +00003673 bool isSigned, bool Inside,
3674 Instruction &IB) {
Owen Andersonb5618da2009-07-03 00:17:18 +00003675 assert(cast<ConstantInt>(Context->getConstantExprICmp((isSigned ?
Reid Spencercddc9df2007-01-12 04:24:46 +00003676 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattner6862fbd2004-09-29 17:40:11 +00003677 "Lo is not <= Hi in range emission code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003678
Chris Lattner6862fbd2004-09-29 17:40:11 +00003679 if (Inside) {
3680 if (Lo == Hi) // Trivially false.
Owen Anderson1e5f00e2009-07-09 23:48:35 +00003681 return new ICmpInst(*Context, ICmpInst::ICMP_NE, V, V);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003682
Reid Spencer266e42b2006-12-23 06:05:41 +00003683 // V >= Min && V < Hi --> V < Hi
Zhou Sheng75b871f2007-01-11 12:24:14 +00003684 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencerf4071162007-03-21 23:19:50 +00003685 ICmpInst::Predicate pred = (isSigned ?
Reid Spencer266e42b2006-12-23 06:05:41 +00003686 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
Owen Anderson1e5f00e2009-07-09 23:48:35 +00003687 return new ICmpInst(*Context, pred, V, Hi);
Reid Spencer266e42b2006-12-23 06:05:41 +00003688 }
3689
3690 // Emit V-Lo <u Hi-Lo
Owen Andersonb5618da2009-07-03 00:17:18 +00003691 Constant *NegLo = Context->getConstantExprNeg(Lo);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00003692 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Chris Lattner6862fbd2004-09-29 17:40:11 +00003693 InsertNewInstBefore(Add, IB);
Owen Andersonb5618da2009-07-03 00:17:18 +00003694 Constant *UpperBound = Context->getConstantExprAdd(NegLo, Hi);
Owen Anderson1e5f00e2009-07-09 23:48:35 +00003695 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00003696 }
3697
3698 if (Lo == Hi) // Trivially true.
Owen Anderson1e5f00e2009-07-09 23:48:35 +00003699 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, V, V);
Chris Lattner6862fbd2004-09-29 17:40:11 +00003700
Reid Spencerf4071162007-03-21 23:19:50 +00003701 // V < Min || V >= Hi -> V > Hi-1
Owen Andersonb5618da2009-07-03 00:17:18 +00003702 Hi = SubOne(cast<ConstantInt>(Hi), Context);
Zhou Sheng75b871f2007-01-11 12:24:14 +00003703 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00003704 ICmpInst::Predicate pred = (isSigned ?
3705 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
Owen Anderson1e5f00e2009-07-09 23:48:35 +00003706 return new ICmpInst(*Context, pred, V, Hi);
Reid Spencer266e42b2006-12-23 06:05:41 +00003707 }
Reid Spencere0fc4df2006-10-20 07:07:24 +00003708
Reid Spencerf4071162007-03-21 23:19:50 +00003709 // Emit V-Lo >u Hi-1-Lo
3710 // Note that Hi has already had one subtracted from it, above.
Owen Andersonb5618da2009-07-03 00:17:18 +00003711 ConstantInt *NegLo = cast<ConstantInt>(Context->getConstantExprNeg(Lo));
Gabor Greife1f6e4b2008-05-16 19:29:10 +00003712 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Chris Lattner6862fbd2004-09-29 17:40:11 +00003713 InsertNewInstBefore(Add, IB);
Owen Andersonb5618da2009-07-03 00:17:18 +00003714 Constant *LowerBound = Context->getConstantExprAdd(NegLo, Hi);
Owen Anderson1e5f00e2009-07-09 23:48:35 +00003715 return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00003716}
3717
Chris Lattnerb4b25302005-09-18 07:22:02 +00003718// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3719// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3720// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3721// not, since all 1s are not contiguous.
Zhou Sheng56cda952007-04-02 08:20:41 +00003722static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng150f3bb2007-04-01 17:13:37 +00003723 const APInt& V = Val->getValue();
Reid Spencera962d182007-03-24 00:42:08 +00003724 uint32_t BitWidth = Val->getType()->getBitWidth();
3725 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattnerb4b25302005-09-18 07:22:02 +00003726
3727 // look for the first zero bit after the run of ones
Reid Spencera962d182007-03-24 00:42:08 +00003728 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattnerb4b25302005-09-18 07:22:02 +00003729 // look for the first non-zero bit
Reid Spencera962d182007-03-24 00:42:08 +00003730 ME = V.getActiveBits();
Chris Lattnerb4b25302005-09-18 07:22:02 +00003731 return true;
3732}
3733
Chris Lattnerb4b25302005-09-18 07:22:02 +00003734/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3735/// where isSub determines whether the operator is a sub. If we can fold one of
3736/// the following xforms:
Chris Lattneraf517572005-09-18 04:24:45 +00003737///
3738/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3739/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3740/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3741///
3742/// return (A +/- B).
3743///
3744Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng75b871f2007-01-11 12:24:14 +00003745 ConstantInt *Mask, bool isSub,
Chris Lattneraf517572005-09-18 04:24:45 +00003746 Instruction &I) {
3747 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3748 if (!LHSI || LHSI->getNumOperands() != 2 ||
3749 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3750
3751 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3752
3753 switch (LHSI->getOpcode()) {
3754 default: return 0;
3755 case Instruction::And:
Owen Andersonb5618da2009-07-03 00:17:18 +00003756 if (Context->getConstantExprAnd(N, Mask) == Mask) {
Chris Lattnerb4b25302005-09-18 07:22:02 +00003757 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Shenge9ebd3f2007-03-24 15:34:37 +00003758 if ((Mask->getValue().countLeadingZeros() +
3759 Mask->getValue().countPopulation()) ==
3760 Mask->getValue().getBitWidth())
Chris Lattnerb4b25302005-09-18 07:22:02 +00003761 break;
3762
3763 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3764 // part, we don't need any explicit masks to take them out of A. If that
3765 // is all N is, ignore it.
Zhou Sheng56cda952007-04-02 08:20:41 +00003766 uint32_t MB = 0, ME = 0;
Chris Lattnerb4b25302005-09-18 07:22:02 +00003767 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencer6274c722007-03-23 18:46:34 +00003768 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Shengb3a80b12007-03-29 08:15:12 +00003769 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003770 if (MaskedValueIsZero(RHS, Mask))
Chris Lattnerb4b25302005-09-18 07:22:02 +00003771 break;
3772 }
3773 }
Chris Lattneraf517572005-09-18 04:24:45 +00003774 return 0;
3775 case Instruction::Or:
3776 case Instruction::Xor:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003777 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Shenge9ebd3f2007-03-24 15:34:37 +00003778 if ((Mask->getValue().countLeadingZeros() +
3779 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Owen Andersonb5618da2009-07-03 00:17:18 +00003780 && Context->getConstantExprAnd(N, Mask)->isNullValue())
Chris Lattneraf517572005-09-18 04:24:45 +00003781 break;
3782 return 0;
3783 }
3784
3785 Instruction *New;
3786 if (isSub)
Gabor Greife1f6e4b2008-05-16 19:29:10 +00003787 New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
Chris Lattneraf517572005-09-18 04:24:45 +00003788 else
Gabor Greife1f6e4b2008-05-16 19:29:10 +00003789 New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
Chris Lattneraf517572005-09-18 04:24:45 +00003790 return InsertNewInstBefore(New, I);
3791}
3792
Chris Lattner269cbd52008-11-16 05:06:21 +00003793/// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3794Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3795 ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattnerfeaea9b2008-11-16 05:10:52 +00003796 Value *Val, *Val2;
Chris Lattner269cbd52008-11-16 05:06:21 +00003797 ConstantInt *LHSCst, *RHSCst;
3798 ICmpInst::Predicate LHSCC, RHSCC;
3799
Chris Lattnerfeaea9b2008-11-16 05:10:52 +00003800 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
Owen Anderson16e76742009-07-10 17:35:01 +00003801 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
3802 m_ConstantInt(LHSCst)), *Context) ||
3803 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
3804 m_ConstantInt(RHSCst)), *Context))
Chris Lattner269cbd52008-11-16 05:06:21 +00003805 return 0;
Chris Lattnerfeaea9b2008-11-16 05:10:52 +00003806
3807 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3808 // where C is a power of 2
3809 if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3810 LHSCst->getValue().isPowerOf2()) {
3811 Instruction *NewOr = BinaryOperator::CreateOr(Val, Val2);
3812 InsertNewInstBefore(NewOr, I);
Owen Anderson1e5f00e2009-07-09 23:48:35 +00003813 return new ICmpInst(*Context, LHSCC, NewOr, LHSCst);
Chris Lattnerfeaea9b2008-11-16 05:10:52 +00003814 }
3815
3816 // From here on, we only handle:
3817 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3818 if (Val != Val2) return 0;
3819
Chris Lattner269cbd52008-11-16 05:06:21 +00003820 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3821 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3822 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3823 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3824 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3825 return 0;
3826
3827 // We can't fold (ugt x, C) & (sgt x, C2).
3828 if (!PredicatesFoldable(LHSCC, RHSCC))
3829 return 0;
3830
3831 // Ensure that the larger constant is on the RHS.
Chris Lattner909b9692008-11-16 05:14:43 +00003832 bool ShouldSwap;
Chris Lattner269cbd52008-11-16 05:06:21 +00003833 if (ICmpInst::isSignedPredicate(LHSCC) ||
3834 (ICmpInst::isEquality(LHSCC) &&
3835 ICmpInst::isSignedPredicate(RHSCC)))
Chris Lattner909b9692008-11-16 05:14:43 +00003836 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner269cbd52008-11-16 05:06:21 +00003837 else
Chris Lattner909b9692008-11-16 05:14:43 +00003838 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3839
3840 if (ShouldSwap) {
Chris Lattner269cbd52008-11-16 05:06:21 +00003841 std::swap(LHS, RHS);
3842 std::swap(LHSCst, RHSCst);
3843 std::swap(LHSCC, RHSCC);
3844 }
3845
3846 // At this point, we know we have have two icmp instructions
3847 // comparing a value against two constants and and'ing the result
3848 // together. Because of the above check, we know that we only have
3849 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3850 // (from the FoldICmpLogical check above), that the two constants
3851 // are not equal and that the larger constant is on the RHS
3852 assert(LHSCst != RHSCst && "Compares not folded above?");
3853
3854 switch (LHSCC) {
Torok Edwin56d06592009-07-11 20:10:48 +00003855 default: LLVM_UNREACHABLE("Unknown integer condition code!");
Chris Lattner269cbd52008-11-16 05:06:21 +00003856 case ICmpInst::ICMP_EQ:
3857 switch (RHSCC) {
Torok Edwin56d06592009-07-11 20:10:48 +00003858 default: LLVM_UNREACHABLE("Unknown integer condition code!");
Chris Lattner269cbd52008-11-16 05:06:21 +00003859 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3860 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3861 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Owen Andersonb5618da2009-07-03 00:17:18 +00003862 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Chris Lattner269cbd52008-11-16 05:06:21 +00003863 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3864 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3865 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
3866 return ReplaceInstUsesWith(I, LHS);
3867 }
3868 case ICmpInst::ICMP_NE:
3869 switch (RHSCC) {
Torok Edwin56d06592009-07-11 20:10:48 +00003870 default: LLVM_UNREACHABLE("Unknown integer condition code!");
Chris Lattner269cbd52008-11-16 05:06:21 +00003871 case ICmpInst::ICMP_ULT:
Owen Andersonb5618da2009-07-03 00:17:18 +00003872 if (LHSCst == SubOne(RHSCst, Context)) // (X != 13 & X u< 14) -> X < 13
Owen Anderson1e5f00e2009-07-09 23:48:35 +00003873 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Val, LHSCst);
Chris Lattner269cbd52008-11-16 05:06:21 +00003874 break; // (X != 13 & X u< 15) -> no change
3875 case ICmpInst::ICMP_SLT:
Owen Andersonb5618da2009-07-03 00:17:18 +00003876 if (LHSCst == SubOne(RHSCst, Context)) // (X != 13 & X s< 14) -> X < 13
Owen Anderson1e5f00e2009-07-09 23:48:35 +00003877 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Val, LHSCst);
Chris Lattner269cbd52008-11-16 05:06:21 +00003878 break; // (X != 13 & X s< 15) -> no change
3879 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3880 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3881 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
3882 return ReplaceInstUsesWith(I, RHS);
3883 case ICmpInst::ICMP_NE:
Owen Andersonb5618da2009-07-03 00:17:18 +00003884 if (LHSCst == SubOne(RHSCst, Context)){// (X != 13 & X != 14) -> X-13 >u 1
3885 Constant *AddCST = Context->getConstantExprNeg(LHSCst);
Chris Lattner269cbd52008-11-16 05:06:21 +00003886 Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
3887 Val->getName()+".off");
3888 InsertNewInstBefore(Add, I);
Owen Anderson1e5f00e2009-07-09 23:48:35 +00003889 return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Add,
Owen Andersonb5618da2009-07-03 00:17:18 +00003890 Context->getConstantInt(Add->getType(), 1));
Chris Lattner269cbd52008-11-16 05:06:21 +00003891 }
3892 break; // (X != 13 & X != 15) -> no change
3893 }
3894 break;
3895 case ICmpInst::ICMP_ULT:
3896 switch (RHSCC) {
Torok Edwin56d06592009-07-11 20:10:48 +00003897 default: LLVM_UNREACHABLE("Unknown integer condition code!");
Chris Lattner269cbd52008-11-16 05:06:21 +00003898 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3899 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Owen Andersonb5618da2009-07-03 00:17:18 +00003900 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Chris Lattner269cbd52008-11-16 05:06:21 +00003901 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3902 break;
3903 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3904 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
3905 return ReplaceInstUsesWith(I, LHS);
3906 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3907 break;
3908 }
3909 break;
3910 case ICmpInst::ICMP_SLT:
3911 switch (RHSCC) {
Torok Edwin56d06592009-07-11 20:10:48 +00003912 default: LLVM_UNREACHABLE("Unknown integer condition code!");
Chris Lattner269cbd52008-11-16 05:06:21 +00003913 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3914 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Owen Andersonb5618da2009-07-03 00:17:18 +00003915 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Chris Lattner269cbd52008-11-16 05:06:21 +00003916 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3917 break;
3918 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3919 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
3920 return ReplaceInstUsesWith(I, LHS);
3921 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3922 break;
3923 }
3924 break;
3925 case ICmpInst::ICMP_UGT:
3926 switch (RHSCC) {
Torok Edwin56d06592009-07-11 20:10:48 +00003927 default: LLVM_UNREACHABLE("Unknown integer condition code!");
Chris Lattner269cbd52008-11-16 05:06:21 +00003928 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
3929 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3930 return ReplaceInstUsesWith(I, RHS);
3931 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3932 break;
3933 case ICmpInst::ICMP_NE:
Owen Andersonb5618da2009-07-03 00:17:18 +00003934 if (RHSCst == AddOne(LHSCst, Context)) // (X u> 13 & X != 14) -> X u> 14
Owen Anderson1e5f00e2009-07-09 23:48:35 +00003935 return new ICmpInst(*Context, LHSCC, Val, RHSCst);
Chris Lattner269cbd52008-11-16 05:06:21 +00003936 break; // (X u> 13 & X != 15) -> no change
Chris Lattnerd397fef2008-11-16 05:20:07 +00003937 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Owen Andersonb5618da2009-07-03 00:17:18 +00003938 return InsertRangeTest(Val, AddOne(LHSCst, Context),
3939 RHSCst, false, true, I);
Chris Lattner269cbd52008-11-16 05:06:21 +00003940 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3941 break;
3942 }
3943 break;
3944 case ICmpInst::ICMP_SGT:
3945 switch (RHSCC) {
Torok Edwin56d06592009-07-11 20:10:48 +00003946 default: LLVM_UNREACHABLE("Unknown integer condition code!");
Chris Lattner269cbd52008-11-16 05:06:21 +00003947 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
3948 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3949 return ReplaceInstUsesWith(I, RHS);
3950 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3951 break;
3952 case ICmpInst::ICMP_NE:
Owen Andersonb5618da2009-07-03 00:17:18 +00003953 if (RHSCst == AddOne(LHSCst, Context)) // (X s> 13 & X != 14) -> X s> 14
Owen Anderson1e5f00e2009-07-09 23:48:35 +00003954 return new ICmpInst(*Context, LHSCC, Val, RHSCst);
Chris Lattner269cbd52008-11-16 05:06:21 +00003955 break; // (X s> 13 & X != 15) -> no change
Chris Lattnerd397fef2008-11-16 05:20:07 +00003956 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Owen Andersonb5618da2009-07-03 00:17:18 +00003957 return InsertRangeTest(Val, AddOne(LHSCst, Context),
3958 RHSCst, true, true, I);
Chris Lattner269cbd52008-11-16 05:06:21 +00003959 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3960 break;
3961 }
3962 break;
3963 }
Chris Lattner269cbd52008-11-16 05:06:21 +00003964
3965 return 0;
3966}
3967
3968
Chris Lattner113f4f42002-06-25 16:13:24 +00003969Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003970 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003971 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003972
Chris Lattner81a7a232004-10-16 18:11:37 +00003973 if (isa<UndefValue>(Op1)) // X & undef -> 0
Owen Andersonb5618da2009-07-03 00:17:18 +00003974 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattner81a7a232004-10-16 18:11:37 +00003975
Chris Lattner86102b82005-01-01 16:22:27 +00003976 // and X, X = X
3977 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00003978 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003979
Chris Lattner5b2edb12006-02-12 08:02:11 +00003980 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner5997cf92006-02-08 03:25:32 +00003981 // purpose is to compute bits we don't care about.
Dan Gohman7ccc52f2009-06-15 22:12:54 +00003982 if (SimplifyDemandedInstructionBits(I))
3983 return &I;
3984 if (isa<VectorType>(I.getType())) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00003985 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
Chris Lattnerf14e5172007-06-15 05:26:55 +00003986 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
Chris Lattner120ab032007-01-18 22:16:33 +00003987 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattnerf14e5172007-06-15 05:26:55 +00003988 } else if (isa<ConstantAggregateZero>(Op1)) {
3989 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
Chris Lattner120ab032007-01-18 22:16:33 +00003990 }
3991 }
Dan Gohman7ccc52f2009-06-15 22:12:54 +00003992
Zhou Sheng75b871f2007-01-11 12:24:14 +00003993 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Zhou Sheng150f3bb2007-04-01 17:13:37 +00003994 const APInt& AndRHSMask = AndRHS->getValue();
3995 APInt NotAndRHS(~AndRHSMask);
Chris Lattner86102b82005-01-01 16:22:27 +00003996
Chris Lattnerba1cb382003-09-19 17:17:26 +00003997 // Optimize a variety of ((val OP C1) & C2) combinations...
Reid Spencer2341c222007-02-02 02:16:23 +00003998 if (isa<BinaryOperator>(Op0)) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00003999 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner86102b82005-01-01 16:22:27 +00004000 Value *Op0LHS = Op0I->getOperand(0);
4001 Value *Op0RHS = Op0I->getOperand(1);
4002 switch (Op0I->getOpcode()) {
4003 case Instruction::Xor:
4004 case Instruction::Or:
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00004005 // If the mask is only needed on one incoming arm, push it up.
4006 if (Op0I->hasOneUse()) {
4007 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4008 // Not masking anything out for the LHS, move to RHS.
Gabor Greife1f6e4b2008-05-16 19:29:10 +00004009 Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00004010 Op0RHS->getName()+".masked");
4011 InsertNewInstBefore(NewRHS, I);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00004012 return BinaryOperator::Create(
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00004013 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004014 }
Chris Lattnerc3ebf402006-02-07 07:27:52 +00004015 if (!isa<Constant>(Op0RHS) &&
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00004016 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4017 // Not masking anything out for the RHS, move to LHS.
Gabor Greife1f6e4b2008-05-16 19:29:10 +00004018 Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00004019 Op0LHS->getName()+".masked");
4020 InsertNewInstBefore(NewLHS, I);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00004021 return BinaryOperator::Create(
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00004022 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
4023 }
4024 }
4025
Chris Lattner86102b82005-01-01 16:22:27 +00004026 break;
Chris Lattneraf517572005-09-18 04:24:45 +00004027 case Instruction::Add:
Chris Lattnerb4b25302005-09-18 07:22:02 +00004028 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4029 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4030 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4031 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greife1f6e4b2008-05-16 19:29:10 +00004032 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattnerb4b25302005-09-18 07:22:02 +00004033 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greife1f6e4b2008-05-16 19:29:10 +00004034 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Chris Lattneraf517572005-09-18 04:24:45 +00004035 break;
4036
4037 case Instruction::Sub:
Chris Lattnerb4b25302005-09-18 07:22:02 +00004038 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4039 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4040 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4041 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greife1f6e4b2008-05-16 19:29:10 +00004042 return BinaryOperator::CreateAnd(V, AndRHS);
Nick Lewycky0d3645e2008-07-09 04:32:37 +00004043
Nick Lewycky6193a562008-07-10 05:51:40 +00004044 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4045 // has 1's for all bits that the subtraction with A might affect.
4046 if (Op0I->hasOneUse()) {
4047 uint32_t BitWidth = AndRHSMask.getBitWidth();
4048 uint32_t Zeros = AndRHSMask.countLeadingZeros();
4049 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4050
Nick Lewycky0d3645e2008-07-09 04:32:37 +00004051 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
Nick Lewycky6193a562008-07-10 05:51:40 +00004052 if (!(A && A->isZero()) && // avoid infinite recursion.
4053 MaskedValueIsZero(Op0LHS, Mask)) {
Owen Anderson53a52212009-07-13 04:09:18 +00004054 Instruction *NewNeg = BinaryOperator::CreateNeg(*Context, Op0RHS);
Nick Lewycky0d3645e2008-07-09 04:32:37 +00004055 InsertNewInstBefore(NewNeg, I);
4056 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4057 }
4058 }
Chris Lattneraf517572005-09-18 04:24:45 +00004059 break;
Nick Lewycky364661c2008-07-09 05:20:13 +00004060
4061 case Instruction::Shl:
4062 case Instruction::LShr:
4063 // (1 << x) & 1 --> zext(x == 0)
4064 // (1 >> x) & 1 --> zext(x == 0)
Nick Lewyckybb89c2a2008-07-09 07:35:26 +00004065 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
Owen Anderson1e5f00e2009-07-09 23:48:35 +00004066 Instruction *NewICmp = new ICmpInst(*Context, ICmpInst::ICMP_EQ,
4067 Op0RHS, Context->getNullValue(I.getType()));
Nick Lewycky364661c2008-07-09 05:20:13 +00004068 InsertNewInstBefore(NewICmp, I);
4069 return new ZExtInst(NewICmp, I.getType());
4070 }
4071 break;
Chris Lattner86102b82005-01-01 16:22:27 +00004072 }
4073
Chris Lattner16464b32003-07-23 19:25:52 +00004074 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner86102b82005-01-01 16:22:27 +00004075 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerba1cb382003-09-19 17:17:26 +00004076 return Res;
Chris Lattner86102b82005-01-01 16:22:27 +00004077 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2c14cf72005-08-07 07:03:10 +00004078 // If this is an integer truncation or change from signed-to-unsigned, and
4079 // if the source is an and/or with immediate, transform it. This
4080 // frequently occurs for bitfield accesses.
4081 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00004082 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2c14cf72005-08-07 07:03:10 +00004083 CastOp->getNumOperands() == 2)
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +00004084 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
Chris Lattner2c14cf72005-08-07 07:03:10 +00004085 if (CastOp->getOpcode() == Instruction::And) {
4086 // Change: and (cast (and X, C1) to T), C2
Reid Spencer6c38f0b2006-11-27 01:05:10 +00004087 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
4088 // This will fold the two constants together, which may allow
4089 // other simplifications.
Gabor Greife1f6e4b2008-05-16 19:29:10 +00004090 Instruction *NewCast = CastInst::CreateTruncOrBitCast(
Reid Spencerbb65ebf2006-12-12 23:36:14 +00004091 CastOp->getOperand(0), I.getType(),
4092 CastOp->getName()+".shrunk");
Chris Lattner2c14cf72005-08-07 07:03:10 +00004093 NewCast = InsertNewInstBefore(NewCast, I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00004094 // trunc_or_bitcast(C1)&C2
Owen Andersonb5618da2009-07-03 00:17:18 +00004095 Constant *C3 =
4096 Context->getConstantExprTruncOrBitCast(AndCI,I.getType());
4097 C3 = Context->getConstantExprAnd(C3, AndRHS);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00004098 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner2c14cf72005-08-07 07:03:10 +00004099 } else if (CastOp->getOpcode() == Instruction::Or) {
4100 // Change: and (cast (or X, C1) to T), C2
4101 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Owen Andersonb5618da2009-07-03 00:17:18 +00004102 Constant *C3 =
4103 Context->getConstantExprTruncOrBitCast(AndCI,I.getType());
4104 if (Context->getConstantExprAnd(C3, AndRHS) == AndRHS)
4105 // trunc(C1)&C2
Chris Lattner2c14cf72005-08-07 07:03:10 +00004106 return ReplaceInstUsesWith(I, AndRHS);
4107 }
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +00004108 }
Chris Lattner2c14cf72005-08-07 07:03:10 +00004109 }
Chris Lattner33217db2003-07-23 19:36:21 +00004110 }
Chris Lattner183b3362004-04-09 19:05:30 +00004111
4112 // Try to fold constant and into select arguments.
4113 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00004114 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00004115 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00004116 if (isa<PHINode>(Op0))
4117 if (Instruction *NV = FoldOpIntoPhi(I))
4118 return NV;
Chris Lattner49b47ae2003-07-23 17:57:01 +00004119 }
4120
Owen Andersonb5618da2009-07-03 00:17:18 +00004121 Value *Op0NotVal = dyn_castNotVal(Op0, Context);
4122 Value *Op1NotVal = dyn_castNotVal(Op1, Context);
Chris Lattner3082c5a2003-02-18 19:28:33 +00004123
Chris Lattner023a4832004-06-18 06:07:51 +00004124 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
Owen Andersonb5618da2009-07-03 00:17:18 +00004125 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattner023a4832004-06-18 06:07:51 +00004126
Misha Brukman9c003d82004-07-30 12:50:08 +00004127 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerbb74e222003-03-10 23:06:50 +00004128 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greife1f6e4b2008-05-16 19:29:10 +00004129 Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004130 I.getName()+".demorgan");
Chris Lattner49b47ae2003-07-23 17:57:01 +00004131 InsertNewInstBefore(Or, I);
Owen Anderson542619e2009-07-13 20:58:05 +00004132 return BinaryOperator::CreateNot(*Context, Or);
Chris Lattner3082c5a2003-02-18 19:28:33 +00004133 }
Chris Lattner8b10ab32006-02-13 23:07:23 +00004134
4135 {
Chris Lattner481e28b2007-06-15 05:58:24 +00004136 Value *A = 0, *B = 0, *C = 0, *D = 0;
Owen Anderson16e76742009-07-10 17:35:01 +00004137 if (match(Op0, m_Or(m_Value(A), m_Value(B)), *Context)) {
Chris Lattner8b10ab32006-02-13 23:07:23 +00004138 if (A == Op1 || B == Op1) // (A | ?) & A --> A
4139 return ReplaceInstUsesWith(I, Op1);
Chris Lattner481e28b2007-06-15 05:58:24 +00004140
4141 // (A|B) & ~(A&B) -> A^B
Owen Anderson16e76742009-07-10 17:35:01 +00004142 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))), *Context)) {
Chris Lattner481e28b2007-06-15 05:58:24 +00004143 if ((A == C && B == D) || (A == D && B == C))
Gabor Greife1f6e4b2008-05-16 19:29:10 +00004144 return BinaryOperator::CreateXor(A, B);
Chris Lattner481e28b2007-06-15 05:58:24 +00004145 }
4146 }
4147
Owen Anderson16e76742009-07-10 17:35:01 +00004148 if (match(Op1, m_Or(m_Value(A), m_Value(B)), *Context)) {
Chris Lattner8b10ab32006-02-13 23:07:23 +00004149 if (A == Op0 || B == Op0) // A & (A | ?) --> A
4150 return ReplaceInstUsesWith(I, Op0);
Chris Lattner481e28b2007-06-15 05:58:24 +00004151
4152 // ~(A&B) & (A|B) -> A^B
Owen Anderson16e76742009-07-10 17:35:01 +00004153 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))), *Context)) {
Chris Lattner481e28b2007-06-15 05:58:24 +00004154 if ((A == C && B == D) || (A == D && B == C))
Gabor Greife1f6e4b2008-05-16 19:29:10 +00004155 return BinaryOperator::CreateXor(A, B);
Chris Lattner481e28b2007-06-15 05:58:24 +00004156 }
4157 }
Chris Lattnerdcd07922006-04-01 08:03:55 +00004158
4159 if (Op0->hasOneUse() &&
Owen Anderson16e76742009-07-10 17:35:01 +00004160 match(Op0, m_Xor(m_Value(A), m_Value(B)), *Context)) {
Chris Lattnerdcd07922006-04-01 08:03:55 +00004161 if (A == Op1) { // (A^B)&A -> A&(A^B)
4162 I.swapOperands(); // Simplify below
4163 std::swap(Op0, Op1);
4164 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
4165 cast<BinaryOperator>(Op0)->swapOperands();
4166 I.swapOperands(); // Simplify below
4167 std::swap(Op0, Op1);
4168 }
4169 }
Bill Wendling9eef4212008-11-30 13:08:13 +00004170
Chris Lattnerdcd07922006-04-01 08:03:55 +00004171 if (Op1->hasOneUse() &&
Owen Anderson16e76742009-07-10 17:35:01 +00004172 match(Op1, m_Xor(m_Value(A), m_Value(B)), *Context)) {
Chris Lattnerdcd07922006-04-01 08:03:55 +00004173 if (B == Op0) { // B&(A^B) -> B&(B^A)
4174 cast<BinaryOperator>(Op1)->swapOperands();
4175 std::swap(A, B);
4176 }
4177 if (A == Op0) { // A&(A^B) -> A & ~B
Owen Anderson542619e2009-07-13 20:58:05 +00004178 Instruction *NotB = BinaryOperator::CreateNot(*Context, B, "tmp");
Chris Lattnerdcd07922006-04-01 08:03:55 +00004179 InsertNewInstBefore(NotB, I);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00004180 return BinaryOperator::CreateAnd(A, NotB);
Chris Lattnerdcd07922006-04-01 08:03:55 +00004181 }
4182 }
Bill Wendling9eef4212008-11-30 13:08:13 +00004183
4184 // (A&((~A)|B)) -> A&B
Owen Anderson16e76742009-07-10 17:35:01 +00004185 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A)), *Context) ||
4186 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1))), *Context))
Chris Lattner9e6b2432008-12-01 05:16:26 +00004187 return BinaryOperator::CreateAnd(A, Op1);
Owen Anderson16e76742009-07-10 17:35:01 +00004188 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A)), *Context) ||
4189 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0))), *Context))
Chris Lattner9e6b2432008-12-01 05:16:26 +00004190 return BinaryOperator::CreateAnd(A, Op0);
Chris Lattner8b10ab32006-02-13 23:07:23 +00004191 }
4192
Reid Spencer266e42b2006-12-23 06:05:41 +00004193 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4194 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
Owen Andersonb5618da2009-07-03 00:17:18 +00004195 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
Chris Lattner3ac7c262003-08-13 20:16:26 +00004196 return R;
4197
Chris Lattner269cbd52008-11-16 05:06:21 +00004198 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4199 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4200 return Res;
Chris Lattner623826c2004-09-28 21:48:02 +00004201 }
4202
Chris Lattner3af10532006-05-05 06:39:07 +00004203 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer799b5bf2006-12-13 08:27:15 +00004204 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4205 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4206 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4207 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner03c49532007-01-15 02:27:26 +00004208 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer799b5bf2006-12-13 08:27:15 +00004209 // Only do this if the casts both really cause code to be generated.
Reid Spencer266e42b2006-12-23 06:05:41 +00004210 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4211 I.getType(), TD) &&
4212 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4213 I.getType(), TD)) {
Gabor Greife1f6e4b2008-05-16 19:29:10 +00004214 Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
Reid Spencer799b5bf2006-12-13 08:27:15 +00004215 Op1C->getOperand(0),
4216 I.getName());
4217 InsertNewInstBefore(NewOp, I);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00004218 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer799b5bf2006-12-13 08:27:15 +00004219 }
Chris Lattner3af10532006-05-05 06:39:07 +00004220 }
Chris Lattnerf05d69a2006-11-14 07:46:50 +00004221
4222 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer2341c222007-02-02 02:16:23 +00004223 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4224 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4225 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnerf05d69a2006-11-14 07:46:50 +00004226 SI0->getOperand(1) == SI1->getOperand(1) &&
4227 (SI0->hasOneUse() || SI1->hasOneUse())) {
4228 Instruction *NewOp =
Gabor Greife1f6e4b2008-05-16 19:29:10 +00004229 InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
Chris Lattnerf05d69a2006-11-14 07:46:50 +00004230 SI1->getOperand(0),
4231 SI0->getName()), I);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00004232 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer2341c222007-02-02 02:16:23 +00004233 SI1->getOperand(1));
Chris Lattnerf05d69a2006-11-14 07:46:50 +00004234 }
Chris Lattner3af10532006-05-05 06:39:07 +00004235 }
4236
Evan Cheng67786cc2008-10-14 17:15:11 +00004237 // If and'ing two fcmp, try combine them into one.
Chris Lattnerc62877e2007-10-24 05:38:08 +00004238 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4239 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4240 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
Evan Cheng67786cc2008-10-14 17:15:11 +00004241 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
4242 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
Chris Lattnerc62877e2007-10-24 05:38:08 +00004243 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4244 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4245 // If either of the constants are nans, then the whole thing returns
4246 // false.
Chris Lattner55b83022007-10-24 18:54:45 +00004247 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Andersonb5618da2009-07-03 00:17:18 +00004248 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Owen Anderson1e5f00e2009-07-09 23:48:35 +00004249 return new FCmpInst(*Context, FCmpInst::FCMP_ORD,
4250 LHS->getOperand(0), RHS->getOperand(0));
Chris Lattnerc62877e2007-10-24 05:38:08 +00004251 }
Evan Cheng67786cc2008-10-14 17:15:11 +00004252 } else {
4253 Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4254 FCmpInst::Predicate Op0CC, Op1CC;
Owen Anderson16e76742009-07-10 17:35:01 +00004255 if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS),
4256 m_Value(Op0RHS)), *Context) &&
4257 match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS),
4258 m_Value(Op1RHS)), *Context)) {
Evan Chengce707522008-10-14 18:13:38 +00004259 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4260 // Swap RHS operands to match LHS.
4261 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4262 std::swap(Op1LHS, Op1RHS);
4263 }
Evan Cheng67786cc2008-10-14 17:15:11 +00004264 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4265 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4266 if (Op0CC == Op1CC)
Owen Anderson1e5f00e2009-07-09 23:48:35 +00004267 return new FCmpInst(*Context, (FCmpInst::Predicate)Op0CC,
4268 Op0LHS, Op0RHS);
Evan Cheng67786cc2008-10-14 17:15:11 +00004269 else if (Op0CC == FCmpInst::FCMP_FALSE ||
4270 Op1CC == FCmpInst::FCMP_FALSE)
Owen Andersonb5618da2009-07-03 00:17:18 +00004271 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Evan Cheng67786cc2008-10-14 17:15:11 +00004272 else if (Op0CC == FCmpInst::FCMP_TRUE)
4273 return ReplaceInstUsesWith(I, Op1);
4274 else if (Op1CC == FCmpInst::FCMP_TRUE)
4275 return ReplaceInstUsesWith(I, Op0);
4276 bool Op0Ordered;
4277 bool Op1Ordered;
4278 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4279 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4280 if (Op1Pred == 0) {
4281 std::swap(Op0, Op1);
4282 std::swap(Op0Pred, Op1Pred);
4283 std::swap(Op0Ordered, Op1Ordered);
4284 }
4285 if (Op0Pred == 0) {
4286 // uno && ueq -> uno && (uno || eq) -> ueq
4287 // ord && olt -> ord && (ord && lt) -> olt
4288 if (Op0Ordered == Op1Ordered)
4289 return ReplaceInstUsesWith(I, Op1);
4290 // uno && oeq -> uno && (ord && eq) -> false
4291 // uno && ord -> false
4292 if (!Op0Ordered)
Owen Andersonb5618da2009-07-03 00:17:18 +00004293 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Evan Cheng67786cc2008-10-14 17:15:11 +00004294 // ord && ueq -> ord && (uno || eq) -> oeq
4295 return cast<Instruction>(getFCmpValue(true, Op1Pred,
Owen Andersonb5618da2009-07-03 00:17:18 +00004296 Op0LHS, Op0RHS, Context));
Evan Cheng67786cc2008-10-14 17:15:11 +00004297 }
4298 }
4299 }
4300 }
Chris Lattnerc62877e2007-10-24 05:38:08 +00004301 }
4302 }
Nick Lewycky0d3645e2008-07-09 04:32:37 +00004303
Chris Lattner113f4f42002-06-25 16:13:24 +00004304 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004305}
4306
Chris Lattner917a6c12008-10-05 02:13:19 +00004307/// CollectBSwapParts - Analyze the specified subexpression and see if it is
4308/// capable of providing pieces of a bswap. The subexpression provides pieces
4309/// of a bswap if it is proven that each of the non-zero bytes in the output of
4310/// the expression came from the corresponding "byte swapped" byte in some other
4311/// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
4312/// we know that the expression deposits the low byte of %X into the high byte
4313/// of the bswap result and that all other bytes are zero. This expression is
4314/// accepted, the high byte of ByteValues is set to X to indicate a correct
4315/// match.
4316///
4317/// This function returns true if the match was unsuccessful and false if so.
4318/// On entry to the function the "OverallLeftShift" is a signed integer value
4319/// indicating the number of bytes that the subexpression is later shifted. For
4320/// example, if the expression is later right shifted by 16 bits, the
4321/// OverallLeftShift value would be -2 on entry. This is used to specify which
4322/// byte of ByteValues is actually being set.
4323///
4324/// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4325/// byte is masked to zero by a user. For example, in (X & 255), X will be
4326/// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
4327/// this function to working on up to 32-byte (256 bit) values. ByteMask is
4328/// always in the local (OverallLeftShift) coordinate space.
4329///
4330static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4331 SmallVector<Value*, 8> &ByteValues) {
4332 if (Instruction *I = dyn_cast<Instruction>(V)) {
4333 // If this is an or instruction, it may be an inner node of the bswap.
4334 if (I->getOpcode() == Instruction::Or) {
4335 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4336 ByteValues) ||
4337 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4338 ByteValues);
Chris Lattnerc482a9e2006-06-15 19:07:26 +00004339 }
Chris Lattner917a6c12008-10-05 02:13:19 +00004340
4341 // If this is a logical shift by a constant multiple of 8, recurse with
4342 // OverallLeftShift and ByteMask adjusted.
4343 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4344 unsigned ShAmt =
4345 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4346 // Ensure the shift amount is defined and of a byte value.
4347 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4348 return true;
4349
4350 unsigned ByteShift = ShAmt >> 3;
4351 if (I->getOpcode() == Instruction::Shl) {
4352 // X << 2 -> collect(X, +2)
4353 OverallLeftShift += ByteShift;
4354 ByteMask >>= ByteShift;
4355 } else {
4356 // X >>u 2 -> collect(X, -2)
4357 OverallLeftShift -= ByteShift;
4358 ByteMask <<= ByteShift;
Chris Lattner42d57852008-10-08 06:42:28 +00004359 ByteMask &= (~0U >> (32-ByteValues.size()));
Chris Lattner917a6c12008-10-05 02:13:19 +00004360 }
4361
4362 if (OverallLeftShift >= (int)ByteValues.size()) return true;
4363 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4364
4365 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4366 ByteValues);
4367 }
4368
4369 // If this is a logical 'and' with a mask that clears bytes, clear the
4370 // corresponding bytes in ByteMask.
4371 if (I->getOpcode() == Instruction::And &&
4372 isa<ConstantInt>(I->getOperand(1))) {
4373 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4374 unsigned NumBytes = ByteValues.size();
4375 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4376 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4377
4378 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4379 // If this byte is masked out by a later operation, we don't care what
4380 // the and mask is.
4381 if ((ByteMask & (1 << i)) == 0)
4382 continue;
4383
4384 // If the AndMask is all zeros for this byte, clear the bit.
4385 APInt MaskB = AndMask & Byte;
4386 if (MaskB == 0) {
4387 ByteMask &= ~(1U << i);
4388 continue;
4389 }
4390
4391 // If the AndMask is not all ones for this byte, it's not a bytezap.
4392 if (MaskB != Byte)
4393 return true;
4394
4395 // Otherwise, this byte is kept.
4396 }
4397
4398 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4399 ByteValues);
4400 }
Chris Lattnerc482a9e2006-06-15 19:07:26 +00004401 }
4402
Chris Lattner917a6c12008-10-05 02:13:19 +00004403 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
4404 // the input value to the bswap. Some observations: 1) if more than one byte
4405 // is demanded from this input, then it could not be successfully assembled
4406 // into a byteswap. At least one of the two bytes would not be aligned with
4407 // their ultimate destination.
4408 if (!isPowerOf2_32(ByteMask)) return true;
4409 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
Chris Lattnerc482a9e2006-06-15 19:07:26 +00004410
Chris Lattner917a6c12008-10-05 02:13:19 +00004411 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4412 // is demanded, it needs to go into byte 0 of the result. This means that the
4413 // byte needs to be shifted until it lands in the right byte bucket. The
4414 // shift amount depends on the position: if the byte is coming from the high
4415 // part of the value (e.g. byte 3) then it must be shifted right. If from the
4416 // low part, it must be shifted left.
4417 unsigned DestByteNo = InputByteNo + OverallLeftShift;
4418 if (InputByteNo < ByteValues.size()/2) {
4419 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4420 return true;
4421 } else {
4422 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4423 return true;
4424 }
Chris Lattnerc482a9e2006-06-15 19:07:26 +00004425
4426 // If the destination byte value is already defined, the values are or'd
4427 // together, which isn't a bswap (unless it's an or of the same bits).
Chris Lattner917a6c12008-10-05 02:13:19 +00004428 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00004429 return true;
Chris Lattner917a6c12008-10-05 02:13:19 +00004430 ByteValues[DestByteNo] = V;
Chris Lattnerc482a9e2006-06-15 19:07:26 +00004431 return false;
4432}
4433
4434/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4435/// If so, insert the new bswap intrinsic and return it.
4436Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattnerc3eeb422007-04-01 20:57:36 +00004437 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
Chris Lattner917a6c12008-10-05 02:13:19 +00004438 if (!ITy || ITy->getBitWidth() % 16 ||
4439 // ByteMask only allows up to 32-byte values.
4440 ITy->getBitWidth() > 32*8)
Chris Lattnerc3eeb422007-04-01 20:57:36 +00004441 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerc482a9e2006-06-15 19:07:26 +00004442
4443 /// ByteValues - For each byte of the result, we keep track of which value
4444 /// defines each byte.
Chris Lattner99c6cf62007-02-15 22:52:10 +00004445 SmallVector<Value*, 8> ByteValues;
Chris Lattnerc3eeb422007-04-01 20:57:36 +00004446 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerc482a9e2006-06-15 19:07:26 +00004447
4448 // Try to find all the pieces corresponding to the bswap.
Chris Lattner917a6c12008-10-05 02:13:19 +00004449 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4450 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
Chris Lattnerc482a9e2006-06-15 19:07:26 +00004451 return 0;
4452
4453 // Check to see if all of the bytes come from the same value.
4454 Value *V = ByteValues[0];
4455 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4456
4457 // Check to make sure that all of the bytes come from the same value.
4458 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4459 if (ByteValues[i] != V)
4460 return 0;
Chandler Carruth7132e002007-08-04 01:51:18 +00004461 const Type *Tys[] = { ITy };
Chris Lattnerc482a9e2006-06-15 19:07:26 +00004462 Module *M = I.getParent()->getParent()->getParent();
Chandler Carruth7132e002007-08-04 01:51:18 +00004463 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greife9ecc682008-04-06 20:25:17 +00004464 return CallInst::Create(F, V);
Chris Lattnerc482a9e2006-06-15 19:07:26 +00004465}
4466
Chris Lattner5f6d9a32008-11-16 04:24:12 +00004467/// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
4468/// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4469/// we can simplify this expression to "cond ? C : D or B".
4470static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
Owen Anderson16e76742009-07-10 17:35:01 +00004471 Value *C, Value *D,
4472 LLVMContext *Context) {
Chris Lattner569d78c2008-11-16 04:26:55 +00004473 // If A is not a select of -1/0, this cannot match.
Chris Lattnerf1be2852008-11-16 04:46:19 +00004474 Value *Cond = 0;
Owen Anderson16e76742009-07-10 17:35:01 +00004475 if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond)), *Context))
Chris Lattner5f6d9a32008-11-16 04:24:12 +00004476 return 0;
4477
Chris Lattner569d78c2008-11-16 04:26:55 +00004478 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
Owen Anderson16e76742009-07-10 17:35:01 +00004479 if (match(D, m_SelectCst<0, -1>(m_Specific(Cond)), *Context))
Chris Lattner569d78c2008-11-16 04:26:55 +00004480 return SelectInst::Create(Cond, C, B);
Owen Anderson16e76742009-07-10 17:35:01 +00004481 if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond))), *Context))
Chris Lattner569d78c2008-11-16 04:26:55 +00004482 return SelectInst::Create(Cond, C, B);
4483 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
Owen Anderson16e76742009-07-10 17:35:01 +00004484 if (match(B, m_SelectCst<0, -1>(m_Specific(Cond)), *Context))
Chris Lattner569d78c2008-11-16 04:26:55 +00004485 return SelectInst::Create(Cond, C, D);
Owen Anderson16e76742009-07-10 17:35:01 +00004486 if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond))), *Context))
Chris Lattner569d78c2008-11-16 04:26:55 +00004487 return SelectInst::Create(Cond, C, D);
Chris Lattner5f6d9a32008-11-16 04:24:12 +00004488 return 0;
4489}
Chris Lattnerc482a9e2006-06-15 19:07:26 +00004490
Chris Lattnerd397fef2008-11-16 05:20:07 +00004491/// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4492Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4493 ICmpInst *LHS, ICmpInst *RHS) {
4494 Value *Val, *Val2;
4495 ConstantInt *LHSCst, *RHSCst;
4496 ICmpInst::Predicate LHSCC, RHSCC;
4497
4498 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
Owen Anderson16e76742009-07-10 17:35:01 +00004499 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
4500 m_ConstantInt(LHSCst)), *Context) ||
4501 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
4502 m_ConstantInt(RHSCst)), *Context))
Chris Lattnerd397fef2008-11-16 05:20:07 +00004503 return 0;
4504
4505 // From here on, we only handle:
4506 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4507 if (Val != Val2) return 0;
4508
4509 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4510 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4511 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4512 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4513 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4514 return 0;
4515
4516 // We can't fold (ugt x, C) | (sgt x, C2).
4517 if (!PredicatesFoldable(LHSCC, RHSCC))
4518 return 0;
4519
4520 // Ensure that the larger constant is on the RHS.
4521 bool ShouldSwap;
4522 if (ICmpInst::isSignedPredicate(LHSCC) ||
4523 (ICmpInst::isEquality(LHSCC) &&
4524 ICmpInst::isSignedPredicate(RHSCC)))
4525 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4526 else
4527 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4528
4529 if (ShouldSwap) {
4530 std::swap(LHS, RHS);
4531 std::swap(LHSCst, RHSCst);
4532 std::swap(LHSCC, RHSCC);
4533 }
4534
4535 // At this point, we know we have have two icmp instructions
4536 // comparing a value against two constants and or'ing the result
4537 // together. Because of the above check, we know that we only have
4538 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4539 // FoldICmpLogical check above), that the two constants are not
4540 // equal.
4541 assert(LHSCst != RHSCst && "Compares not folded above?");
4542
4543 switch (LHSCC) {
Torok Edwin56d06592009-07-11 20:10:48 +00004544 default: LLVM_UNREACHABLE("Unknown integer condition code!");
Chris Lattnerd397fef2008-11-16 05:20:07 +00004545 case ICmpInst::ICMP_EQ:
4546 switch (RHSCC) {
Torok Edwin56d06592009-07-11 20:10:48 +00004547 default: LLVM_UNREACHABLE("Unknown integer condition code!");
Chris Lattnerd397fef2008-11-16 05:20:07 +00004548 case ICmpInst::ICMP_EQ:
Owen Andersonb5618da2009-07-03 00:17:18 +00004549 if (LHSCst == SubOne(RHSCst, Context)) {
4550 // (X == 13 | X == 14) -> X-13 <u 2
4551 Constant *AddCST = Context->getConstantExprNeg(LHSCst);
Chris Lattnerd397fef2008-11-16 05:20:07 +00004552 Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
4553 Val->getName()+".off");
4554 InsertNewInstBefore(Add, I);
Owen Andersonb5618da2009-07-03 00:17:18 +00004555 AddCST = Context->getConstantExprSub(AddOne(RHSCst, Context), LHSCst);
Owen Anderson1e5f00e2009-07-09 23:48:35 +00004556 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattnerd397fef2008-11-16 05:20:07 +00004557 }
4558 break; // (X == 13 | X == 15) -> no change
4559 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4560 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4561 break;
4562 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4563 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4564 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4565 return ReplaceInstUsesWith(I, RHS);
4566 }
4567 break;
4568 case ICmpInst::ICMP_NE:
4569 switch (RHSCC) {
Torok Edwin56d06592009-07-11 20:10:48 +00004570 default: LLVM_UNREACHABLE("Unknown integer condition code!");
Chris Lattnerd397fef2008-11-16 05:20:07 +00004571 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4572 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4573 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4574 return ReplaceInstUsesWith(I, LHS);
4575 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4576 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4577 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Owen Andersonb5618da2009-07-03 00:17:18 +00004578 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Chris Lattnerd397fef2008-11-16 05:20:07 +00004579 }
4580 break;
4581 case ICmpInst::ICMP_ULT:
4582 switch (RHSCC) {
Torok Edwin56d06592009-07-11 20:10:48 +00004583 default: LLVM_UNREACHABLE("Unknown integer condition code!");
Chris Lattnerd397fef2008-11-16 05:20:07 +00004584 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4585 break;
4586 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
4587 // If RHSCst is [us]MAXINT, it is always false. Not handling
4588 // this can cause overflow.
4589 if (RHSCst->isMaxValue(false))
4590 return ReplaceInstUsesWith(I, LHS);
Owen Andersonb5618da2009-07-03 00:17:18 +00004591 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst, Context),
4592 false, false, I);
Chris Lattnerd397fef2008-11-16 05:20:07 +00004593 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4594 break;
4595 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4596 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4597 return ReplaceInstUsesWith(I, RHS);
4598 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4599 break;
4600 }
4601 break;
4602 case ICmpInst::ICMP_SLT:
4603 switch (RHSCC) {
Torok Edwin56d06592009-07-11 20:10:48 +00004604 default: LLVM_UNREACHABLE("Unknown integer condition code!");
Chris Lattnerd397fef2008-11-16 05:20:07 +00004605 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4606 break;
4607 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
4608 // If RHSCst is [us]MAXINT, it is always false. Not handling
4609 // this can cause overflow.
4610 if (RHSCst->isMaxValue(true))
4611 return ReplaceInstUsesWith(I, LHS);
Owen Andersonb5618da2009-07-03 00:17:18 +00004612 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst, Context),
4613 true, false, I);
Chris Lattnerd397fef2008-11-16 05:20:07 +00004614 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4615 break;
4616 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4617 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4618 return ReplaceInstUsesWith(I, RHS);
4619 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4620 break;
4621 }
4622 break;
4623 case ICmpInst::ICMP_UGT:
4624 switch (RHSCC) {
Torok Edwin56d06592009-07-11 20:10:48 +00004625 default: LLVM_UNREACHABLE("Unknown integer condition code!");
Chris Lattnerd397fef2008-11-16 05:20:07 +00004626 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4627 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4628 return ReplaceInstUsesWith(I, LHS);
4629 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4630 break;
4631 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4632 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Owen Andersonb5618da2009-07-03 00:17:18 +00004633 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Chris Lattnerd397fef2008-11-16 05:20:07 +00004634 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4635 break;
4636 }
4637 break;
4638 case ICmpInst::ICMP_SGT:
4639 switch (RHSCC) {
Torok Edwin56d06592009-07-11 20:10:48 +00004640 default: LLVM_UNREACHABLE("Unknown integer condition code!");
Chris Lattnerd397fef2008-11-16 05:20:07 +00004641 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4642 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4643 return ReplaceInstUsesWith(I, LHS);
4644 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4645 break;
4646 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4647 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Owen Andersonb5618da2009-07-03 00:17:18 +00004648 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Chris Lattnerd397fef2008-11-16 05:20:07 +00004649 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4650 break;
4651 }
4652 break;
4653 }
4654 return 0;
4655}
4656
Bill Wendling22e761b2008-12-01 08:23:25 +00004657/// FoldOrWithConstants - This helper function folds:
4658///
Bill Wendling5369db52008-12-02 05:09:00 +00004659/// ((A | B) & C1) | (B & C2)
Bill Wendling22e761b2008-12-01 08:23:25 +00004660///
4661/// into:
4662///
Bill Wendling5369db52008-12-02 05:09:00 +00004663/// (A & C1) | B
Bill Wendling47f733e2008-12-01 08:32:40 +00004664///
Bill Wendling5369db52008-12-02 05:09:00 +00004665/// when the XOR of the two constants is "all ones" (-1).
Bill Wendling47f733e2008-12-01 08:32:40 +00004666Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendling22e761b2008-12-01 08:23:25 +00004667 Value *A, Value *B, Value *C) {
Bill Wendling21716df2008-12-02 05:06:43 +00004668 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4669 if (!CI1) return 0;
Bill Wendling22e761b2008-12-01 08:23:25 +00004670
Bill Wendling87beb9b2008-12-02 06:24:20 +00004671 Value *V1 = 0;
4672 ConstantInt *CI2 = 0;
Owen Anderson16e76742009-07-10 17:35:01 +00004673 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)), *Context)) return 0;
Bill Wendling22e761b2008-12-01 08:23:25 +00004674
Bill Wendling56352952008-12-02 06:18:11 +00004675 APInt Xor = CI1->getValue() ^ CI2->getValue();
4676 if (!Xor.isAllOnesValue()) return 0;
4677
Bill Wendling87beb9b2008-12-02 06:24:20 +00004678 if (V1 == A || V1 == B) {
Bill Wendling56352952008-12-02 06:18:11 +00004679 Instruction *NewOp =
Bill Wendling790b4bf2008-12-02 06:22:04 +00004680 InsertNewInstBefore(BinaryOperator::CreateAnd((V1 == A) ? B : A, CI1), I);
4681 return BinaryOperator::CreateOr(NewOp, V1);
Bill Wendling22e761b2008-12-01 08:23:25 +00004682 }
4683
4684 return 0;
4685}
4686
Chris Lattner113f4f42002-06-25 16:13:24 +00004687Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00004688 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00004689 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004690
Chris Lattner3a8248f2007-03-24 23:56:43 +00004691 if (isa<UndefValue>(Op1)) // X | undef -> -1
Owen Andersonb5618da2009-07-03 00:17:18 +00004692 return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
Chris Lattner81a7a232004-10-16 18:11:37 +00004693
Chris Lattner5b2edb12006-02-12 08:02:11 +00004694 // or X, X = X
4695 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00004696 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004697
Chris Lattner5b2edb12006-02-12 08:02:11 +00004698 // See if we can simplify any instructions used by the instruction whose sole
4699 // purpose is to compute bits we don't care about.
Dan Gohman7ccc52f2009-06-15 22:12:54 +00004700 if (SimplifyDemandedInstructionBits(I))
4701 return &I;
4702 if (isa<VectorType>(I.getType())) {
4703 if (isa<ConstantAggregateZero>(Op1)) {
4704 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4705 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4706 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4707 return ReplaceInstUsesWith(I, I.getOperand(1));
4708 }
Chris Lattner3a8248f2007-03-24 23:56:43 +00004709 }
Chris Lattnerf14e5172007-06-15 05:26:55 +00004710
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004711 // or X, -1 == -1
Zhou Sheng75b871f2007-01-11 12:24:14 +00004712 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner330628a2006-01-06 17:59:59 +00004713 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00004714 // (X & C1) | C2 --> (X | C2) & (C1|C2)
Owen Anderson16e76742009-07-10 17:35:01 +00004715 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1)), *Context) &&
4716 isOnlyUse(Op0)) {
Gabor Greife1f6e4b2008-05-16 19:29:10 +00004717 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Chris Lattnerd4252a72004-07-30 07:50:03 +00004718 InsertNewInstBefore(Or, I);
Chris Lattner6e0123b2007-02-11 01:23:03 +00004719 Or->takeName(Op0);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00004720 return BinaryOperator::CreateAnd(Or,
Owen Andersonb5618da2009-07-03 00:17:18 +00004721 Context->getConstantInt(RHS->getValue() | C1->getValue()));
Chris Lattnerd4252a72004-07-30 07:50:03 +00004722 }
Chris Lattner8f0d1562003-07-23 18:29:44 +00004723
Chris Lattnerd4252a72004-07-30 07:50:03 +00004724 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
Owen Anderson16e76742009-07-10 17:35:01 +00004725 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1)), *Context) &&
4726 isOnlyUse(Op0)) {
Gabor Greife1f6e4b2008-05-16 19:29:10 +00004727 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Chris Lattnerd4252a72004-07-30 07:50:03 +00004728 InsertNewInstBefore(Or, I);
Chris Lattner6e0123b2007-02-11 01:23:03 +00004729 Or->takeName(Op0);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00004730 return BinaryOperator::CreateXor(Or,
Owen Andersonb5618da2009-07-03 00:17:18 +00004731 Context->getConstantInt(C1->getValue() & ~RHS->getValue()));
Chris Lattner8f0d1562003-07-23 18:29:44 +00004732 }
Chris Lattner183b3362004-04-09 19:05:30 +00004733
4734 // Try to fold constant and into select arguments.
4735 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00004736 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00004737 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00004738 if (isa<PHINode>(Op0))
4739 if (Instruction *NV = FoldOpIntoPhi(I))
4740 return NV;
Chris Lattner8f0d1562003-07-23 18:29:44 +00004741 }
4742
Chris Lattner330628a2006-01-06 17:59:59 +00004743 Value *A = 0, *B = 0;
4744 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattner4294cec2005-05-07 23:49:08 +00004745
Owen Anderson16e76742009-07-10 17:35:01 +00004746 if (match(Op0, m_And(m_Value(A), m_Value(B)), *Context))
Chris Lattner4294cec2005-05-07 23:49:08 +00004747 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4748 return ReplaceInstUsesWith(I, Op1);
Owen Anderson16e76742009-07-10 17:35:01 +00004749 if (match(Op1, m_And(m_Value(A), m_Value(B)), *Context))
Chris Lattner4294cec2005-05-07 23:49:08 +00004750 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4751 return ReplaceInstUsesWith(I, Op0);
4752
Chris Lattnerb7845d62006-07-10 20:25:24 +00004753 // (A | B) | C and A | (B | C) -> bswap if possible.
4754 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Owen Anderson16e76742009-07-10 17:35:01 +00004755 if (match(Op0, m_Or(m_Value(), m_Value()), *Context) ||
4756 match(Op1, m_Or(m_Value(), m_Value()), *Context) ||
4757 (match(Op0, m_Shift(m_Value(), m_Value()), *Context) &&
4758 match(Op1, m_Shift(m_Value(), m_Value()), *Context))) {
Chris Lattnerc482a9e2006-06-15 19:07:26 +00004759 if (Instruction *BSwap = MatchBSwap(I))
4760 return BSwap;
4761 }
4762
Chris Lattnerb62f5082005-05-09 04:58:36 +00004763 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
Owen Anderson16e76742009-07-10 17:35:01 +00004764 if (Op0->hasOneUse() &&
4765 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1)), *Context) &&
Reid Spencerb722f2b2007-03-22 22:19:58 +00004766 MaskedValueIsZero(Op1, C1->getValue())) {
Gabor Greife1f6e4b2008-05-16 19:29:10 +00004767 Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
Chris Lattner6e0123b2007-02-11 01:23:03 +00004768 InsertNewInstBefore(NOr, I);
4769 NOr->takeName(Op0);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00004770 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattnerb62f5082005-05-09 04:58:36 +00004771 }
4772
4773 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
Owen Anderson16e76742009-07-10 17:35:01 +00004774 if (Op1->hasOneUse() &&
4775 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1)), *Context) &&
Reid Spencerb722f2b2007-03-22 22:19:58 +00004776 MaskedValueIsZero(Op0, C1->getValue())) {
Gabor Greife1f6e4b2008-05-16 19:29:10 +00004777 Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
Chris Lattner6e0123b2007-02-11 01:23:03 +00004778 InsertNewInstBefore(NOr, I);
4779 NOr->takeName(Op0);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00004780 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattnerb62f5082005-05-09 04:58:36 +00004781 }
4782
Chris Lattner1150df92007-04-08 07:47:01 +00004783 // (A & C)|(B & D)
Chris Lattner09a33a42007-06-19 05:43:49 +00004784 Value *C = 0, *D = 0;
Owen Anderson16e76742009-07-10 17:35:01 +00004785 if (match(Op0, m_And(m_Value(A), m_Value(C)), *Context) &&
4786 match(Op1, m_And(m_Value(B), m_Value(D)), *Context)) {
Chris Lattner7621a032007-04-08 07:55:22 +00004787 Value *V1 = 0, *V2 = 0, *V3 = 0;
4788 C1 = dyn_cast<ConstantInt>(C);
4789 C2 = dyn_cast<ConstantInt>(D);
4790 if (C1 && C2) { // (A & C1)|(B & C2)
4791 // If we have: ((V + N) & C1) | (V & C2)
4792 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4793 // replace with V+N.
4794 if (C1->getValue() == ~C2->getValue()) {
4795 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
Owen Anderson16e76742009-07-10 17:35:01 +00004796 match(A, m_Add(m_Value(V1), m_Value(V2)), *Context)) {
Chris Lattner7621a032007-04-08 07:55:22 +00004797 // Add commutes, try both ways.
4798 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4799 return ReplaceInstUsesWith(I, A);
4800 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4801 return ReplaceInstUsesWith(I, A);
4802 }
4803 // Or commutes, try both ways.
4804 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
Owen Anderson16e76742009-07-10 17:35:01 +00004805 match(B, m_Add(m_Value(V1), m_Value(V2)), *Context)) {
Chris Lattner7621a032007-04-08 07:55:22 +00004806 // Add commutes, try both ways.
4807 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4808 return ReplaceInstUsesWith(I, B);
4809 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4810 return ReplaceInstUsesWith(I, B);
4811 }
4812 }
Chris Lattnerc8d37882007-04-08 08:01:49 +00004813 V1 = 0; V2 = 0; V3 = 0;
Chris Lattner7621a032007-04-08 07:55:22 +00004814 }
4815
Chris Lattner1150df92007-04-08 07:47:01 +00004816 // Check to see if we have any common things being and'ed. If so, find the
4817 // terms for V1 & (V2|V3).
Chris Lattner1150df92007-04-08 07:47:01 +00004818 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4819 if (A == B) // (A & C)|(A & D) == A & (C|D)
4820 V1 = A, V2 = C, V3 = D;
4821 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4822 V1 = A, V2 = B, V3 = C;
4823 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4824 V1 = C, V2 = A, V3 = D;
4825 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4826 V1 = C, V2 = A, V3 = B;
4827
4828 if (V1) {
4829 Value *Or =
Gabor Greife1f6e4b2008-05-16 19:29:10 +00004830 InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4831 return BinaryOperator::CreateAnd(V1, Or);
Chris Lattner01f56c62005-09-18 06:02:59 +00004832 }
Chris Lattner1150df92007-04-08 07:47:01 +00004833 }
Dan Gohman2c34c132008-10-28 22:38:57 +00004834
Dan Gohman13cbcf1c182008-10-30 20:40:10 +00004835 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
Owen Anderson16e76742009-07-10 17:35:01 +00004836 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
Chris Lattner5f6d9a32008-11-16 04:24:12 +00004837 return Match;
Owen Anderson16e76742009-07-10 17:35:01 +00004838 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
Chris Lattner5f6d9a32008-11-16 04:24:12 +00004839 return Match;
Owen Anderson16e76742009-07-10 17:35:01 +00004840 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
Chris Lattner5f6d9a32008-11-16 04:24:12 +00004841 return Match;
Owen Anderson16e76742009-07-10 17:35:01 +00004842 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
Chris Lattner5f6d9a32008-11-16 04:24:12 +00004843 return Match;
Bill Wendlingde89bc22008-11-30 13:52:49 +00004844
Bill Wendlingde89bc22008-11-30 13:52:49 +00004845 // ((A&~B)|(~A&B)) -> A^B
Owen Anderson16e76742009-07-10 17:35:01 +00004846 if ((match(C, m_Not(m_Specific(D)), *Context) &&
4847 match(B, m_Not(m_Specific(A)), *Context)))
Bill Wendling582fe6b2008-12-01 08:09:47 +00004848 return BinaryOperator::CreateXor(A, D);
Bill Wendlingde89bc22008-11-30 13:52:49 +00004849 // ((~B&A)|(~A&B)) -> A^B
Owen Anderson16e76742009-07-10 17:35:01 +00004850 if ((match(A, m_Not(m_Specific(D)), *Context) &&
4851 match(B, m_Not(m_Specific(C)), *Context)))
Bill Wendling582fe6b2008-12-01 08:09:47 +00004852 return BinaryOperator::CreateXor(C, D);
Bill Wendlingde89bc22008-11-30 13:52:49 +00004853 // ((A&~B)|(B&~A)) -> A^B
Owen Anderson16e76742009-07-10 17:35:01 +00004854 if ((match(C, m_Not(m_Specific(B)), *Context) &&
4855 match(D, m_Not(m_Specific(A)), *Context)))
Bill Wendling582fe6b2008-12-01 08:09:47 +00004856 return BinaryOperator::CreateXor(A, B);
Bill Wendlingde89bc22008-11-30 13:52:49 +00004857 // ((~B&A)|(B&~A)) -> A^B
Owen Anderson16e76742009-07-10 17:35:01 +00004858 if ((match(A, m_Not(m_Specific(B)), *Context) &&
4859 match(D, m_Not(m_Specific(C)), *Context)))
Bill Wendling582fe6b2008-12-01 08:09:47 +00004860 return BinaryOperator::CreateXor(C, B);
Chris Lattner15212982005-09-18 03:42:07 +00004861 }
Chris Lattnerf05d69a2006-11-14 07:46:50 +00004862
4863 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer2341c222007-02-02 02:16:23 +00004864 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4865 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4866 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnerf05d69a2006-11-14 07:46:50 +00004867 SI0->getOperand(1) == SI1->getOperand(1) &&
4868 (SI0->hasOneUse() || SI1->hasOneUse())) {
4869 Instruction *NewOp =
Gabor Greife1f6e4b2008-05-16 19:29:10 +00004870 InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
Chris Lattnerf05d69a2006-11-14 07:46:50 +00004871 SI1->getOperand(0),
4872 SI0->getName()), I);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00004873 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer2341c222007-02-02 02:16:23 +00004874 SI1->getOperand(1));
Chris Lattnerf05d69a2006-11-14 07:46:50 +00004875 }
4876 }
Chris Lattner812aab72003-08-12 19:11:07 +00004877
Bill Wendling5b902c52008-12-01 01:07:11 +00004878 // ((A|B)&1)|(B&-2) -> (A&1) | B
Owen Anderson16e76742009-07-10 17:35:01 +00004879 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C)), *Context) ||
4880 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))), *Context)) {
Bill Wendling47f733e2008-12-01 08:32:40 +00004881 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
Bill Wendling22e761b2008-12-01 08:23:25 +00004882 if (Ret) return Ret;
Bill Wendling5b902c52008-12-01 01:07:11 +00004883 }
4884 // (B&-2)|((A|B)&1) -> (A&1) | B
Owen Anderson16e76742009-07-10 17:35:01 +00004885 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C)), *Context) ||
4886 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))), *Context)) {
Bill Wendling47f733e2008-12-01 08:32:40 +00004887 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
Bill Wendling22e761b2008-12-01 08:23:25 +00004888 if (Ret) return Ret;
Bill Wendling5b902c52008-12-01 01:07:11 +00004889 }
4890
Owen Anderson16e76742009-07-10 17:35:01 +00004891 if (match(Op0, m_Not(m_Value(A)), *Context)) { // ~A | Op1
Chris Lattnerd4252a72004-07-30 07:50:03 +00004892 if (A == Op1) // ~A | A == -1
Owen Andersonb5618da2009-07-03 00:17:18 +00004893 return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
Chris Lattnerd4252a72004-07-30 07:50:03 +00004894 } else {
4895 A = 0;
4896 }
Chris Lattner4294cec2005-05-07 23:49:08 +00004897 // Note, A is still live here!
Owen Anderson16e76742009-07-10 17:35:01 +00004898 if (match(Op1, m_Not(m_Value(B)), *Context)) { // Op0 | ~B
Chris Lattnerd4252a72004-07-30 07:50:03 +00004899 if (Op0 == B)
Owen Andersonb5618da2009-07-03 00:17:18 +00004900 return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
Chris Lattner3e327a42003-03-10 23:13:59 +00004901
Misha Brukman9c003d82004-07-30 12:50:08 +00004902 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattnerd4252a72004-07-30 07:50:03 +00004903 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greife1f6e4b2008-05-16 19:29:10 +00004904 Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
Chris Lattnerd4252a72004-07-30 07:50:03 +00004905 I.getName()+".demorgan"), I);
Owen Anderson542619e2009-07-13 20:58:05 +00004906 return BinaryOperator::CreateNot(*Context, And);
Chris Lattnerd4252a72004-07-30 07:50:03 +00004907 }
Chris Lattner3e327a42003-03-10 23:13:59 +00004908 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00004909
Reid Spencer266e42b2006-12-23 06:05:41 +00004910 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4911 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
Owen Andersonb5618da2009-07-03 00:17:18 +00004912 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
Chris Lattner3ac7c262003-08-13 20:16:26 +00004913 return R;
4914
Chris Lattnerd397fef2008-11-16 05:20:07 +00004915 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4916 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4917 return Res;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004918 }
Chris Lattner3af10532006-05-05 06:39:07 +00004919
4920 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattnerc62877e2007-10-24 05:38:08 +00004921 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner3af10532006-05-05 06:39:07 +00004922 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer799b5bf2006-12-13 08:27:15 +00004923 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chengc3cf9f82008-03-24 00:21:34 +00004924 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4925 !isa<ICmpInst>(Op1C->getOperand(0))) {
4926 const Type *SrcTy = Op0C->getOperand(0)->getType();
4927 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4928 // Only do this if the casts both really cause code to be
4929 // generated.
4930 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4931 I.getType(), TD) &&
4932 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4933 I.getType(), TD)) {
Gabor Greife1f6e4b2008-05-16 19:29:10 +00004934 Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
Evan Chengc3cf9f82008-03-24 00:21:34 +00004935 Op1C->getOperand(0),
4936 I.getName());
4937 InsertNewInstBefore(NewOp, I);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00004938 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chengc3cf9f82008-03-24 00:21:34 +00004939 }
Reid Spencer799b5bf2006-12-13 08:27:15 +00004940 }
Chris Lattner3af10532006-05-05 06:39:07 +00004941 }
Chris Lattnerc62877e2007-10-24 05:38:08 +00004942 }
4943
4944
4945 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4946 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4947 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4948 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
Chris Lattnerc6125712008-02-29 06:09:11 +00004949 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
Evan Chengd885f6e2008-10-14 18:44:08 +00004950 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
Chris Lattnerc62877e2007-10-24 05:38:08 +00004951 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4952 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4953 // If either of the constants are nans, then the whole thing returns
4954 // true.
Chris Lattner55b83022007-10-24 18:54:45 +00004955 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Andersonb5618da2009-07-03 00:17:18 +00004956 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Chris Lattnerc62877e2007-10-24 05:38:08 +00004957
4958 // Otherwise, no need to compare the two constants, compare the
4959 // rest.
Owen Anderson1e5f00e2009-07-09 23:48:35 +00004960 return new FCmpInst(*Context, FCmpInst::FCMP_UNO,
4961 LHS->getOperand(0), RHS->getOperand(0));
Chris Lattnerc62877e2007-10-24 05:38:08 +00004962 }
Evan Chengd885f6e2008-10-14 18:44:08 +00004963 } else {
4964 Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4965 FCmpInst::Predicate Op0CC, Op1CC;
Owen Anderson16e76742009-07-10 17:35:01 +00004966 if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS),
4967 m_Value(Op0RHS)), *Context) &&
4968 match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS),
4969 m_Value(Op1RHS)), *Context)) {
Evan Chengd885f6e2008-10-14 18:44:08 +00004970 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4971 // Swap RHS operands to match LHS.
4972 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4973 std::swap(Op1LHS, Op1RHS);
4974 }
4975 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4976 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4977 if (Op0CC == Op1CC)
Owen Anderson1e5f00e2009-07-09 23:48:35 +00004978 return new FCmpInst(*Context, (FCmpInst::Predicate)Op0CC,
4979 Op0LHS, Op0RHS);
Evan Chengd885f6e2008-10-14 18:44:08 +00004980 else if (Op0CC == FCmpInst::FCMP_TRUE ||
4981 Op1CC == FCmpInst::FCMP_TRUE)
Owen Andersonb5618da2009-07-03 00:17:18 +00004982 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Evan Chengd885f6e2008-10-14 18:44:08 +00004983 else if (Op0CC == FCmpInst::FCMP_FALSE)
4984 return ReplaceInstUsesWith(I, Op1);
4985 else if (Op1CC == FCmpInst::FCMP_FALSE)
4986 return ReplaceInstUsesWith(I, Op0);
4987 bool Op0Ordered;
4988 bool Op1Ordered;
4989 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4990 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4991 if (Op0Ordered == Op1Ordered) {
4992 // If both are ordered or unordered, return a new fcmp with
4993 // or'ed predicates.
4994 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
Owen Andersonb5618da2009-07-03 00:17:18 +00004995 Op0LHS, Op0RHS, Context);
Evan Chengd885f6e2008-10-14 18:44:08 +00004996 if (Instruction *I = dyn_cast<Instruction>(RV))
4997 return I;
4998 // Otherwise, it's a constant boolean value...
4999 return ReplaceInstUsesWith(I, RV);
5000 }
5001 }
5002 }
5003 }
Chris Lattnerc62877e2007-10-24 05:38:08 +00005004 }
5005 }
Chris Lattner15212982005-09-18 03:42:07 +00005006
Chris Lattner113f4f42002-06-25 16:13:24 +00005007 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005008}
5009
Dan Gohmand78c4002008-05-13 00:00:25 +00005010namespace {
5011
Chris Lattnerc2076352004-02-16 01:20:27 +00005012// XorSelf - Implements: X ^ X --> 0
5013struct XorSelf {
5014 Value *RHS;
5015 XorSelf(Value *rhs) : RHS(rhs) {}
5016 bool shouldApply(Value *LHS) const { return LHS == RHS; }
5017 Instruction *apply(BinaryOperator &Xor) const {
5018 return &Xor;
5019 }
5020};
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005021
Dan Gohmand78c4002008-05-13 00:00:25 +00005022}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005023
Chris Lattner113f4f42002-06-25 16:13:24 +00005024Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00005025 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00005026 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005027
Evan Cheng2b72c052008-03-25 20:07:13 +00005028 if (isa<UndefValue>(Op1)) {
5029 if (isa<UndefValue>(Op0))
5030 // Handle undef ^ undef -> 0 special case. This is a common
5031 // idiom (misuse).
Owen Andersonb5618da2009-07-03 00:17:18 +00005032 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattner81a7a232004-10-16 18:11:37 +00005033 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Cheng2b72c052008-03-25 20:07:13 +00005034 }
Chris Lattner81a7a232004-10-16 18:11:37 +00005035
Chris Lattnerc2076352004-02-16 01:20:27 +00005036 // xor X, X = 0, even if X is nested in a sequence of Xor's.
Owen Andersonb5618da2009-07-03 00:17:18 +00005037 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1), Context)) {
Chris Lattnerf0da7972007-08-05 08:47:58 +00005038 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Owen Andersonb5618da2009-07-03 00:17:18 +00005039 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnerc2076352004-02-16 01:20:27 +00005040 }
Chris Lattner5b2edb12006-02-12 08:02:11 +00005041
5042 // See if we can simplify any instructions used by the instruction whose sole
5043 // purpose is to compute bits we don't care about.
Dan Gohman7ccc52f2009-06-15 22:12:54 +00005044 if (SimplifyDemandedInstructionBits(I))
5045 return &I;
5046 if (isa<VectorType>(I.getType()))
5047 if (isa<ConstantAggregateZero>(Op1))
5048 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005049
Chris Lattner37338922007-06-15 06:23:19 +00005050 // Is this a ~ operation?
Owen Andersonb5618da2009-07-03 00:17:18 +00005051 if (Value *NotOp = dyn_castNotVal(&I, Context)) {
Chris Lattner37338922007-06-15 06:23:19 +00005052 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
5053 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
5054 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5055 if (Op0I->getOpcode() == Instruction::And ||
5056 Op0I->getOpcode() == Instruction::Or) {
Owen Andersonb5618da2009-07-03 00:17:18 +00005057 if (dyn_castNotVal(Op0I->getOperand(1), Context)) Op0I->swapOperands();
5058 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0), Context)) {
Chris Lattner37338922007-06-15 06:23:19 +00005059 Instruction *NotY =
Owen Anderson542619e2009-07-13 20:58:05 +00005060 BinaryOperator::CreateNot(*Context, Op0I->getOperand(1),
Chris Lattner37338922007-06-15 06:23:19 +00005061 Op0I->getOperand(1)->getName()+".not");
5062 InsertNewInstBefore(NotY, I);
5063 if (Op0I->getOpcode() == Instruction::And)
Gabor Greife1f6e4b2008-05-16 19:29:10 +00005064 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Chris Lattner37338922007-06-15 06:23:19 +00005065 else
Gabor Greife1f6e4b2008-05-16 19:29:10 +00005066 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Chris Lattner37338922007-06-15 06:23:19 +00005067 }
5068 }
5069 }
5070 }
5071
5072
Zhou Sheng75b871f2007-01-11 12:24:14 +00005073 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Owen Andersonb5618da2009-07-03 00:17:18 +00005074 if (RHS == Context->getConstantIntTrue() && Op0->hasOneUse()) {
Bill Wendlingaedb54a2009-01-01 01:18:23 +00005075 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
Nick Lewycky80520192007-08-06 20:04:16 +00005076 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Owen Anderson1e5f00e2009-07-09 23:48:35 +00005077 return new ICmpInst(*Context, ICI->getInversePredicate(),
Reid Spencer266e42b2006-12-23 06:05:41 +00005078 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnere5806662003-11-04 23:50:51 +00005079
Nick Lewycky80520192007-08-06 20:04:16 +00005080 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
Owen Anderson1e5f00e2009-07-09 23:48:35 +00005081 return new FCmpInst(*Context, FCI->getInversePredicate(),
Nick Lewycky80520192007-08-06 20:04:16 +00005082 FCI->getOperand(0), FCI->getOperand(1));
5083 }
5084
Nick Lewycky035fe6f2008-05-31 19:01:33 +00005085 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5086 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5087 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5088 if (CI->hasOneUse() && Op0C->hasOneUse()) {
5089 Instruction::CastOps Opcode = Op0C->getOpcode();
5090 if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
Owen Andersonb5618da2009-07-03 00:17:18 +00005091 if (RHS == Context->getConstantExprCast(Opcode,
5092 Context->getConstantIntTrue(),
Nick Lewycky035fe6f2008-05-31 19:01:33 +00005093 Op0C->getDestTy())) {
5094 Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
Owen Anderson1e5f00e2009-07-09 23:48:35 +00005095 *Context,
Nick Lewycky035fe6f2008-05-31 19:01:33 +00005096 CI->getOpcode(), CI->getInversePredicate(),
5097 CI->getOperand(0), CI->getOperand(1)), I);
5098 NewCI->takeName(CI);
5099 return CastInst::Create(Opcode, NewCI, Op0C->getType());
5100 }
5101 }
5102 }
5103 }
5104 }
5105
Reid Spencer266e42b2006-12-23 06:05:41 +00005106 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner8f2f5982003-11-05 01:06:05 +00005107 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00005108 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5109 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Owen Andersonb5618da2009-07-03 00:17:18 +00005110 Constant *NegOp0I0C = Context->getConstantExprNeg(Op0I0C);
5111 Constant *ConstantRHS = Context->getConstantExprSub(NegOp0I0C,
5112 Context->getConstantInt(I.getType(), 1));
Gabor Greife1f6e4b2008-05-16 19:29:10 +00005113 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00005114 }
Chris Lattnerb24acc72007-04-02 05:36:22 +00005115
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +00005116 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Chris Lattner5b2edb12006-02-12 08:02:11 +00005117 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner0f68fa62003-11-04 23:37:10 +00005118 // ~(X-c) --> (-c-1)-X
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00005119 if (RHS->isAllOnesValue()) {
Owen Andersonb5618da2009-07-03 00:17:18 +00005120 Constant *NegOp0CI = Context->getConstantExprNeg(Op0CI);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00005121 return BinaryOperator::CreateSub(
Owen Andersonb5618da2009-07-03 00:17:18 +00005122 Context->getConstantExprSub(NegOp0CI,
5123 Context->getConstantInt(I.getType(), 1)),
5124 Op0I->getOperand(0));
Chris Lattner50490d52007-04-02 05:42:22 +00005125 } else if (RHS->getValue().isSignBit()) {
Chris Lattnerb24acc72007-04-02 05:36:22 +00005126 // (X + C) ^ signbit -> (X + C + signbit)
Owen Andersonb5618da2009-07-03 00:17:18 +00005127 Constant *C =
5128 Context->getConstantInt(RHS->getValue() + Op0CI->getValue());
Gabor Greife1f6e4b2008-05-16 19:29:10 +00005129 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Chris Lattner9d5aace2007-04-02 05:48:58 +00005130
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00005131 }
Chris Lattnerf78df7c2006-02-26 19:57:54 +00005132 } else if (Op0I->getOpcode() == Instruction::Or) {
5133 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencerb722f2b2007-03-22 22:19:58 +00005134 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Owen Andersonb5618da2009-07-03 00:17:18 +00005135 Constant *NewRHS = Context->getConstantExprOr(Op0CI, RHS);
Chris Lattnerf78df7c2006-02-26 19:57:54 +00005136 // Anything in both C1 and C2 is known to be zero, remove it from
5137 // NewRHS.
Owen Andersonb5618da2009-07-03 00:17:18 +00005138 Constant *CommonBits = Context->getConstantExprAnd(Op0CI, RHS);
5139 NewRHS = Context->getConstantExprAnd(NewRHS,
5140 Context->getConstantExprNot(CommonBits));
Chris Lattnerb15e2b12007-03-02 21:28:56 +00005141 AddToWorkList(Op0I);
Chris Lattnerf78df7c2006-02-26 19:57:54 +00005142 I.setOperand(0, Op0I->getOperand(0));
5143 I.setOperand(1, NewRHS);
5144 return &I;
5145 }
Chris Lattner97638592003-07-23 21:37:07 +00005146 }
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +00005147 }
Chris Lattnerb8d6e402002-08-20 18:24:26 +00005148 }
Chris Lattner183b3362004-04-09 19:05:30 +00005149
5150 // Try to fold constant and into select arguments.
5151 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00005152 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00005153 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00005154 if (isa<PHINode>(Op0))
5155 if (Instruction *NV = FoldOpIntoPhi(I))
5156 return NV;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005157 }
5158
Owen Andersonb5618da2009-07-03 00:17:18 +00005159 if (Value *X = dyn_castNotVal(Op0, Context)) // ~A ^ A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00005160 if (X == Op1)
Owen Andersonb5618da2009-07-03 00:17:18 +00005161 return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
Chris Lattner3082c5a2003-02-18 19:28:33 +00005162
Owen Andersonb5618da2009-07-03 00:17:18 +00005163 if (Value *X = dyn_castNotVal(Op1, Context)) // A ^ ~A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00005164 if (X == Op0)
Owen Andersonb5618da2009-07-03 00:17:18 +00005165 return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
Chris Lattner3082c5a2003-02-18 19:28:33 +00005166
Chris Lattner07418422007-03-18 22:51:34 +00005167
5168 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5169 if (Op1I) {
5170 Value *A, *B;
Owen Anderson16e76742009-07-10 17:35:01 +00005171 if (match(Op1I, m_Or(m_Value(A), m_Value(B)), *Context)) {
Chris Lattner07418422007-03-18 22:51:34 +00005172 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00005173 Op1I->swapOperands();
Chris Lattner1bbb7b62003-03-10 18:24:17 +00005174 I.swapOperands();
5175 std::swap(Op0, Op1);
Chris Lattner07418422007-03-18 22:51:34 +00005176 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00005177 I.swapOperands(); // Simplified below.
Chris Lattner1bbb7b62003-03-10 18:24:17 +00005178 std::swap(Op0, Op1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005179 }
Owen Anderson16e76742009-07-10 17:35:01 +00005180 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)), *Context)) {
Chris Lattner44152742008-11-16 05:38:51 +00005181 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
Owen Anderson16e76742009-07-10 17:35:01 +00005182 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)), *Context)) {
Chris Lattner44152742008-11-16 05:38:51 +00005183 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
Owen Anderson16e76742009-07-10 17:35:01 +00005184 } else if (match(Op1I, m_And(m_Value(A), m_Value(B)), *Context) &&
5185 Op1I->hasOneUse()){
Chris Lattner04277992007-04-01 05:36:37 +00005186 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattnerdcd07922006-04-01 08:03:55 +00005187 Op1I->swapOperands();
Chris Lattner04277992007-04-01 05:36:37 +00005188 std::swap(A, B);
5189 }
Chris Lattner07418422007-03-18 22:51:34 +00005190 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattnerdcd07922006-04-01 08:03:55 +00005191 I.swapOperands(); // Simplified below.
5192 std::swap(Op0, Op1);
5193 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00005194 }
Chris Lattner07418422007-03-18 22:51:34 +00005195 }
5196
5197 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5198 if (Op0I) {
5199 Value *A, *B;
Owen Anderson16e76742009-07-10 17:35:01 +00005200 if (match(Op0I, m_Or(m_Value(A), m_Value(B)), *Context) &&
5201 Op0I->hasOneUse()) {
Chris Lattner07418422007-03-18 22:51:34 +00005202 if (A == Op1) // (B|A)^B == (A|B)^B
5203 std::swap(A, B);
5204 if (B == Op1) { // (A|B)^B == A & ~B
5205 Instruction *NotB =
Owen Anderson542619e2009-07-13 20:58:05 +00005206 InsertNewInstBefore(BinaryOperator::CreateNot(*Context,
5207 Op1, "tmp"), I);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00005208 return BinaryOperator::CreateAnd(A, NotB);
Chris Lattner1bbb7b62003-03-10 18:24:17 +00005209 }
Owen Anderson16e76742009-07-10 17:35:01 +00005210 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)), *Context)) {
Chris Lattner44152742008-11-16 05:38:51 +00005211 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
Owen Anderson16e76742009-07-10 17:35:01 +00005212 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)), *Context)) {
Chris Lattner44152742008-11-16 05:38:51 +00005213 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
Owen Anderson16e76742009-07-10 17:35:01 +00005214 } else if (match(Op0I, m_And(m_Value(A), m_Value(B)), *Context) &&
5215 Op0I->hasOneUse()){
Chris Lattner07418422007-03-18 22:51:34 +00005216 if (A == Op1) // (A&B)^A -> (B&A)^A
5217 std::swap(A, B);
5218 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattner6cf49142006-04-01 22:05:01 +00005219 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner07418422007-03-18 22:51:34 +00005220 Instruction *N =
Owen Anderson542619e2009-07-13 20:58:05 +00005221 InsertNewInstBefore(BinaryOperator::CreateNot(*Context, A, "tmp"), I);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00005222 return BinaryOperator::CreateAnd(N, Op1);
Chris Lattnerdcd07922006-04-01 08:03:55 +00005223 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00005224 }
Chris Lattner07418422007-03-18 22:51:34 +00005225 }
5226
5227 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
5228 if (Op0I && Op1I && Op0I->isShift() &&
5229 Op0I->getOpcode() == Op1I->getOpcode() &&
5230 Op0I->getOperand(1) == Op1I->getOperand(1) &&
5231 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5232 Instruction *NewOp =
Gabor Greife1f6e4b2008-05-16 19:29:10 +00005233 InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
Chris Lattner07418422007-03-18 22:51:34 +00005234 Op1I->getOperand(0),
5235 Op0I->getName()), I);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00005236 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Chris Lattner07418422007-03-18 22:51:34 +00005237 Op1I->getOperand(1));
5238 }
5239
5240 if (Op0I && Op1I) {
5241 Value *A, *B, *C, *D;
5242 // (A & B)^(A | B) -> A ^ B
Owen Anderson16e76742009-07-10 17:35:01 +00005243 if (match(Op0I, m_And(m_Value(A), m_Value(B)), *Context) &&
5244 match(Op1I, m_Or(m_Value(C), m_Value(D)), *Context)) {
Chris Lattner07418422007-03-18 22:51:34 +00005245 if ((A == C && B == D) || (A == D && B == C))
Gabor Greife1f6e4b2008-05-16 19:29:10 +00005246 return BinaryOperator::CreateXor(A, B);
Chris Lattner07418422007-03-18 22:51:34 +00005247 }
5248 // (A | B)^(A & B) -> A ^ B
Owen Anderson16e76742009-07-10 17:35:01 +00005249 if (match(Op0I, m_Or(m_Value(A), m_Value(B)), *Context) &&
5250 match(Op1I, m_And(m_Value(C), m_Value(D)), *Context)) {
Chris Lattner07418422007-03-18 22:51:34 +00005251 if ((A == C && B == D) || (A == D && B == C))
Gabor Greife1f6e4b2008-05-16 19:29:10 +00005252 return BinaryOperator::CreateXor(A, B);
Chris Lattner07418422007-03-18 22:51:34 +00005253 }
5254
5255 // (A & B)^(C & D)
5256 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
Owen Anderson16e76742009-07-10 17:35:01 +00005257 match(Op0I, m_And(m_Value(A), m_Value(B)), *Context) &&
5258 match(Op1I, m_And(m_Value(C), m_Value(D)), *Context)) {
Chris Lattner07418422007-03-18 22:51:34 +00005259 // (X & Y)^(X & Y) -> (Y^Z) & X
5260 Value *X = 0, *Y = 0, *Z = 0;
5261 if (A == C)
5262 X = A, Y = B, Z = D;
5263 else if (A == D)
5264 X = A, Y = B, Z = C;
5265 else if (B == C)
5266 X = B, Y = A, Z = D;
5267 else if (B == D)
5268 X = B, Y = A, Z = C;
5269
5270 if (X) {
5271 Instruction *NewOp =
Gabor Greife1f6e4b2008-05-16 19:29:10 +00005272 InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
5273 return BinaryOperator::CreateAnd(NewOp, X);
Chris Lattner07418422007-03-18 22:51:34 +00005274 }
5275 }
5276 }
5277
Reid Spencer266e42b2006-12-23 06:05:41 +00005278 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5279 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
Owen Andersonb5618da2009-07-03 00:17:18 +00005280 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
Chris Lattner3ac7c262003-08-13 20:16:26 +00005281 return R;
5282
Chris Lattner3af10532006-05-05 06:39:07 +00005283 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattnerc62877e2007-10-24 05:38:08 +00005284 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner3af10532006-05-05 06:39:07 +00005285 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer799b5bf2006-12-13 08:27:15 +00005286 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5287 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner03c49532007-01-15 02:27:26 +00005288 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer799b5bf2006-12-13 08:27:15 +00005289 // Only do this if the casts both really cause code to be generated.
Reid Spencer266e42b2006-12-23 06:05:41 +00005290 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5291 I.getType(), TD) &&
5292 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5293 I.getType(), TD)) {
Gabor Greife1f6e4b2008-05-16 19:29:10 +00005294 Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
Reid Spencer799b5bf2006-12-13 08:27:15 +00005295 Op1C->getOperand(0),
5296 I.getName());
5297 InsertNewInstBefore(NewOp, I);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00005298 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer799b5bf2006-12-13 08:27:15 +00005299 }
Chris Lattner3af10532006-05-05 06:39:07 +00005300 }
Chris Lattnerc62877e2007-10-24 05:38:08 +00005301 }
Nick Lewycky035fe6f2008-05-31 19:01:33 +00005302
Chris Lattner113f4f42002-06-25 16:13:24 +00005303 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005304}
5305
Owen Andersonb5618da2009-07-03 00:17:18 +00005306static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
Owen Anderson38264b12009-07-06 23:00:19 +00005307 LLVMContext *Context) {
Owen Andersonb5618da2009-07-03 00:17:18 +00005308 return cast<ConstantInt>(Context->getConstantExprExtractElement(V, Idx));
Dan Gohman7ccc52f2009-06-15 22:12:54 +00005309}
Chris Lattner6862fbd2004-09-29 17:40:11 +00005310
Dan Gohman7ccc52f2009-06-15 22:12:54 +00005311static bool HasAddOverflow(ConstantInt *Result,
5312 ConstantInt *In1, ConstantInt *In2,
5313 bool IsSigned) {
Reid Spencerf4071162007-03-21 23:19:50 +00005314 if (IsSigned)
5315 if (In2->getValue().isNegative())
5316 return Result->getValue().sgt(In1->getValue());
5317 else
5318 return Result->getValue().slt(In1->getValue());
5319 else
5320 return Result->getValue().ult(In1->getValue());
Chris Lattner6862fbd2004-09-29 17:40:11 +00005321}
5322
Dan Gohman7ccc52f2009-06-15 22:12:54 +00005323/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
Dan Gohmanc1ae0162008-09-10 23:30:57 +00005324/// overflowed for this type.
Dan Gohman7ccc52f2009-06-15 22:12:54 +00005325static bool AddWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson38264b12009-07-06 23:00:19 +00005326 Constant *In2, LLVMContext *Context,
Owen Andersonb5618da2009-07-03 00:17:18 +00005327 bool IsSigned = false) {
5328 Result = Context->getConstantExprAdd(In1, In2);
Dan Gohmanc1ae0162008-09-10 23:30:57 +00005329
Dan Gohman7ccc52f2009-06-15 22:12:54 +00005330 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5331 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Andersonb5618da2009-07-03 00:17:18 +00005332 Constant *Idx = Context->getConstantInt(Type::Int32Ty, i);
5333 if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5334 ExtractElement(In1, Idx, Context),
5335 ExtractElement(In2, Idx, Context),
Dan Gohman7ccc52f2009-06-15 22:12:54 +00005336 IsSigned))
5337 return true;
5338 }
5339 return false;
5340 }
5341
5342 return HasAddOverflow(cast<ConstantInt>(Result),
5343 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5344 IsSigned);
5345}
5346
5347static bool HasSubOverflow(ConstantInt *Result,
5348 ConstantInt *In1, ConstantInt *In2,
5349 bool IsSigned) {
Dan Gohmanc1ae0162008-09-10 23:30:57 +00005350 if (IsSigned)
5351 if (In2->getValue().isNegative())
5352 return Result->getValue().slt(In1->getValue());
5353 else
5354 return Result->getValue().sgt(In1->getValue());
5355 else
5356 return Result->getValue().ugt(In1->getValue());
5357}
5358
Dan Gohman7ccc52f2009-06-15 22:12:54 +00005359/// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5360/// overflowed for this type.
5361static bool SubWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson38264b12009-07-06 23:00:19 +00005362 Constant *In2, LLVMContext *Context,
Owen Andersonb5618da2009-07-03 00:17:18 +00005363 bool IsSigned = false) {
5364 Result = Context->getConstantExprSub(In1, In2);
Dan Gohman7ccc52f2009-06-15 22:12:54 +00005365
5366 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5367 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Andersonb5618da2009-07-03 00:17:18 +00005368 Constant *Idx = Context->getConstantInt(Type::Int32Ty, i);
5369 if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5370 ExtractElement(In1, Idx, Context),
5371 ExtractElement(In2, Idx, Context),
Dan Gohman7ccc52f2009-06-15 22:12:54 +00005372 IsSigned))
5373 return true;
5374 }
5375 return false;
5376 }
5377
5378 return HasSubOverflow(cast<ConstantInt>(Result),
5379 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5380 IsSigned);
5381}
5382
Chris Lattner0798af32005-01-13 20:14:25 +00005383/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5384/// code necessary to compute the offset from the base pointer (without adding
5385/// in the base pointer). Return the result as a signed integer of intptr size.
5386static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
5387 TargetData &TD = IC.getTargetData();
5388 gep_type_iterator GTI = gep_type_begin(GEP);
Reid Spencer266e42b2006-12-23 06:05:41 +00005389 const Type *IntPtrTy = TD.getIntPtrType();
Owen Anderson38264b12009-07-06 23:00:19 +00005390 LLVMContext *Context = IC.getContext();
Owen Andersonb5618da2009-07-03 00:17:18 +00005391 Value *Result = Context->getNullValue(IntPtrTy);
Chris Lattner0798af32005-01-13 20:14:25 +00005392
5393 // Build a mask for high order bits.
Chris Lattnerc3a43932008-04-22 02:53:33 +00005394 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Chris Lattner6e880872007-04-28 04:52:43 +00005395 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Chris Lattner0798af32005-01-13 20:14:25 +00005396
Gabor Greiff6d8e772008-06-12 21:37:33 +00005397 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5398 ++i, ++GTI) {
5399 Value *Op = *i;
Duncan Sandsaf9eaa82009-05-09 07:06:46 +00005400 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattner6e880872007-04-28 04:52:43 +00005401 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5402 if (OpC->isZero()) continue;
5403
5404 // Handle a struct index, which adds its field offset to the pointer.
5405 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5406 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5407
5408 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
Owen Andersonb5618da2009-07-03 00:17:18 +00005409 Result =
5410 Context->getConstantInt(RC->getValue() + APInt(IntPtrWidth, Size));
Chris Lattneracbf6a42007-04-28 00:57:34 +00005411 else
Chris Lattner6e880872007-04-28 04:52:43 +00005412 Result = IC.InsertNewInstBefore(
Gabor Greife1f6e4b2008-05-16 19:29:10 +00005413 BinaryOperator::CreateAdd(Result,
Owen Andersonb5618da2009-07-03 00:17:18 +00005414 Context->getConstantInt(IntPtrTy, Size),
Chris Lattner6e880872007-04-28 04:52:43 +00005415 GEP->getName()+".offs"), I);
5416 continue;
Chris Lattneracbf6a42007-04-28 00:57:34 +00005417 }
Chris Lattner6e880872007-04-28 04:52:43 +00005418
Owen Andersonb5618da2009-07-03 00:17:18 +00005419 Constant *Scale = Context->getConstantInt(IntPtrTy, Size);
5420 Constant *OC =
5421 Context->getConstantExprIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5422 Scale = Context->getConstantExprMul(OC, Scale);
Chris Lattner6e880872007-04-28 04:52:43 +00005423 if (Constant *RC = dyn_cast<Constant>(Result))
Owen Andersonb5618da2009-07-03 00:17:18 +00005424 Result = Context->getConstantExprAdd(RC, Scale);
Chris Lattner6e880872007-04-28 04:52:43 +00005425 else {
5426 // Emit an add instruction.
5427 Result = IC.InsertNewInstBefore(
Gabor Greife1f6e4b2008-05-16 19:29:10 +00005428 BinaryOperator::CreateAdd(Result, Scale,
Chris Lattner6e880872007-04-28 04:52:43 +00005429 GEP->getName()+".offs"), I);
Chris Lattneracbf6a42007-04-28 00:57:34 +00005430 }
Chris Lattner6e880872007-04-28 04:52:43 +00005431 continue;
Chris Lattner0798af32005-01-13 20:14:25 +00005432 }
Chris Lattner6e880872007-04-28 04:52:43 +00005433 // Convert to correct type.
5434 if (Op->getType() != IntPtrTy) {
5435 if (Constant *OpC = dyn_cast<Constant>(Op))
Owen Andersonb5618da2009-07-03 00:17:18 +00005436 Op = Context->getConstantExprIntegerCast(OpC, IntPtrTy, true);
Chris Lattner6e880872007-04-28 04:52:43 +00005437 else
Chris Lattner321741a2009-04-07 05:03:34 +00005438 Op = IC.InsertNewInstBefore(CastInst::CreateIntegerCast(Op, IntPtrTy,
5439 true,
5440 Op->getName()+".c"), I);
Chris Lattner6e880872007-04-28 04:52:43 +00005441 }
5442 if (Size != 1) {
Owen Andersonb5618da2009-07-03 00:17:18 +00005443 Constant *Scale = Context->getConstantInt(IntPtrTy, Size);
Chris Lattner6e880872007-04-28 04:52:43 +00005444 if (Constant *OpC = dyn_cast<Constant>(Op))
Owen Andersonb5618da2009-07-03 00:17:18 +00005445 Op = Context->getConstantExprMul(OpC, Scale);
Chris Lattner6e880872007-04-28 04:52:43 +00005446 else // We'll let instcombine(mul) convert this to a shl if possible.
Gabor Greife1f6e4b2008-05-16 19:29:10 +00005447 Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
Chris Lattner6e880872007-04-28 04:52:43 +00005448 GEP->getName()+".idx"), I);
5449 }
5450
5451 // Emit an add instruction.
5452 if (isa<Constant>(Op) && isa<Constant>(Result))
Owen Andersonb5618da2009-07-03 00:17:18 +00005453 Result = Context->getConstantExprAdd(cast<Constant>(Op),
Chris Lattner6e880872007-04-28 04:52:43 +00005454 cast<Constant>(Result));
5455 else
Gabor Greife1f6e4b2008-05-16 19:29:10 +00005456 Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
Chris Lattner6e880872007-04-28 04:52:43 +00005457 GEP->getName()+".offs"), I);
Chris Lattner0798af32005-01-13 20:14:25 +00005458 }
5459 return Result;
5460}
5461
Chris Lattnerc3a43932008-04-22 02:53:33 +00005462
5463/// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
5464/// the *offset* implied by GEP to zero. For example, if we have &A[i], we want
5465/// to return 'i' for "icmp ne i, 0". Note that, in general, indices can be
5466/// complex, and scales are involved. The above expression would also be legal
5467/// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32). This
5468/// later form is less amenable to optimization though, and we are allowed to
5469/// generate the first by knowing that pointer arithmetic doesn't overflow.
5470///
5471/// If we can't emit an optimized form for this expression, this returns null.
5472///
5473static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5474 InstCombiner &IC) {
Chris Lattnerc3a43932008-04-22 02:53:33 +00005475 TargetData &TD = IC.getTargetData();
5476 gep_type_iterator GTI = gep_type_begin(GEP);
5477
5478 // Check to see if this gep only has a single variable index. If so, and if
5479 // any constant indices are a multiple of its scale, then we can compute this
5480 // in terms of the scale of the variable index. For example, if the GEP
5481 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5482 // because the expression will cross zero at the same point.
5483 unsigned i, e = GEP->getNumOperands();
5484 int64_t Offset = 0;
5485 for (i = 1; i != e; ++i, ++GTI) {
5486 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5487 // Compute the aggregate offset of constant indices.
5488 if (CI->isZero()) continue;
5489
5490 // Handle a struct index, which adds its field offset to the pointer.
5491 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5492 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5493 } else {
Duncan Sandsaf9eaa82009-05-09 07:06:46 +00005494 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattnerc3a43932008-04-22 02:53:33 +00005495 Offset += Size*CI->getSExtValue();
5496 }
5497 } else {
5498 // Found our variable index.
5499 break;
5500 }
5501 }
5502
5503 // If there are no variable indices, we must have a constant offset, just
5504 // evaluate it the general way.
5505 if (i == e) return 0;
5506
5507 Value *VariableIdx = GEP->getOperand(i);
5508 // Determine the scale factor of the variable element. For example, this is
5509 // 4 if the variable index is into an array of i32.
Duncan Sandsaf9eaa82009-05-09 07:06:46 +00005510 uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattnerc3a43932008-04-22 02:53:33 +00005511
5512 // Verify that there are no other variable indices. If so, emit the hard way.
5513 for (++i, ++GTI; i != e; ++i, ++GTI) {
5514 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5515 if (!CI) return 0;
5516
5517 // Compute the aggregate offset of constant indices.
5518 if (CI->isZero()) continue;
5519
5520 // Handle a struct index, which adds its field offset to the pointer.
5521 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5522 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5523 } else {
Duncan Sandsaf9eaa82009-05-09 07:06:46 +00005524 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattnerc3a43932008-04-22 02:53:33 +00005525 Offset += Size*CI->getSExtValue();
5526 }
5527 }
5528
5529 // Okay, we know we have a single variable index, which must be a
5530 // pointer/array/vector index. If there is no offset, life is simple, return
5531 // the index.
5532 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5533 if (Offset == 0) {
5534 // Cast to intptrty in case a truncation occurs. If an extension is needed,
5535 // we don't need to bother extending: the extension won't affect where the
5536 // computation crosses zero.
5537 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5538 VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
5539 VariableIdx->getNameStart(), &I);
5540 return VariableIdx;
5541 }
5542
5543 // Otherwise, there is an index. The computation we will do will be modulo
5544 // the pointer size, so get it.
5545 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5546
5547 Offset &= PtrSizeMask;
5548 VariableScale &= PtrSizeMask;
5549
5550 // To do this transformation, any constant index must be a multiple of the
5551 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
5552 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
5553 // multiple of the variable scale.
5554 int64_t NewOffs = Offset / (int64_t)VariableScale;
5555 if (Offset != NewOffs*(int64_t)VariableScale)
5556 return 0;
5557
5558 // Okay, we can do this evaluation. Start by converting the index to intptr.
5559 const Type *IntPtrTy = TD.getIntPtrType();
5560 if (VariableIdx->getType() != IntPtrTy)
Gabor Greife1f6e4b2008-05-16 19:29:10 +00005561 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
Chris Lattnerc3a43932008-04-22 02:53:33 +00005562 true /*SExt*/,
5563 VariableIdx->getNameStart(), &I);
Owen Andersonb5618da2009-07-03 00:17:18 +00005564 Constant *OffsetVal = IC.getContext()->getConstantInt(IntPtrTy, NewOffs);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00005565 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
Chris Lattnerc3a43932008-04-22 02:53:33 +00005566}
5567
5568
Reid Spencer266e42b2006-12-23 06:05:41 +00005569/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner0798af32005-01-13 20:14:25 +00005570/// else. At this point we know that the GEP is on the LHS of the comparison.
Reid Spencer266e42b2006-12-23 06:05:41 +00005571Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
5572 ICmpInst::Predicate Cond,
5573 Instruction &I) {
Chris Lattner0798af32005-01-13 20:14:25 +00005574 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattner81e84172005-01-13 22:25:21 +00005575
Chris Lattnerc3a43932008-04-22 02:53:33 +00005576 // Look through bitcasts.
5577 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5578 RHS = BCI->getOperand(0);
Chris Lattner81e84172005-01-13 22:25:21 +00005579
Chris Lattner0798af32005-01-13 20:14:25 +00005580 Value *PtrBase = GEPLHS->getOperand(0);
5581 if (PtrBase == RHS) {
Chris Lattner682a7dc2008-02-05 04:45:32 +00005582 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattnerc3a43932008-04-22 02:53:33 +00005583 // This transformation (ignoring the base and scales) is valid because we
5584 // know pointers can't overflow. See if we can output an optimized form.
5585 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5586
5587 // If not, synthesize the offset the hard way.
5588 if (Offset == 0)
5589 Offset = EmitGEPOffset(GEPLHS, I, *this);
Owen Anderson1e5f00e2009-07-09 23:48:35 +00005590 return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond), Offset,
Owen Andersonb5618da2009-07-03 00:17:18 +00005591 Context->getNullValue(Offset->getType()));
Chris Lattner0798af32005-01-13 20:14:25 +00005592 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera21bf8d2005-04-25 20:17:30 +00005593 // If the base pointers are different, but the indices are the same, just
5594 // compare the base pointer.
5595 if (PtrBase != GEPRHS->getOperand(0)) {
5596 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00005597 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattnerbd43b9d2005-04-26 14:40:41 +00005598 GEPRHS->getOperand(0)->getType();
Chris Lattnera21bf8d2005-04-25 20:17:30 +00005599 if (IndicesTheSame)
5600 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5601 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5602 IndicesTheSame = false;
5603 break;
5604 }
5605
5606 // If all indices are the same, just compare the base pointers.
5607 if (IndicesTheSame)
Owen Anderson1e5f00e2009-07-09 23:48:35 +00005608 return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond),
Reid Spencer266e42b2006-12-23 06:05:41 +00005609 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera21bf8d2005-04-25 20:17:30 +00005610
5611 // Otherwise, the base pointers are different and the indices are
5612 // different, bail out.
Chris Lattner0798af32005-01-13 20:14:25 +00005613 return 0;
Chris Lattnera21bf8d2005-04-25 20:17:30 +00005614 }
Chris Lattner0798af32005-01-13 20:14:25 +00005615
Chris Lattner81e84172005-01-13 22:25:21 +00005616 // If one of the GEPs has all zero indices, recurse.
5617 bool AllZeros = true;
5618 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5619 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5620 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5621 AllZeros = false;
5622 break;
5623 }
5624 if (AllZeros)
Reid Spencer266e42b2006-12-23 06:05:41 +00005625 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5626 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4fa89822005-01-14 00:20:05 +00005627
5628 // If the other GEP has all zero indices, recurse.
Chris Lattner81e84172005-01-13 22:25:21 +00005629 AllZeros = true;
5630 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5631 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5632 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5633 AllZeros = false;
5634 break;
5635 }
5636 if (AllZeros)
Reid Spencer266e42b2006-12-23 06:05:41 +00005637 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattner81e84172005-01-13 22:25:21 +00005638
Chris Lattner4fa89822005-01-14 00:20:05 +00005639 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5640 // If the GEPs only differ by one index, compare it.
5641 unsigned NumDifferences = 0; // Keep track of # differences.
5642 unsigned DiffOperand = 0; // The operand that differs.
5643 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5644 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005645 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5646 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00005647 // Irreconcilable differences.
Chris Lattner4fa89822005-01-14 00:20:05 +00005648 NumDifferences = 2;
5649 break;
5650 } else {
5651 if (NumDifferences++) break;
5652 DiffOperand = i;
5653 }
5654 }
5655
5656 if (NumDifferences == 0) // SAME GEP?
5657 return ReplaceInstUsesWith(I, // No comparison is needed here.
Owen Andersonb5618da2009-07-03 00:17:18 +00005658 Context->getConstantInt(Type::Int1Ty,
Nick Lewycky79376f42008-05-17 07:33:39 +00005659 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky0c5c4792007-09-06 02:40:25 +00005660
Chris Lattner4fa89822005-01-14 00:20:05 +00005661 else if (NumDifferences == 1) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00005662 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5663 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencer266e42b2006-12-23 06:05:41 +00005664 // Make sure we do a signed comparison here.
Owen Anderson1e5f00e2009-07-09 23:48:35 +00005665 return new ICmpInst(*Context,
5666 ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4fa89822005-01-14 00:20:05 +00005667 }
5668 }
5669
Reid Spencer266e42b2006-12-23 06:05:41 +00005670 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner0798af32005-01-13 20:14:25 +00005671 // the result to fold to a constant!
5672 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5673 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5674 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
5675 Value *L = EmitGEPOffset(GEPLHS, I, *this);
5676 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Owen Anderson1e5f00e2009-07-09 23:48:35 +00005677 return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner0798af32005-01-13 20:14:25 +00005678 }
5679 }
5680 return 0;
5681}
5682
Chris Lattner5920a782008-05-19 20:18:56 +00005683/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5684///
5685Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5686 Instruction *LHSI,
5687 Constant *RHSC) {
5688 if (!isa<ConstantFP>(RHSC)) return 0;
5689 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5690
5691 // Get the width of the mantissa. We don't want to hack on conversions that
5692 // might lose information from the integer, e.g. "i64 -> float"
Chris Lattnerb4271222008-05-19 21:17:23 +00005693 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Chris Lattner5920a782008-05-19 20:18:56 +00005694 if (MantissaWidth == -1) return 0; // Unknown.
5695
5696 // Check to see that the input is converted from an integer type that is small
5697 // enough that preserves all bits. TODO: check here for "known" sign bits.
5698 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
Dan Gohman7ccc52f2009-06-15 22:12:54 +00005699 unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
Chris Lattner5920a782008-05-19 20:18:56 +00005700
5701 // If this is a uitofp instruction, we need an extra bit to hold the sign.
Bill Wendling3f547be2008-11-09 04:26:50 +00005702 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5703 if (LHSUnsigned)
Chris Lattner5920a782008-05-19 20:18:56 +00005704 ++InputSize;
5705
5706 // If the conversion would lose info, don't hack on this.
5707 if ((int)InputSize > MantissaWidth)
5708 return 0;
5709
5710 // Otherwise, we can potentially simplify the comparison. We know that it
5711 // will always come through as an integer value and we know the constant is
5712 // not a NAN (it would have been previously simplified).
5713 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5714
5715 ICmpInst::Predicate Pred;
5716 switch (I.getPredicate()) {
Torok Edwin56d06592009-07-11 20:10:48 +00005717 default: LLVM_UNREACHABLE("Unexpected predicate!");
Chris Lattner5920a782008-05-19 20:18:56 +00005718 case FCmpInst::FCMP_UEQ:
Bill Wendling3f547be2008-11-09 04:26:50 +00005719 case FCmpInst::FCMP_OEQ:
5720 Pred = ICmpInst::ICMP_EQ;
5721 break;
Chris Lattner5920a782008-05-19 20:18:56 +00005722 case FCmpInst::FCMP_UGT:
Bill Wendling3f547be2008-11-09 04:26:50 +00005723 case FCmpInst::FCMP_OGT:
5724 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5725 break;
Chris Lattner5920a782008-05-19 20:18:56 +00005726 case FCmpInst::FCMP_UGE:
Bill Wendling3f547be2008-11-09 04:26:50 +00005727 case FCmpInst::FCMP_OGE:
5728 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5729 break;
Chris Lattner5920a782008-05-19 20:18:56 +00005730 case FCmpInst::FCMP_ULT:
Bill Wendling3f547be2008-11-09 04:26:50 +00005731 case FCmpInst::FCMP_OLT:
5732 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5733 break;
Chris Lattner5920a782008-05-19 20:18:56 +00005734 case FCmpInst::FCMP_ULE:
Bill Wendling3f547be2008-11-09 04:26:50 +00005735 case FCmpInst::FCMP_OLE:
5736 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5737 break;
Chris Lattner5920a782008-05-19 20:18:56 +00005738 case FCmpInst::FCMP_UNE:
Bill Wendling3f547be2008-11-09 04:26:50 +00005739 case FCmpInst::FCMP_ONE:
5740 Pred = ICmpInst::ICMP_NE;
5741 break;
Chris Lattner5920a782008-05-19 20:18:56 +00005742 case FCmpInst::FCMP_ORD:
Owen Andersonb5618da2009-07-03 00:17:18 +00005743 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Chris Lattner5920a782008-05-19 20:18:56 +00005744 case FCmpInst::FCMP_UNO:
Owen Andersonb5618da2009-07-03 00:17:18 +00005745 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Chris Lattner5920a782008-05-19 20:18:56 +00005746 }
5747
5748 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5749
5750 // Now we know that the APFloat is a normal number, zero or inf.
5751
Chris Lattner9c27f962008-05-20 03:50:52 +00005752 // See if the FP constant is too large for the integer. For example,
Chris Lattner5920a782008-05-19 20:18:56 +00005753 // comparing an i8 to 300.0.
Dan Gohman7ccc52f2009-06-15 22:12:54 +00005754 unsigned IntWidth = IntTy->getScalarSizeInBits();
Chris Lattner5920a782008-05-19 20:18:56 +00005755
Bill Wendling3f547be2008-11-09 04:26:50 +00005756 if (!LHSUnsigned) {
5757 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5758 // and large values.
5759 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5760 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5761 APFloat::rmNearestTiesToEven);
5762 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5763 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
5764 Pred == ICmpInst::ICMP_SLE)
Owen Andersonb5618da2009-07-03 00:17:18 +00005765 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5766 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Bill Wendling3f547be2008-11-09 04:26:50 +00005767 }
5768 } else {
5769 // If the RHS value is > UnsignedMax, fold the comparison. This handles
5770 // +INF and large values.
5771 APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5772 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5773 APFloat::rmNearestTiesToEven);
5774 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
5775 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
5776 Pred == ICmpInst::ICMP_ULE)
Owen Andersonb5618da2009-07-03 00:17:18 +00005777 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5778 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Bill Wendling3f547be2008-11-09 04:26:50 +00005779 }
Chris Lattner5920a782008-05-19 20:18:56 +00005780 }
5781
Bill Wendling3f547be2008-11-09 04:26:50 +00005782 if (!LHSUnsigned) {
5783 // See if the RHS value is < SignedMin.
5784 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5785 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5786 APFloat::rmNearestTiesToEven);
5787 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5788 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5789 Pred == ICmpInst::ICMP_SGE)
Owen Andersonb5618da2009-07-03 00:17:18 +00005790 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5791 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Bill Wendling3f547be2008-11-09 04:26:50 +00005792 }
Chris Lattner5920a782008-05-19 20:18:56 +00005793 }
5794
Bill Wendling3f547be2008-11-09 04:26:50 +00005795 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5796 // [0, UMAX], but it may still be fractional. See if it is fractional by
5797 // casting the FP value to the integer value and back, checking for equality.
5798 // Don't do this for zero, because -0.0 is not fractional.
Evan Chenga838a402009-05-22 23:10:53 +00005799 Constant *RHSInt = LHSUnsigned
Owen Andersonb5618da2009-07-03 00:17:18 +00005800 ? Context->getConstantExprFPToUI(RHSC, IntTy)
5801 : Context->getConstantExprFPToSI(RHSC, IntTy);
Evan Chenga838a402009-05-22 23:10:53 +00005802 if (!RHS.isZero()) {
5803 bool Equal = LHSUnsigned
Owen Andersonb5618da2009-07-03 00:17:18 +00005804 ? Context->getConstantExprUIToFP(RHSInt, RHSC->getType()) == RHSC
5805 : Context->getConstantExprSIToFP(RHSInt, RHSC->getType()) == RHSC;
Evan Chenga838a402009-05-22 23:10:53 +00005806 if (!Equal) {
5807 // If we had a comparison against a fractional value, we have to adjust
5808 // the compare predicate and sometimes the value. RHSC is rounded towards
5809 // zero at this point.
5810 switch (Pred) {
Torok Edwin56d06592009-07-11 20:10:48 +00005811 default: LLVM_UNREACHABLE("Unexpected integer comparison!");
Evan Chenga838a402009-05-22 23:10:53 +00005812 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
Owen Andersonb5618da2009-07-03 00:17:18 +00005813 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Evan Chenga838a402009-05-22 23:10:53 +00005814 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
Owen Andersonb5618da2009-07-03 00:17:18 +00005815 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Evan Chenga838a402009-05-22 23:10:53 +00005816 case ICmpInst::ICMP_ULE:
5817 // (float)int <= 4.4 --> int <= 4
5818 // (float)int <= -4.4 --> false
5819 if (RHS.isNegative())
Owen Andersonb5618da2009-07-03 00:17:18 +00005820 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Evan Chenga838a402009-05-22 23:10:53 +00005821 break;
5822 case ICmpInst::ICMP_SLE:
5823 // (float)int <= 4.4 --> int <= 4
5824 // (float)int <= -4.4 --> int < -4
5825 if (RHS.isNegative())
5826 Pred = ICmpInst::ICMP_SLT;
5827 break;
5828 case ICmpInst::ICMP_ULT:
5829 // (float)int < -4.4 --> false
5830 // (float)int < 4.4 --> int <= 4
5831 if (RHS.isNegative())
Owen Andersonb5618da2009-07-03 00:17:18 +00005832 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Evan Chenga838a402009-05-22 23:10:53 +00005833 Pred = ICmpInst::ICMP_ULE;
5834 break;
5835 case ICmpInst::ICMP_SLT:
5836 // (float)int < -4.4 --> int < -4
5837 // (float)int < 4.4 --> int <= 4
5838 if (!RHS.isNegative())
5839 Pred = ICmpInst::ICMP_SLE;
5840 break;
5841 case ICmpInst::ICMP_UGT:
5842 // (float)int > 4.4 --> int > 4
5843 // (float)int > -4.4 --> true
5844 if (RHS.isNegative())
Owen Andersonb5618da2009-07-03 00:17:18 +00005845 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Evan Chenga838a402009-05-22 23:10:53 +00005846 break;
5847 case ICmpInst::ICMP_SGT:
5848 // (float)int > 4.4 --> int > 4
5849 // (float)int > -4.4 --> int >= -4
5850 if (RHS.isNegative())
5851 Pred = ICmpInst::ICMP_SGE;
5852 break;
5853 case ICmpInst::ICMP_UGE:
5854 // (float)int >= -4.4 --> true
5855 // (float)int >= 4.4 --> int > 4
5856 if (!RHS.isNegative())
Owen Andersonb5618da2009-07-03 00:17:18 +00005857 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Evan Chenga838a402009-05-22 23:10:53 +00005858 Pred = ICmpInst::ICMP_UGT;
5859 break;
5860 case ICmpInst::ICMP_SGE:
5861 // (float)int >= -4.4 --> int >= -4
5862 // (float)int >= 4.4 --> int > 4
5863 if (!RHS.isNegative())
5864 Pred = ICmpInst::ICMP_SGT;
5865 break;
5866 }
Chris Lattner5920a782008-05-19 20:18:56 +00005867 }
5868 }
5869
5870 // Lower this FP comparison into an appropriate integer version of the
5871 // comparison.
Owen Anderson1e5f00e2009-07-09 23:48:35 +00005872 return new ICmpInst(*Context, Pred, LHSI->getOperand(0), RHSInt);
Chris Lattner5920a782008-05-19 20:18:56 +00005873}
5874
Reid Spencer266e42b2006-12-23 06:05:41 +00005875Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5876 bool Changed = SimplifyCompare(I);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00005877 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005878
Chris Lattner6ee923f2007-01-14 19:42:17 +00005879 // Fold trivial predicates.
5880 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
Owen Andersonb5618da2009-07-03 00:17:18 +00005881 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Chris Lattner6ee923f2007-01-14 19:42:17 +00005882 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
Owen Andersonb5618da2009-07-03 00:17:18 +00005883 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Chris Lattner6ee923f2007-01-14 19:42:17 +00005884
5885 // Simplify 'fcmp pred X, X'
5886 if (Op0 == Op1) {
5887 switch (I.getPredicate()) {
Torok Edwin56d06592009-07-11 20:10:48 +00005888 default: LLVM_UNREACHABLE("Unknown predicate!");
Chris Lattner6ee923f2007-01-14 19:42:17 +00005889 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5890 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5891 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
Owen Andersonb5618da2009-07-03 00:17:18 +00005892 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Chris Lattner6ee923f2007-01-14 19:42:17 +00005893 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5894 case FCmpInst::FCMP_OLT: // True if ordered and less than
5895 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
Owen Andersonb5618da2009-07-03 00:17:18 +00005896 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Chris Lattner6ee923f2007-01-14 19:42:17 +00005897
5898 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5899 case FCmpInst::FCMP_ULT: // True if unordered or less than
5900 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5901 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5902 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5903 I.setPredicate(FCmpInst::FCMP_UNO);
Owen Andersonb5618da2009-07-03 00:17:18 +00005904 I.setOperand(1, Context->getNullValue(Op0->getType()));
Chris Lattner6ee923f2007-01-14 19:42:17 +00005905 return &I;
5906
5907 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5908 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5909 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5910 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5911 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5912 I.setPredicate(FCmpInst::FCMP_ORD);
Owen Andersonb5618da2009-07-03 00:17:18 +00005913 I.setOperand(1, Context->getNullValue(Op0->getType()));
Chris Lattner6ee923f2007-01-14 19:42:17 +00005914 return &I;
5915 }
5916 }
5917
Reid Spencer266e42b2006-12-23 06:05:41 +00005918 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Owen Andersonb5618da2009-07-03 00:17:18 +00005919 return ReplaceInstUsesWith(I, Context->getUndef(Type::Int1Ty));
Chris Lattner81a7a232004-10-16 18:11:37 +00005920
Reid Spencer266e42b2006-12-23 06:05:41 +00005921 // Handle fcmp with constant RHS
5922 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
Chris Lattner5920a782008-05-19 20:18:56 +00005923 // If the constant is a nan, see if we can fold the comparison based on it.
5924 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5925 if (CFP->getValueAPF().isNaN()) {
5926 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
Owen Andersonb5618da2009-07-03 00:17:18 +00005927 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Chris Lattner9c27f962008-05-20 03:50:52 +00005928 assert(FCmpInst::isUnordered(I.getPredicate()) &&
5929 "Comparison must be either ordered or unordered!");
5930 // True if unordered.
Owen Andersonb5618da2009-07-03 00:17:18 +00005931 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Chris Lattner5920a782008-05-19 20:18:56 +00005932 }
5933 }
5934
Reid Spencer266e42b2006-12-23 06:05:41 +00005935 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5936 switch (LHSI->getOpcode()) {
5937 case Instruction::PHI:
Chris Lattnerb4866ef2008-06-08 20:52:11 +00005938 // Only fold fcmp into the PHI if the phi and fcmp are in the same
5939 // block. If in the same block, we're encouraging jump threading. If
5940 // not, we are just pessimizing the code by making an i1 phi.
5941 if (LHSI->getParent() == I.getParent())
5942 if (Instruction *NV = FoldOpIntoPhi(I))
5943 return NV;
Reid Spencer266e42b2006-12-23 06:05:41 +00005944 break;
Chris Lattner5920a782008-05-19 20:18:56 +00005945 case Instruction::SIToFP:
5946 case Instruction::UIToFP:
5947 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5948 return NV;
5949 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00005950 case Instruction::Select:
5951 // If either operand of the select is a constant, we can fold the
5952 // comparison into the select arms, which will cause one to be
5953 // constant folded and the select turned into a bitwise or.
5954 Value *Op1 = 0, *Op2 = 0;
5955 if (LHSI->hasOneUse()) {
5956 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5957 // Fold the known value into the constant operand.
Owen Andersonb5618da2009-07-03 00:17:18 +00005958 Op1 = Context->getConstantExprCompare(I.getPredicate(), C, RHSC);
Reid Spencer266e42b2006-12-23 06:05:41 +00005959 // Insert a new FCmp of the other select operand.
Owen Anderson1e5f00e2009-07-09 23:48:35 +00005960 Op2 = InsertNewInstBefore(new FCmpInst(*Context, I.getPredicate(),
Reid Spencer266e42b2006-12-23 06:05:41 +00005961 LHSI->getOperand(2), RHSC,
5962 I.getName()), I);
5963 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5964 // Fold the known value into the constant operand.
Owen Andersonb5618da2009-07-03 00:17:18 +00005965 Op2 = Context->getConstantExprCompare(I.getPredicate(), C, RHSC);
Reid Spencer266e42b2006-12-23 06:05:41 +00005966 // Insert a new FCmp of the other select operand.
Owen Anderson1e5f00e2009-07-09 23:48:35 +00005967 Op1 = InsertNewInstBefore(new FCmpInst(*Context, I.getPredicate(),
Reid Spencer266e42b2006-12-23 06:05:41 +00005968 LHSI->getOperand(1), RHSC,
5969 I.getName()), I);
5970 }
5971 }
5972
5973 if (Op1)
Gabor Greife9ecc682008-04-06 20:25:17 +00005974 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Reid Spencer266e42b2006-12-23 06:05:41 +00005975 break;
5976 }
5977 }
5978
5979 return Changed ? &I : 0;
5980}
5981
5982Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5983 bool Changed = SimplifyCompare(I);
5984 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5985 const Type *Ty = Op0->getType();
5986
5987 // icmp X, X
5988 if (Op0 == Op1)
Owen Andersonb5618da2009-07-03 00:17:18 +00005989 return ReplaceInstUsesWith(I, Context->getConstantInt(Type::Int1Ty,
Nick Lewycky79376f42008-05-17 07:33:39 +00005990 I.isTrueWhenEqual()));
Reid Spencer266e42b2006-12-23 06:05:41 +00005991
5992 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Owen Andersonb5618da2009-07-03 00:17:18 +00005993 return ReplaceInstUsesWith(I, Context->getUndef(Type::Int1Ty));
Christopher Lambf00ac6d2007-12-18 21:32:20 +00005994
Reid Spencer266e42b2006-12-23 06:05:41 +00005995 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner15ff1e12004-11-14 07:33:16 +00005996 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanb1c93172005-04-21 23:48:37 +00005997 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5998 isa<ConstantPointerNull>(Op0)) &&
5999 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner15ff1e12004-11-14 07:33:16 +00006000 isa<ConstantPointerNull>(Op1)))
Owen Andersonb5618da2009-07-03 00:17:18 +00006001 return ReplaceInstUsesWith(I, Context->getConstantInt(Type::Int1Ty,
Nick Lewycky79376f42008-05-17 07:33:39 +00006002 !I.isTrueWhenEqual()));
Chris Lattner6d14f2a2002-08-09 23:47:40 +00006003
Reid Spencer266e42b2006-12-23 06:05:41 +00006004 // icmp's with boolean values can always be turned into bitwise operations
Reid Spencer542964f2007-01-11 18:21:29 +00006005 if (Ty == Type::Int1Ty) {
Reid Spencer266e42b2006-12-23 06:05:41 +00006006 switch (I.getPredicate()) {
Torok Edwin56d06592009-07-11 20:10:48 +00006007 default: LLVM_UNREACHABLE("Invalid icmp instruction!");
Chris Lattner6af608b2008-07-11 04:20:58 +00006008 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
Gabor Greife1f6e4b2008-05-16 19:29:10 +00006009 Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +00006010 InsertNewInstBefore(Xor, I);
Owen Anderson542619e2009-07-13 20:58:05 +00006011 return BinaryOperator::CreateNot(*Context, Xor);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00006012 }
Chris Lattner6af608b2008-07-11 04:20:58 +00006013 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
Gabor Greife1f6e4b2008-05-16 19:29:10 +00006014 return BinaryOperator::CreateXor(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00006015
Reid Spencer266e42b2006-12-23 06:05:41 +00006016 case ICmpInst::ICMP_UGT:
Chris Lattner6af608b2008-07-11 04:20:58 +00006017 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
Chris Lattner4456da62004-08-11 00:50:51 +00006018 // FALL THROUGH
Chris Lattner6af608b2008-07-11 04:20:58 +00006019 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
Owen Anderson542619e2009-07-13 20:58:05 +00006020 Instruction *Not = BinaryOperator::CreateNot(*Context,
6021 Op0, I.getName()+"tmp");
Chris Lattner4456da62004-08-11 00:50:51 +00006022 InsertNewInstBefore(Not, I);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00006023 return BinaryOperator::CreateAnd(Not, Op1);
Chris Lattner4456da62004-08-11 00:50:51 +00006024 }
Chris Lattner6af608b2008-07-11 04:20:58 +00006025 case ICmpInst::ICMP_SGT:
6026 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
Chris Lattner4456da62004-08-11 00:50:51 +00006027 // FALL THROUGH
Chris Lattner6af608b2008-07-11 04:20:58 +00006028 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
Owen Anderson542619e2009-07-13 20:58:05 +00006029 Instruction *Not = BinaryOperator::CreateNot(*Context,
6030 Op1, I.getName()+"tmp");
Chris Lattner6af608b2008-07-11 04:20:58 +00006031 InsertNewInstBefore(Not, I);
6032 return BinaryOperator::CreateAnd(Not, Op0);
6033 }
6034 case ICmpInst::ICMP_UGE:
6035 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
6036 // FALL THROUGH
6037 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
Owen Anderson542619e2009-07-13 20:58:05 +00006038 Instruction *Not = BinaryOperator::CreateNot(*Context,
6039 Op0, I.getName()+"tmp");
Chris Lattner4456da62004-08-11 00:50:51 +00006040 InsertNewInstBefore(Not, I);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00006041 return BinaryOperator::CreateOr(Not, Op1);
Chris Lattner4456da62004-08-11 00:50:51 +00006042 }
Chris Lattner6af608b2008-07-11 04:20:58 +00006043 case ICmpInst::ICMP_SGE:
6044 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
6045 // FALL THROUGH
6046 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
Owen Anderson542619e2009-07-13 20:58:05 +00006047 Instruction *Not = BinaryOperator::CreateNot(*Context,
6048 Op1, I.getName()+"tmp");
Chris Lattner6af608b2008-07-11 04:20:58 +00006049 InsertNewInstBefore(Not, I);
6050 return BinaryOperator::CreateOr(Not, Op0);
6051 }
Chris Lattner4456da62004-08-11 00:50:51 +00006052 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +00006053 }
6054
Dan Gohman5638e0d2009-04-25 17:12:48 +00006055 unsigned BitWidth = 0;
6056 if (TD)
Dan Gohman0ed77562009-06-16 19:55:29 +00006057 BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
6058 else if (Ty->isIntOrIntVector())
6059 BitWidth = Ty->getScalarSizeInBits();
Dan Gohman5638e0d2009-04-25 17:12:48 +00006060
6061 bool isSignBit = false;
6062
Dan Gohmandafa9c62008-09-16 18:46:06 +00006063 // See if we are doing a comparison with a constant.
Chris Lattner6d14f2a2002-08-09 23:47:40 +00006064 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky34709f82009-02-27 06:37:39 +00006065 Value *A = 0, *B = 0;
Christopher Lamb7d82bc42007-12-20 07:21:11 +00006066
Chris Lattnerdb026d72008-01-05 01:18:20 +00006067 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
6068 if (I.isEquality() && CI->isNullValue() &&
Owen Anderson16e76742009-07-10 17:35:01 +00006069 match(Op0, m_Sub(m_Value(A), m_Value(B)), *Context)) {
Chris Lattnerdb026d72008-01-05 01:18:20 +00006070 // (icmp cond A B) if cond is equality
Owen Anderson1e5f00e2009-07-09 23:48:35 +00006071 return new ICmpInst(*Context, I.getPredicate(), A, B);
Owen Anderson73639142007-12-28 07:42:12 +00006072 }
Christopher Lamb7d82bc42007-12-20 07:21:11 +00006073
Dan Gohmandafa9c62008-09-16 18:46:06 +00006074 // If we have an icmp le or icmp ge instruction, turn it into the
6075 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
6076 // them being folded in the code below.
Chris Lattner38a50c92008-07-11 05:08:55 +00006077 switch (I.getPredicate()) {
6078 default: break;
6079 case ICmpInst::ICMP_ULE:
6080 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Owen Andersonb5618da2009-07-03 00:17:18 +00006081 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Owen Anderson1e5f00e2009-07-09 23:48:35 +00006082 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Op0,
6083 AddOne(CI, Context));
Chris Lattner38a50c92008-07-11 05:08:55 +00006084 case ICmpInst::ICMP_SLE:
6085 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Owen Andersonb5618da2009-07-03 00:17:18 +00006086 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Owen Anderson1e5f00e2009-07-09 23:48:35 +00006087 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Op0,
6088 AddOne(CI, Context));
Chris Lattner38a50c92008-07-11 05:08:55 +00006089 case ICmpInst::ICMP_UGE:
6090 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
Owen Andersonb5618da2009-07-03 00:17:18 +00006091 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Owen Anderson1e5f00e2009-07-09 23:48:35 +00006092 return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Op0,
6093 SubOne(CI, Context));
Chris Lattner38a50c92008-07-11 05:08:55 +00006094 case ICmpInst::ICMP_SGE:
6095 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Owen Andersonb5618da2009-07-03 00:17:18 +00006096 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Owen Anderson1e5f00e2009-07-09 23:48:35 +00006097 return new ICmpInst(*Context, ICmpInst::ICMP_SGT, Op0,
6098 SubOne(CI, Context));
Chris Lattner38a50c92008-07-11 05:08:55 +00006099 }
6100
Chris Lattnerbd25b852008-07-11 05:40:05 +00006101 // If this comparison is a normal comparison, it demands all
Chris Lattnerd4fef8d2007-07-15 20:54:51 +00006102 // bits, if it is a sign bit comparison, it only demands the sign bit.
Chris Lattnerd4fef8d2007-07-15 20:54:51 +00006103 bool UnusedBit;
Dan Gohman5638e0d2009-04-25 17:12:48 +00006104 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6105 }
6106
6107 // See if we can fold the comparison based on range information we can get
6108 // by checking whether bits are known to be zero or one in the input.
6109 if (BitWidth != 0) {
6110 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6111 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6112
6113 if (SimplifyDemandedBits(I.getOperandUse(0),
Chris Lattnerd4fef8d2007-07-15 20:54:51 +00006114 isSignBit ? APInt::getSignBit(BitWidth)
6115 : APInt::getAllOnesValue(BitWidth),
Dan Gohman5638e0d2009-04-25 17:12:48 +00006116 Op0KnownZero, Op0KnownOne, 0))
Chris Lattneree0f2802006-02-12 02:07:56 +00006117 return &I;
Dan Gohman5638e0d2009-04-25 17:12:48 +00006118 if (SimplifyDemandedBits(I.getOperandUse(1),
6119 APInt::getAllOnesValue(BitWidth),
6120 Op1KnownZero, Op1KnownOne, 0))
6121 return &I;
6122
Chris Lattneree0f2802006-02-12 02:07:56 +00006123 // Given the known and unknown bits, compute a range that the LHS could be
Chris Lattner38a50c92008-07-11 05:08:55 +00006124 // in. Compute the Min, Max and RHS values based on the known bits. For the
6125 // EQ and NE we use unsigned values.
Dan Gohman5638e0d2009-04-25 17:12:48 +00006126 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6127 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
6128 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
6129 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6130 Op0Min, Op0Max);
6131 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6132 Op1Min, Op1Max);
6133 } else {
6134 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6135 Op0Min, Op0Max);
6136 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6137 Op1Min, Op1Max);
6138 }
6139
Chris Lattnerbd25b852008-07-11 05:40:05 +00006140 // If Min and Max are known to be the same, then SimplifyDemandedBits
6141 // figured out that the LHS is a constant. Just constant fold this now so
6142 // that code below can assume that Min != Max.
Dan Gohman5638e0d2009-04-25 17:12:48 +00006143 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
Owen Anderson1e5f00e2009-07-09 23:48:35 +00006144 return new ICmpInst(*Context, I.getPredicate(),
Owen Andersonb5618da2009-07-03 00:17:18 +00006145 Context->getConstantInt(Op0Min), Op1);
Dan Gohman5638e0d2009-04-25 17:12:48 +00006146 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
Owen Anderson1e5f00e2009-07-09 23:48:35 +00006147 return new ICmpInst(*Context, I.getPredicate(), Op0,
Owen Andersonb5618da2009-07-03 00:17:18 +00006148 Context->getConstantInt(Op1Min));
Dan Gohman5638e0d2009-04-25 17:12:48 +00006149
Chris Lattnerbd25b852008-07-11 05:40:05 +00006150 // Based on the range information we know about the LHS, see if we can
6151 // simplify this comparison. For example, (x&4) < 8 is always true.
Dan Gohman5638e0d2009-04-25 17:12:48 +00006152 switch (I.getPredicate()) {
Torok Edwin56d06592009-07-11 20:10:48 +00006153 default: LLVM_UNREACHABLE("Unknown icmp opcode!");
Chris Lattner38a50c92008-07-11 05:08:55 +00006154 case ICmpInst::ICMP_EQ:
Dan Gohman5638e0d2009-04-25 17:12:48 +00006155 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Andersonb5618da2009-07-03 00:17:18 +00006156 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Chris Lattner38a50c92008-07-11 05:08:55 +00006157 break;
6158 case ICmpInst::ICMP_NE:
Dan Gohman5638e0d2009-04-25 17:12:48 +00006159 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Andersonb5618da2009-07-03 00:17:18 +00006160 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Chris Lattner38a50c92008-07-11 05:08:55 +00006161 break;
6162 case ICmpInst::ICMP_ULT:
Dan Gohman5638e0d2009-04-25 17:12:48 +00006163 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
Owen Andersonb5618da2009-07-03 00:17:18 +00006164 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Dan Gohman5638e0d2009-04-25 17:12:48 +00006165 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
Owen Andersonb5618da2009-07-03 00:17:18 +00006166 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Dan Gohman5638e0d2009-04-25 17:12:48 +00006167 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
Owen Anderson1e5f00e2009-07-09 23:48:35 +00006168 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman5638e0d2009-04-25 17:12:48 +00006169 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6170 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
Owen Anderson1e5f00e2009-07-09 23:48:35 +00006171 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6172 SubOne(CI, Context));
Dan Gohman5638e0d2009-04-25 17:12:48 +00006173
6174 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
6175 if (CI->isMinValue(true))
Owen Anderson1e5f00e2009-07-09 23:48:35 +00006176 return new ICmpInst(*Context, ICmpInst::ICMP_SGT, Op0,
Owen Anderson542619e2009-07-13 20:58:05 +00006177 Context->getAllOnesValue(Op0->getType()));
Dan Gohman5638e0d2009-04-25 17:12:48 +00006178 }
Chris Lattner38a50c92008-07-11 05:08:55 +00006179 break;
6180 case ICmpInst::ICMP_UGT:
Dan Gohman5638e0d2009-04-25 17:12:48 +00006181 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
Owen Andersonb5618da2009-07-03 00:17:18 +00006182 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Dan Gohman5638e0d2009-04-25 17:12:48 +00006183 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
Owen Andersonb5618da2009-07-03 00:17:18 +00006184 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Dan Gohman5638e0d2009-04-25 17:12:48 +00006185
6186 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
Owen Anderson1e5f00e2009-07-09 23:48:35 +00006187 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman5638e0d2009-04-25 17:12:48 +00006188 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6189 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C
Owen Anderson1e5f00e2009-07-09 23:48:35 +00006190 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6191 AddOne(CI, Context));
Dan Gohman5638e0d2009-04-25 17:12:48 +00006192
6193 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
6194 if (CI->isMaxValue(true))
Owen Anderson1e5f00e2009-07-09 23:48:35 +00006195 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Op0,
Owen Andersonb5618da2009-07-03 00:17:18 +00006196 Context->getNullValue(Op0->getType()));
Dan Gohman5638e0d2009-04-25 17:12:48 +00006197 }
Chris Lattner38a50c92008-07-11 05:08:55 +00006198 break;
6199 case ICmpInst::ICMP_SLT:
Dan Gohman5638e0d2009-04-25 17:12:48 +00006200 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
Owen Andersonb5618da2009-07-03 00:17:18 +00006201 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Dan Gohman5638e0d2009-04-25 17:12:48 +00006202 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
Owen Andersonb5618da2009-07-03 00:17:18 +00006203 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Dan Gohman5638e0d2009-04-25 17:12:48 +00006204 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
Owen Anderson1e5f00e2009-07-09 23:48:35 +00006205 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman5638e0d2009-04-25 17:12:48 +00006206 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6207 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C
Owen Anderson1e5f00e2009-07-09 23:48:35 +00006208 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6209 SubOne(CI, Context));
Dan Gohman5638e0d2009-04-25 17:12:48 +00006210 }
Chris Lattner38a50c92008-07-11 05:08:55 +00006211 break;
Dan Gohman5638e0d2009-04-25 17:12:48 +00006212 case ICmpInst::ICMP_SGT:
6213 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
Owen Andersonb5618da2009-07-03 00:17:18 +00006214 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Dan Gohman5638e0d2009-04-25 17:12:48 +00006215 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
Owen Andersonb5618da2009-07-03 00:17:18 +00006216 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Dan Gohman5638e0d2009-04-25 17:12:48 +00006217
6218 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
Owen Anderson1e5f00e2009-07-09 23:48:35 +00006219 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman5638e0d2009-04-25 17:12:48 +00006220 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6221 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
Owen Anderson1e5f00e2009-07-09 23:48:35 +00006222 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6223 AddOne(CI, Context));
Dan Gohman5638e0d2009-04-25 17:12:48 +00006224 }
6225 break;
6226 case ICmpInst::ICMP_SGE:
6227 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6228 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
Owen Andersonb5618da2009-07-03 00:17:18 +00006229 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Dan Gohman5638e0d2009-04-25 17:12:48 +00006230 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
Owen Andersonb5618da2009-07-03 00:17:18 +00006231 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Dan Gohman5638e0d2009-04-25 17:12:48 +00006232 break;
6233 case ICmpInst::ICMP_SLE:
6234 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6235 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
Owen Andersonb5618da2009-07-03 00:17:18 +00006236 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Dan Gohman5638e0d2009-04-25 17:12:48 +00006237 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
Owen Andersonb5618da2009-07-03 00:17:18 +00006238 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Dan Gohman5638e0d2009-04-25 17:12:48 +00006239 break;
6240 case ICmpInst::ICMP_UGE:
6241 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6242 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
Owen Andersonb5618da2009-07-03 00:17:18 +00006243 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Dan Gohman5638e0d2009-04-25 17:12:48 +00006244 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
Owen Andersonb5618da2009-07-03 00:17:18 +00006245 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Dan Gohman5638e0d2009-04-25 17:12:48 +00006246 break;
6247 case ICmpInst::ICMP_ULE:
6248 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6249 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
Owen Andersonb5618da2009-07-03 00:17:18 +00006250 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Dan Gohman5638e0d2009-04-25 17:12:48 +00006251 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
Owen Andersonb5618da2009-07-03 00:17:18 +00006252 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Chris Lattner38a50c92008-07-11 05:08:55 +00006253 break;
Chris Lattneree0f2802006-02-12 02:07:56 +00006254 }
Dan Gohman5638e0d2009-04-25 17:12:48 +00006255
6256 // Turn a signed comparison into an unsigned one if both operands
6257 // are known to have the same sign.
6258 if (I.isSignedPredicate() &&
6259 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6260 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
Owen Anderson1e5f00e2009-07-09 23:48:35 +00006261 return new ICmpInst(*Context, I.getUnsignedPredicate(), Op0, Op1);
Dan Gohmandafa9c62008-09-16 18:46:06 +00006262 }
6263
6264 // Test if the ICmpInst instruction is used exclusively by a select as
6265 // part of a minimum or maximum operation. If so, refrain from doing
6266 // any other folding. This helps out other analyses which understand
6267 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6268 // and CodeGen. And in this case, at least one of the comparison
6269 // operands has at least one user besides the compare (the select),
6270 // which would often largely negate the benefit of folding anyway.
6271 if (I.hasOneUse())
6272 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6273 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6274 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6275 return 0;
6276
6277 // See if we are doing a comparison between a constant and an instruction that
6278 // can be folded into the comparison.
6279 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00006280 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer7e80b0b2006-10-26 06:15:43 +00006281 // instruction, see if that instruction also has constants so that the
Reid Spencer266e42b2006-12-23 06:05:41 +00006282 // instruction can be folded into the icmp
Chris Lattnere1e10e12004-05-25 06:32:08 +00006283 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattnera74deaf2007-04-03 17:43:25 +00006284 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6285 return Res;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00006286 }
6287
Chris Lattnera74deaf2007-04-03 17:43:25 +00006288 // Handle icmp with constant (but not simple integer constant) RHS
Chris Lattner77c32c32005-04-23 15:31:55 +00006289 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6290 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6291 switch (LHSI->getOpcode()) {
Chris Lattnera816eee2005-05-01 04:42:15 +00006292 case Instruction::GetElementPtr:
6293 if (RHSC->isNullValue()) {
Reid Spencer266e42b2006-12-23 06:05:41 +00006294 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattnera816eee2005-05-01 04:42:15 +00006295 bool isAllZeros = true;
6296 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6297 if (!isa<Constant>(LHSI->getOperand(i)) ||
6298 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6299 isAllZeros = false;
6300 break;
6301 }
6302 if (isAllZeros)
Owen Anderson1e5f00e2009-07-09 23:48:35 +00006303 return new ICmpInst(*Context, I.getPredicate(), LHSI->getOperand(0),
Owen Andersonb5618da2009-07-03 00:17:18 +00006304 Context->getNullValue(LHSI->getOperand(0)->getType()));
Chris Lattnera816eee2005-05-01 04:42:15 +00006305 }
6306 break;
6307
Chris Lattner77c32c32005-04-23 15:31:55 +00006308 case Instruction::PHI:
Chris Lattnerb4866ef2008-06-08 20:52:11 +00006309 // Only fold icmp into the PHI if the phi and fcmp are in the same
6310 // block. If in the same block, we're encouraging jump threading. If
6311 // not, we are just pessimizing the code by making an i1 phi.
6312 if (LHSI->getParent() == I.getParent())
6313 if (Instruction *NV = FoldOpIntoPhi(I))
6314 return NV;
Chris Lattner77c32c32005-04-23 15:31:55 +00006315 break;
Chris Lattner3dbe65f2007-04-06 18:57:34 +00006316 case Instruction::Select: {
Chris Lattner77c32c32005-04-23 15:31:55 +00006317 // If either operand of the select is a constant, we can fold the
6318 // comparison into the select arms, which will cause one to be
6319 // constant folded and the select turned into a bitwise or.
6320 Value *Op1 = 0, *Op2 = 0;
6321 if (LHSI->hasOneUse()) {
6322 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6323 // Fold the known value into the constant operand.
Owen Andersonb5618da2009-07-03 00:17:18 +00006324 Op1 = Context->getConstantExprICmp(I.getPredicate(), C, RHSC);
Reid Spencer266e42b2006-12-23 06:05:41 +00006325 // Insert a new ICmp of the other select operand.
Owen Anderson1e5f00e2009-07-09 23:48:35 +00006326 Op2 = InsertNewInstBefore(new ICmpInst(*Context, I.getPredicate(),
Reid Spencer266e42b2006-12-23 06:05:41 +00006327 LHSI->getOperand(2), RHSC,
6328 I.getName()), I);
Chris Lattner77c32c32005-04-23 15:31:55 +00006329 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6330 // Fold the known value into the constant operand.
Owen Andersonb5618da2009-07-03 00:17:18 +00006331 Op2 = Context->getConstantExprICmp(I.getPredicate(), C, RHSC);
Reid Spencer266e42b2006-12-23 06:05:41 +00006332 // Insert a new ICmp of the other select operand.
Owen Anderson1e5f00e2009-07-09 23:48:35 +00006333 Op1 = InsertNewInstBefore(new ICmpInst(*Context, I.getPredicate(),
Reid Spencer266e42b2006-12-23 06:05:41 +00006334 LHSI->getOperand(1), RHSC,
6335 I.getName()), I);
Chris Lattner77c32c32005-04-23 15:31:55 +00006336 }
6337 }
Jeff Cohen82639852005-04-23 21:38:35 +00006338
Chris Lattner77c32c32005-04-23 15:31:55 +00006339 if (Op1)
Gabor Greife9ecc682008-04-06 20:25:17 +00006340 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Chris Lattner77c32c32005-04-23 15:31:55 +00006341 break;
6342 }
Chris Lattner3dbe65f2007-04-06 18:57:34 +00006343 case Instruction::Malloc:
6344 // If we have (malloc != null), and if the malloc has a single use, we
6345 // can assume it is successful and remove the malloc.
6346 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
6347 AddToWorkList(LHSI);
Owen Andersonb5618da2009-07-03 00:17:18 +00006348 return ReplaceInstUsesWith(I, Context->getConstantInt(Type::Int1Ty,
Nick Lewycky79376f42008-05-17 07:33:39 +00006349 !I.isTrueWhenEqual()));
Chris Lattner3dbe65f2007-04-06 18:57:34 +00006350 }
6351 break;
6352 }
Chris Lattner77c32c32005-04-23 15:31:55 +00006353 }
6354
Reid Spencer266e42b2006-12-23 06:05:41 +00006355 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Chris Lattner0798af32005-01-13 20:14:25 +00006356 if (User *GEP = dyn_castGetElementPtr(Op0))
Reid Spencer266e42b2006-12-23 06:05:41 +00006357 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner0798af32005-01-13 20:14:25 +00006358 return NI;
6359 if (User *GEP = dyn_castGetElementPtr(Op1))
Reid Spencer266e42b2006-12-23 06:05:41 +00006360 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6361 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner0798af32005-01-13 20:14:25 +00006362 return NI;
6363
Reid Spencer266e42b2006-12-23 06:05:41 +00006364 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner64d87b02007-01-06 01:45:59 +00006365 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
6366 // now.
6367 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6368 if (isa<PointerType>(Op0->getType()) &&
6369 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattner16930792003-11-03 04:25:02 +00006370 // We keep moving the cast from the left operand over to the right
6371 // operand, where it can often be eliminated completely.
Chris Lattner64d87b02007-01-06 01:45:59 +00006372 Op0 = CI->getOperand(0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00006373
Chris Lattner64d87b02007-01-06 01:45:59 +00006374 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6375 // so eliminate it as well.
6376 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6377 Op1 = CI2->getOperand(0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00006378
Chris Lattner16930792003-11-03 04:25:02 +00006379 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +00006380 if (Op0->getType() != Op1->getType()) {
Chris Lattner16930792003-11-03 04:25:02 +00006381 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Owen Andersonb5618da2009-07-03 00:17:18 +00006382 Op1 = Context->getConstantExprBitCast(Op1C, Op0->getType());
Chris Lattner16930792003-11-03 04:25:02 +00006383 } else {
Reid Spencer266e42b2006-12-23 06:05:41 +00006384 // Otherwise, cast the RHS right before the icmp
Chris Lattner5a866122008-01-13 22:23:22 +00006385 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
Chris Lattner16930792003-11-03 04:25:02 +00006386 }
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +00006387 }
Owen Anderson1e5f00e2009-07-09 23:48:35 +00006388 return new ICmpInst(*Context, I.getPredicate(), Op0, Op1);
Chris Lattner16930792003-11-03 04:25:02 +00006389 }
Chris Lattner64d87b02007-01-06 01:45:59 +00006390 }
6391
6392 if (isa<CastInst>(Op0)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00006393 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner6444c372003-11-03 05:17:03 +00006394 // This comes up when you have code like
6395 // int X = A < B;
6396 // if (X) ...
6397 // For generality, we handle any zero-extension of any operand comparison
Chris Lattnerd1f46d32005-04-24 06:59:08 +00006398 // with a constant or another cast from the same type.
6399 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencer266e42b2006-12-23 06:05:41 +00006400 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattnerd1f46d32005-04-24 06:59:08 +00006401 return R;
Chris Lattner6444c372003-11-03 05:17:03 +00006402 }
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00006403
Nick Lewyckyf95b64a2008-07-11 07:20:53 +00006404 // See if it's the same type of instruction on the left and right.
6405 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6406 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Nick Lewycky99f45582008-08-21 05:56:10 +00006407 if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
Nick Lewyckyf2390812009-01-31 21:30:05 +00006408 Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
Nick Lewycky2fcb26c2008-09-03 06:24:21 +00006409 switch (Op0I->getOpcode()) {
Nick Lewyckyf95b64a2008-07-11 07:20:53 +00006410 default: break;
6411 case Instruction::Add:
6412 case Instruction::Sub:
6413 case Instruction::Xor:
Chris Lattner1aafe4c2009-02-02 07:15:30 +00006414 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
Owen Anderson1e5f00e2009-07-09 23:48:35 +00006415 return new ICmpInst(*Context, I.getPredicate(), Op0I->getOperand(0),
Nick Lewyckyf2390812009-01-31 21:30:05 +00006416 Op1I->getOperand(0));
Chris Lattner1aafe4c2009-02-02 07:15:30 +00006417 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6418 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6419 if (CI->getValue().isSignBit()) {
6420 ICmpInst::Predicate Pred = I.isSignedPredicate()
6421 ? I.getUnsignedPredicate()
6422 : I.getSignedPredicate();
Owen Anderson1e5f00e2009-07-09 23:48:35 +00006423 return new ICmpInst(*Context, Pred, Op0I->getOperand(0),
Chris Lattner1aafe4c2009-02-02 07:15:30 +00006424 Op1I->getOperand(0));
6425 }
6426
6427 if (CI->getValue().isMaxSignedValue()) {
6428 ICmpInst::Predicate Pred = I.isSignedPredicate()
6429 ? I.getUnsignedPredicate()
6430 : I.getSignedPredicate();
6431 Pred = I.getSwappedPredicate(Pred);
Owen Anderson1e5f00e2009-07-09 23:48:35 +00006432 return new ICmpInst(*Context, Pred, Op0I->getOperand(0),
Chris Lattner1aafe4c2009-02-02 07:15:30 +00006433 Op1I->getOperand(0));
Nick Lewyckyf2390812009-01-31 21:30:05 +00006434 }
6435 }
Nick Lewyckyf95b64a2008-07-11 07:20:53 +00006436 break;
6437 case Instruction::Mul:
Nick Lewyckyf2390812009-01-31 21:30:05 +00006438 if (!I.isEquality())
6439 break;
6440
Nick Lewycky99f45582008-08-21 05:56:10 +00006441 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6442 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6443 // Mask = -1 >> count-trailing-zeros(Cst).
6444 if (!CI->isZero() && !CI->isOne()) {
6445 const APInt &AP = CI->getValue();
Owen Andersonb5618da2009-07-03 00:17:18 +00006446 ConstantInt *Mask = Context->getConstantInt(
Nick Lewycky99f45582008-08-21 05:56:10 +00006447 APInt::getLowBitsSet(AP.getBitWidth(),
6448 AP.getBitWidth() -
Nick Lewyckyf95b64a2008-07-11 07:20:53 +00006449 AP.countTrailingZeros()));
Nick Lewycky99f45582008-08-21 05:56:10 +00006450 Instruction *And1 = BinaryOperator::CreateAnd(Op0I->getOperand(0),
6451 Mask);
6452 Instruction *And2 = BinaryOperator::CreateAnd(Op1I->getOperand(0),
6453 Mask);
6454 InsertNewInstBefore(And1, I);
6455 InsertNewInstBefore(And2, I);
Owen Anderson1e5f00e2009-07-09 23:48:35 +00006456 return new ICmpInst(*Context, I.getPredicate(), And1, And2);
Nick Lewyckyf95b64a2008-07-11 07:20:53 +00006457 }
6458 }
6459 break;
6460 }
6461 }
6462 }
6463 }
6464
Chris Lattneraaba10e2008-05-09 05:19:28 +00006465 // ~x < ~y --> y < x
6466 { Value *A, *B;
Owen Anderson16e76742009-07-10 17:35:01 +00006467 if (match(Op0, m_Not(m_Value(A)), *Context) &&
6468 match(Op1, m_Not(m_Value(B)), *Context))
Owen Anderson1e5f00e2009-07-09 23:48:35 +00006469 return new ICmpInst(*Context, I.getPredicate(), B, A);
Chris Lattneraaba10e2008-05-09 05:19:28 +00006470 }
6471
Chris Lattnerb3f24c92006-09-18 04:22:48 +00006472 if (I.isEquality()) {
Chris Lattner17c7c032007-01-05 03:04:57 +00006473 Value *A, *B, *C, *D;
Chris Lattneraaba10e2008-05-09 05:19:28 +00006474
6475 // -x == -y --> x == y
Owen Anderson16e76742009-07-10 17:35:01 +00006476 if (match(Op0, m_Neg(m_Value(A)), *Context) &&
6477 match(Op1, m_Neg(m_Value(B)), *Context))
Owen Anderson1e5f00e2009-07-09 23:48:35 +00006478 return new ICmpInst(*Context, I.getPredicate(), A, B);
Chris Lattneraaba10e2008-05-09 05:19:28 +00006479
Owen Anderson16e76742009-07-10 17:35:01 +00006480 if (match(Op0, m_Xor(m_Value(A), m_Value(B)), *Context)) {
Chris Lattner17c7c032007-01-05 03:04:57 +00006481 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6482 Value *OtherVal = A == Op1 ? B : A;
Owen Anderson1e5f00e2009-07-09 23:48:35 +00006483 return new ICmpInst(*Context, I.getPredicate(), OtherVal,
Owen Andersonb5618da2009-07-03 00:17:18 +00006484 Context->getNullValue(A->getType()));
Chris Lattner17c7c032007-01-05 03:04:57 +00006485 }
6486
Owen Anderson16e76742009-07-10 17:35:01 +00006487 if (match(Op1, m_Xor(m_Value(C), m_Value(D)), *Context)) {
Chris Lattner17c7c032007-01-05 03:04:57 +00006488 // A^c1 == C^c2 --> A == C^(c1^c2)
Chris Lattner44152742008-11-16 05:38:51 +00006489 ConstantInt *C1, *C2;
Owen Anderson16e76742009-07-10 17:35:01 +00006490 if (match(B, m_ConstantInt(C1), *Context) &&
6491 match(D, m_ConstantInt(C2), *Context) && Op1->hasOneUse()) {
Owen Andersonb5618da2009-07-03 00:17:18 +00006492 Constant *NC =
6493 Context->getConstantInt(C1->getValue() ^ C2->getValue());
Chris Lattner44152742008-11-16 05:38:51 +00006494 Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
Owen Anderson1e5f00e2009-07-09 23:48:35 +00006495 return new ICmpInst(*Context, I.getPredicate(), A,
Chris Lattner44152742008-11-16 05:38:51 +00006496 InsertNewInstBefore(Xor, I));
6497 }
Chris Lattner17c7c032007-01-05 03:04:57 +00006498
6499 // A^B == A^D -> B == D
Owen Anderson1e5f00e2009-07-09 23:48:35 +00006500 if (A == C) return new ICmpInst(*Context, I.getPredicate(), B, D);
6501 if (A == D) return new ICmpInst(*Context, I.getPredicate(), B, C);
6502 if (B == C) return new ICmpInst(*Context, I.getPredicate(), A, D);
6503 if (B == D) return new ICmpInst(*Context, I.getPredicate(), A, C);
Chris Lattner17c7c032007-01-05 03:04:57 +00006504 }
6505 }
6506
Owen Anderson16e76742009-07-10 17:35:01 +00006507 if (match(Op1, m_Xor(m_Value(A), m_Value(B)), *Context) &&
Chris Lattner17c7c032007-01-05 03:04:57 +00006508 (A == Op0 || B == Op0)) {
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00006509 // A == (A^B) -> B == 0
6510 Value *OtherVal = A == Op0 ? B : A;
Owen Anderson1e5f00e2009-07-09 23:48:35 +00006511 return new ICmpInst(*Context, I.getPredicate(), OtherVal,
Owen Andersonb5618da2009-07-03 00:17:18 +00006512 Context->getNullValue(A->getType()));
Chris Lattner17c7c032007-01-05 03:04:57 +00006513 }
Chris Lattner44152742008-11-16 05:38:51 +00006514
6515 // (A-B) == A -> B == 0
Owen Anderson16e76742009-07-10 17:35:01 +00006516 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B)), *Context))
Owen Anderson1e5f00e2009-07-09 23:48:35 +00006517 return new ICmpInst(*Context, I.getPredicate(), B,
Owen Andersonb5618da2009-07-03 00:17:18 +00006518 Context->getNullValue(B->getType()));
Chris Lattner44152742008-11-16 05:38:51 +00006519
6520 // A == (A-B) -> B == 0
Owen Anderson16e76742009-07-10 17:35:01 +00006521 if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B)), *Context))
Owen Anderson1e5f00e2009-07-09 23:48:35 +00006522 return new ICmpInst(*Context, I.getPredicate(), B,
Owen Andersonb5618da2009-07-03 00:17:18 +00006523 Context->getNullValue(B->getType()));
Chris Lattnerd12a4bf2006-11-14 06:06:06 +00006524
Chris Lattnerd12a4bf2006-11-14 06:06:06 +00006525 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6526 if (Op0->hasOneUse() && Op1->hasOneUse() &&
Owen Anderson16e76742009-07-10 17:35:01 +00006527 match(Op0, m_And(m_Value(A), m_Value(B)), *Context) &&
6528 match(Op1, m_And(m_Value(C), m_Value(D)), *Context)) {
Chris Lattnerd12a4bf2006-11-14 06:06:06 +00006529 Value *X = 0, *Y = 0, *Z = 0;
6530
6531 if (A == C) {
6532 X = B; Y = D; Z = A;
6533 } else if (A == D) {
6534 X = B; Y = C; Z = A;
6535 } else if (B == C) {
6536 X = A; Y = D; Z = B;
6537 } else if (B == D) {
6538 X = A; Y = C; Z = B;
6539 }
6540
6541 if (X) { // Build (X^Y) & Z
Gabor Greife1f6e4b2008-05-16 19:29:10 +00006542 Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
6543 Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
Chris Lattnerd12a4bf2006-11-14 06:06:06 +00006544 I.setOperand(0, Op1);
Owen Andersonb5618da2009-07-03 00:17:18 +00006545 I.setOperand(1, Context->getNullValue(Op1->getType()));
Chris Lattnerd12a4bf2006-11-14 06:06:06 +00006546 return &I;
6547 }
6548 }
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00006549 }
Chris Lattner113f4f42002-06-25 16:13:24 +00006550 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00006551}
6552
Chris Lattner3bbec592007-06-20 23:46:26 +00006553
6554/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6555/// and CmpRHS are both known to be integer constants.
6556Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6557 ConstantInt *DivRHS) {
6558 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6559 const APInt &CmpRHSV = CmpRHS->getValue();
6560
6561 // FIXME: If the operand types don't match the type of the divide
6562 // then don't attempt this transform. The code below doesn't have the
6563 // logic to deal with a signed divide and an unsigned compare (and
6564 // vice versa). This is because (x /s C1) <s C2 produces different
6565 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6566 // (x /u C1) <u C2. Simply casting the operands and result won't
6567 // work. :( The if statement below tests that condition and bails
6568 // if it finds it.
6569 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6570 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6571 return 0;
6572 if (DivRHS->isZero())
Chris Lattnerfb032b12007-06-21 18:11:19 +00006573 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattnerda435912008-10-11 22:55:00 +00006574 if (DivIsSigned && DivRHS->isAllOnesValue())
6575 return 0; // The overflow computation also screws up here
6576 if (DivRHS->isOne())
6577 return 0; // Not worth bothering, and eliminates some funny cases
6578 // with INT_MIN.
Chris Lattner3bbec592007-06-20 23:46:26 +00006579
6580 // Compute Prod = CI * DivRHS. We are essentially solving an equation
6581 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
6582 // C2 (CI). By solving for X we can turn this into a range check
6583 // instead of computing a divide.
Owen Andersonb5618da2009-07-03 00:17:18 +00006584 Constant *Prod = Context->getConstantExprMul(CmpRHS, DivRHS);
Chris Lattner3bbec592007-06-20 23:46:26 +00006585
6586 // Determine if the product overflows by seeing if the product is
6587 // not equal to the divide. Make sure we do the same kind of divide
6588 // as in the LHS instruction that we're folding.
Owen Andersonb5618da2009-07-03 00:17:18 +00006589 bool ProdOV = (DivIsSigned ? Context->getConstantExprSDiv(Prod, DivRHS) :
6590 Context->getConstantExprUDiv(Prod, DivRHS)) != CmpRHS;
Chris Lattner3bbec592007-06-20 23:46:26 +00006591
6592 // Get the ICmp opcode
Chris Lattnerfb032b12007-06-21 18:11:19 +00006593 ICmpInst::Predicate Pred = ICI.getPredicate();
Chris Lattner3bbec592007-06-20 23:46:26 +00006594
Chris Lattnerfb032b12007-06-21 18:11:19 +00006595 // Figure out the interval that is being checked. For example, a comparison
6596 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
6597 // Compute this interval based on the constants involved and the signedness of
6598 // the compare/divide. This computes a half-open interval, keeping track of
6599 // whether either value in the interval overflows. After analysis each
6600 // overflow variable is set to 0 if it's corresponding bound variable is valid
6601 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6602 int LoOverflow = 0, HiOverflow = 0;
Dan Gohman7ccc52f2009-06-15 22:12:54 +00006603 Constant *LoBound = 0, *HiBound = 0;
Chris Lattnerfb032b12007-06-21 18:11:19 +00006604
Chris Lattner3bbec592007-06-20 23:46:26 +00006605 if (!DivIsSigned) { // udiv
Chris Lattnerfb032b12007-06-21 18:11:19 +00006606 // e.g. X/5 op 3 --> [15, 20)
Chris Lattner3bbec592007-06-20 23:46:26 +00006607 LoBound = Prod;
Chris Lattnerfb032b12007-06-21 18:11:19 +00006608 HiOverflow = LoOverflow = ProdOV;
6609 if (!HiOverflow)
Owen Andersonb5618da2009-07-03 00:17:18 +00006610 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
Dan Gohman1ee8dc92008-02-13 22:09:18 +00006611 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Chris Lattner3bbec592007-06-20 23:46:26 +00006612 if (CmpRHSV == 0) { // (X / pos) op 0
Chris Lattnerfb032b12007-06-21 18:11:19 +00006613 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Owen Andersonb5618da2009-07-03 00:17:18 +00006614 LoBound = cast<ConstantInt>(Context->getConstantExprNeg(SubOne(DivRHS,
6615 Context)));
Chris Lattner3bbec592007-06-20 23:46:26 +00006616 HiBound = DivRHS;
Dan Gohman1ee8dc92008-02-13 22:09:18 +00006617 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Chris Lattnerfb032b12007-06-21 18:11:19 +00006618 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
6619 HiOverflow = LoOverflow = ProdOV;
6620 if (!HiOverflow)
Owen Andersonb5618da2009-07-03 00:17:18 +00006621 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
Chris Lattner3bbec592007-06-20 23:46:26 +00006622 } else { // (X / pos) op neg
Chris Lattnerfb032b12007-06-21 18:11:19 +00006623 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Owen Andersonb5618da2009-07-03 00:17:18 +00006624 HiBound = AddOne(Prod, Context);
Chris Lattnerda435912008-10-11 22:55:00 +00006625 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6626 if (!LoOverflow) {
Owen Andersonb5618da2009-07-03 00:17:18 +00006627 ConstantInt* DivNeg =
6628 cast<ConstantInt>(Context->getConstantExprNeg(DivRHS));
6629 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
Chris Lattnerda435912008-10-11 22:55:00 +00006630 true) ? -1 : 0;
6631 }
Chris Lattner3bbec592007-06-20 23:46:26 +00006632 }
Dan Gohman1ee8dc92008-02-13 22:09:18 +00006633 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Chris Lattner3bbec592007-06-20 23:46:26 +00006634 if (CmpRHSV == 0) { // (X / neg) op 0
Chris Lattnerfb032b12007-06-21 18:11:19 +00006635 // e.g. X/-5 op 0 --> [-4, 5)
Owen Andersonb5618da2009-07-03 00:17:18 +00006636 LoBound = AddOne(DivRHS, Context);
6637 HiBound = cast<ConstantInt>(Context->getConstantExprNeg(DivRHS));
Chris Lattnerfb032b12007-06-21 18:11:19 +00006638 if (HiBound == DivRHS) { // -INTMIN = INTMIN
6639 HiOverflow = 1; // [INTMIN+1, overflow)
6640 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
6641 }
Dan Gohman1ee8dc92008-02-13 22:09:18 +00006642 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Chris Lattnerfb032b12007-06-21 18:11:19 +00006643 // e.g. X/-5 op 3 --> [-19, -14)
Owen Andersonb5618da2009-07-03 00:17:18 +00006644 HiBound = AddOne(Prod, Context);
Chris Lattnerfb032b12007-06-21 18:11:19 +00006645 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
Chris Lattner3bbec592007-06-20 23:46:26 +00006646 if (!LoOverflow)
Owen Andersonb5618da2009-07-03 00:17:18 +00006647 LoOverflow = AddWithOverflow(LoBound, HiBound,
6648 DivRHS, Context, true) ? -1 : 0;
Chris Lattner3bbec592007-06-20 23:46:26 +00006649 } else { // (X / neg) op neg
Chris Lattnerda435912008-10-11 22:55:00 +00006650 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
6651 LoOverflow = HiOverflow = ProdOV;
Dan Gohman9d9a4be2008-09-11 00:25:00 +00006652 if (!HiOverflow)
Owen Andersonb5618da2009-07-03 00:17:18 +00006653 HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
Chris Lattner3bbec592007-06-20 23:46:26 +00006654 }
6655
Chris Lattnerfb032b12007-06-21 18:11:19 +00006656 // Dividing by a negative swaps the condition. LT <-> GT
6657 Pred = ICmpInst::getSwappedPredicate(Pred);
Chris Lattner3bbec592007-06-20 23:46:26 +00006658 }
6659
6660 Value *X = DivI->getOperand(0);
Chris Lattnerfb032b12007-06-21 18:11:19 +00006661 switch (Pred) {
Torok Edwin56d06592009-07-11 20:10:48 +00006662 default: LLVM_UNREACHABLE("Unhandled icmp opcode!");
Chris Lattner3bbec592007-06-20 23:46:26 +00006663 case ICmpInst::ICMP_EQ:
6664 if (LoOverflow && HiOverflow)
Owen Andersonb5618da2009-07-03 00:17:18 +00006665 return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
Chris Lattner3bbec592007-06-20 23:46:26 +00006666 else if (HiOverflow)
Owen Anderson1e5f00e2009-07-09 23:48:35 +00006667 return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner3bbec592007-06-20 23:46:26 +00006668 ICmpInst::ICMP_UGE, X, LoBound);
6669 else if (LoOverflow)
Owen Anderson1e5f00e2009-07-09 23:48:35 +00006670 return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner3bbec592007-06-20 23:46:26 +00006671 ICmpInst::ICMP_ULT, X, HiBound);
6672 else
Chris Lattnerfb032b12007-06-21 18:11:19 +00006673 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
Chris Lattner3bbec592007-06-20 23:46:26 +00006674 case ICmpInst::ICMP_NE:
6675 if (LoOverflow && HiOverflow)
Owen Andersonb5618da2009-07-03 00:17:18 +00006676 return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
Chris Lattner3bbec592007-06-20 23:46:26 +00006677 else if (HiOverflow)
Owen Anderson1e5f00e2009-07-09 23:48:35 +00006678 return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner3bbec592007-06-20 23:46:26 +00006679 ICmpInst::ICMP_ULT, X, LoBound);
6680 else if (LoOverflow)
Owen Anderson1e5f00e2009-07-09 23:48:35 +00006681 return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner3bbec592007-06-20 23:46:26 +00006682 ICmpInst::ICMP_UGE, X, HiBound);
6683 else
Chris Lattnerfb032b12007-06-21 18:11:19 +00006684 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
Chris Lattner3bbec592007-06-20 23:46:26 +00006685 case ICmpInst::ICMP_ULT:
6686 case ICmpInst::ICMP_SLT:
Chris Lattnerfb032b12007-06-21 18:11:19 +00006687 if (LoOverflow == +1) // Low bound is greater than input range.
Owen Andersonb5618da2009-07-03 00:17:18 +00006688 return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
Chris Lattnerfb032b12007-06-21 18:11:19 +00006689 if (LoOverflow == -1) // Low bound is less than input range.
Owen Andersonb5618da2009-07-03 00:17:18 +00006690 return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
Owen Anderson1e5f00e2009-07-09 23:48:35 +00006691 return new ICmpInst(*Context, Pred, X, LoBound);
Chris Lattner3bbec592007-06-20 23:46:26 +00006692 case ICmpInst::ICMP_UGT:
6693 case ICmpInst::ICMP_SGT:
Chris Lattnerfb032b12007-06-21 18:11:19 +00006694 if (HiOverflow == +1) // High bound greater than input range.
Owen Andersonb5618da2009-07-03 00:17:18 +00006695 return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
Chris Lattnerfb032b12007-06-21 18:11:19 +00006696 else if (HiOverflow == -1) // High bound less than input range.
Owen Andersonb5618da2009-07-03 00:17:18 +00006697 return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
Chris Lattnerfb032b12007-06-21 18:11:19 +00006698 if (Pred == ICmpInst::ICMP_UGT)
Owen Anderson1e5f00e2009-07-09 23:48:35 +00006699 return new ICmpInst(*Context, ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattner3bbec592007-06-20 23:46:26 +00006700 else
Owen Anderson1e5f00e2009-07-09 23:48:35 +00006701 return new ICmpInst(*Context, ICmpInst::ICMP_SGE, X, HiBound);
Chris Lattner3bbec592007-06-20 23:46:26 +00006702 }
6703}
6704
6705
Chris Lattnera74deaf2007-04-03 17:43:25 +00006706/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6707///
6708Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6709 Instruction *LHSI,
6710 ConstantInt *RHS) {
6711 const APInt &RHSV = RHS->getValue();
6712
6713 switch (LHSI->getOpcode()) {
Chris Lattnerf50aa6a2009-01-09 07:47:06 +00006714 case Instruction::Trunc:
6715 if (ICI.isEquality() && LHSI->hasOneUse()) {
6716 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6717 // of the high bits truncated out of x are known.
6718 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6719 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6720 APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6721 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6722 ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6723
6724 // If all the high bits are known, we can do this xform.
6725 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6726 // Pull in the high bits from known-ones set.
6727 APInt NewRHS(RHS->getValue());
6728 NewRHS.zext(SrcBits);
6729 NewRHS |= KnownOne;
Owen Anderson1e5f00e2009-07-09 23:48:35 +00006730 return new ICmpInst(*Context, ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersonb5618da2009-07-03 00:17:18 +00006731 Context->getConstantInt(NewRHS));
Chris Lattnerf50aa6a2009-01-09 07:47:06 +00006732 }
6733 }
6734 break;
6735
Duncan Sandsf01a47c2007-04-04 06:42:45 +00006736 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
Chris Lattnera74deaf2007-04-03 17:43:25 +00006737 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6738 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6739 // fold the xor.
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +00006740 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6741 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Chris Lattnera74deaf2007-04-03 17:43:25 +00006742 Value *CompareVal = LHSI->getOperand(0);
6743
6744 // If the sign bit of the XorCST is not set, there is no change to
6745 // the operation, just stop using the Xor.
6746 if (!XorCST->getValue().isNegative()) {
6747 ICI.setOperand(0, CompareVal);
6748 AddToWorkList(LHSI);
6749 return &ICI;
6750 }
6751
6752 // Was the old condition true if the operand is positive?
6753 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6754
6755 // If so, the new one isn't.
6756 isTrueIfPositive ^= true;
6757
6758 if (isTrueIfPositive)
Owen Anderson1e5f00e2009-07-09 23:48:35 +00006759 return new ICmpInst(*Context, ICmpInst::ICMP_SGT, CompareVal,
Owen Andersonb5618da2009-07-03 00:17:18 +00006760 SubOne(RHS, Context));
Chris Lattnera74deaf2007-04-03 17:43:25 +00006761 else
Owen Anderson1e5f00e2009-07-09 23:48:35 +00006762 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, CompareVal,
Owen Andersonb5618da2009-07-03 00:17:18 +00006763 AddOne(RHS, Context));
Chris Lattnera74deaf2007-04-03 17:43:25 +00006764 }
Nick Lewyckyf2390812009-01-31 21:30:05 +00006765
6766 if (LHSI->hasOneUse()) {
6767 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6768 if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6769 const APInt &SignBit = XorCST->getValue();
6770 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6771 ? ICI.getUnsignedPredicate()
6772 : ICI.getSignedPredicate();
Owen Anderson1e5f00e2009-07-09 23:48:35 +00006773 return new ICmpInst(*Context, Pred, LHSI->getOperand(0),
Owen Andersonb5618da2009-07-03 00:17:18 +00006774 Context->getConstantInt(RHSV ^ SignBit));
Nick Lewyckyf2390812009-01-31 21:30:05 +00006775 }
6776
6777 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
Chris Lattner1aafe4c2009-02-02 07:15:30 +00006778 if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
Nick Lewyckyf2390812009-01-31 21:30:05 +00006779 const APInt &NotSignBit = XorCST->getValue();
6780 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6781 ? ICI.getUnsignedPredicate()
6782 : ICI.getSignedPredicate();
6783 Pred = ICI.getSwappedPredicate(Pred);
Owen Anderson1e5f00e2009-07-09 23:48:35 +00006784 return new ICmpInst(*Context, Pred, LHSI->getOperand(0),
Owen Andersonb5618da2009-07-03 00:17:18 +00006785 Context->getConstantInt(RHSV ^ NotSignBit));
Nick Lewyckyf2390812009-01-31 21:30:05 +00006786 }
6787 }
Chris Lattnera74deaf2007-04-03 17:43:25 +00006788 }
6789 break;
6790 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
6791 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6792 LHSI->getOperand(0)->hasOneUse()) {
6793 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6794
6795 // If the LHS is an AND of a truncating cast, we can widen the
6796 // and/compare to be the input width without changing the value
6797 // produced, eliminating a cast.
6798 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6799 // We can do this transformation if either the AND constant does not
6800 // have its sign bit set or if it is an equality comparison.
6801 // Extending a relational comparison when we're checking the sign
6802 // bit would not work.
6803 if (Cast->hasOneUse() &&
Anton Korobeynikov18991d72008-02-20 12:07:57 +00006804 (ICI.isEquality() ||
6805 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Chris Lattnera74deaf2007-04-03 17:43:25 +00006806 uint32_t BitWidth =
6807 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6808 APInt NewCST = AndCST->getValue();
6809 NewCST.zext(BitWidth);
6810 APInt NewCI = RHSV;
6811 NewCI.zext(BitWidth);
6812 Instruction *NewAnd =
Gabor Greife1f6e4b2008-05-16 19:29:10 +00006813 BinaryOperator::CreateAnd(Cast->getOperand(0),
Owen Andersonb5618da2009-07-03 00:17:18 +00006814 Context->getConstantInt(NewCST),LHSI->getName());
Chris Lattnera74deaf2007-04-03 17:43:25 +00006815 InsertNewInstBefore(NewAnd, ICI);
Owen Anderson1e5f00e2009-07-09 23:48:35 +00006816 return new ICmpInst(*Context, ICI.getPredicate(), NewAnd,
Owen Andersonb5618da2009-07-03 00:17:18 +00006817 Context->getConstantInt(NewCI));
Chris Lattnera74deaf2007-04-03 17:43:25 +00006818 }
6819 }
6820
6821 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6822 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
6823 // happens a LOT in code produced by the C front-end, for bitfield
6824 // access.
6825 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6826 if (Shift && !Shift->isShift())
6827 Shift = 0;
6828
6829 ConstantInt *ShAmt;
6830 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6831 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
6832 const Type *AndTy = AndCST->getType(); // Type of the and.
6833
6834 // We can fold this as long as we can't shift unknown bits
6835 // into the mask. This can only happen with signed shift
6836 // rights, as they sign-extend.
6837 if (ShAmt) {
6838 bool CanFold = Shift->isLogicalShift();
6839 if (!CanFold) {
6840 // To test for the bad case of the signed shr, see if any
6841 // of the bits shifted in could be tested after the mask.
6842 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6843 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6844
6845 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6846 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
6847 AndCST->getValue()) == 0)
6848 CanFold = true;
6849 }
6850
6851 if (CanFold) {
6852 Constant *NewCst;
6853 if (Shift->getOpcode() == Instruction::Shl)
Owen Andersonb5618da2009-07-03 00:17:18 +00006854 NewCst = Context->getConstantExprLShr(RHS, ShAmt);
Chris Lattnera74deaf2007-04-03 17:43:25 +00006855 else
Owen Andersonb5618da2009-07-03 00:17:18 +00006856 NewCst = Context->getConstantExprShl(RHS, ShAmt);
Chris Lattnera74deaf2007-04-03 17:43:25 +00006857
6858 // Check to see if we are shifting out any of the bits being
6859 // compared.
Owen Andersonb5618da2009-07-03 00:17:18 +00006860 if (Context->getConstantExpr(Shift->getOpcode(),
6861 NewCst, ShAmt) != RHS) {
Chris Lattnera74deaf2007-04-03 17:43:25 +00006862 // If we shifted bits out, the fold is not going to work out.
6863 // As a special case, check to see if this means that the
6864 // result is always true or false now.
6865 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Andersonb5618da2009-07-03 00:17:18 +00006866 return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
Chris Lattnera74deaf2007-04-03 17:43:25 +00006867 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Andersonb5618da2009-07-03 00:17:18 +00006868 return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
Chris Lattnera74deaf2007-04-03 17:43:25 +00006869 } else {
6870 ICI.setOperand(1, NewCst);
6871 Constant *NewAndCST;
6872 if (Shift->getOpcode() == Instruction::Shl)
Owen Andersonb5618da2009-07-03 00:17:18 +00006873 NewAndCST = Context->getConstantExprLShr(AndCST, ShAmt);
Chris Lattnera74deaf2007-04-03 17:43:25 +00006874 else
Owen Andersonb5618da2009-07-03 00:17:18 +00006875 NewAndCST = Context->getConstantExprShl(AndCST, ShAmt);
Chris Lattnera74deaf2007-04-03 17:43:25 +00006876 LHSI->setOperand(1, NewAndCST);
6877 LHSI->setOperand(0, Shift->getOperand(0));
6878 AddToWorkList(Shift); // Shift is dead.
6879 AddUsesToWorkList(ICI);
6880 return &ICI;
6881 }
6882 }
6883 }
6884
6885 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
6886 // preferable because it allows the C<<Y expression to be hoisted out
6887 // of a loop if Y is invariant and X is not.
6888 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
Chris Lattnerc3b21112009-03-25 00:28:58 +00006889 ICI.isEquality() && !Shift->isArithmeticShift() &&
6890 !isa<Constant>(Shift->getOperand(0))) {
Chris Lattnera74deaf2007-04-03 17:43:25 +00006891 // Compute C << Y.
6892 Value *NS;
6893 if (Shift->getOpcode() == Instruction::LShr) {
Gabor Greife1f6e4b2008-05-16 19:29:10 +00006894 NS = BinaryOperator::CreateShl(AndCST,
Chris Lattnera74deaf2007-04-03 17:43:25 +00006895 Shift->getOperand(1), "tmp");
6896 } else {
6897 // Insert a logical shift.
Gabor Greife1f6e4b2008-05-16 19:29:10 +00006898 NS = BinaryOperator::CreateLShr(AndCST,
Chris Lattnera74deaf2007-04-03 17:43:25 +00006899 Shift->getOperand(1), "tmp");
6900 }
6901 InsertNewInstBefore(cast<Instruction>(NS), ICI);
6902
6903 // Compute X & (C << Y).
6904 Instruction *NewAnd =
Gabor Greife1f6e4b2008-05-16 19:29:10 +00006905 BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Chris Lattnera74deaf2007-04-03 17:43:25 +00006906 InsertNewInstBefore(NewAnd, ICI);
6907
6908 ICI.setOperand(0, NewAnd);
6909 return &ICI;
6910 }
6911 }
6912 break;
6913
Chris Lattner06205d52007-07-15 20:42:37 +00006914 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6915 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6916 if (!ShAmt) break;
6917
6918 uint32_t TypeBits = RHSV.getBitWidth();
6919
6920 // Check that the shift amount is in range. If not, don't perform
6921 // undefined shifts. When the shift is visited it will be
6922 // simplified.
6923 if (ShAmt->uge(TypeBits))
6924 break;
6925
6926 if (ICI.isEquality()) {
6927 // If we are comparing against bits always shifted out, the
6928 // comparison cannot succeed.
6929 Constant *Comp =
Owen Andersonb5618da2009-07-03 00:17:18 +00006930 Context->getConstantExprShl(Context->getConstantExprLShr(RHS, ShAmt),
6931 ShAmt);
Chris Lattner06205d52007-07-15 20:42:37 +00006932 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6933 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Andersonb5618da2009-07-03 00:17:18 +00006934 Constant *Cst = Context->getConstantInt(Type::Int1Ty, IsICMP_NE);
Chris Lattner06205d52007-07-15 20:42:37 +00006935 return ReplaceInstUsesWith(ICI, Cst);
6936 }
6937
6938 if (LHSI->hasOneUse()) {
6939 // Otherwise strength reduce the shift into an and.
6940 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6941 Constant *Mask =
Owen Andersonb5618da2009-07-03 00:17:18 +00006942 Context->getConstantInt(APInt::getLowBitsSet(TypeBits,
6943 TypeBits-ShAmtVal));
Chris Lattnera74deaf2007-04-03 17:43:25 +00006944
Chris Lattner06205d52007-07-15 20:42:37 +00006945 Instruction *AndI =
Gabor Greife1f6e4b2008-05-16 19:29:10 +00006946 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattner06205d52007-07-15 20:42:37 +00006947 Mask, LHSI->getName()+".mask");
6948 Value *And = InsertNewInstBefore(AndI, ICI);
Owen Anderson1e5f00e2009-07-09 23:48:35 +00006949 return new ICmpInst(*Context, ICI.getPredicate(), And,
Owen Andersonb5618da2009-07-03 00:17:18 +00006950 Context->getConstantInt(RHSV.lshr(ShAmtVal)));
Chris Lattnera74deaf2007-04-03 17:43:25 +00006951 }
6952 }
Chris Lattner06205d52007-07-15 20:42:37 +00006953
6954 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6955 bool TrueIfSigned = false;
6956 if (LHSI->hasOneUse() &&
6957 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6958 // (X << 31) <s 0 --> (X&1) != 0
Owen Andersonb5618da2009-07-03 00:17:18 +00006959 Constant *Mask = Context->getConstantInt(APInt(TypeBits, 1) <<
Chris Lattner06205d52007-07-15 20:42:37 +00006960 (TypeBits-ShAmt->getZExtValue()-1));
6961 Instruction *AndI =
Gabor Greife1f6e4b2008-05-16 19:29:10 +00006962 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattner06205d52007-07-15 20:42:37 +00006963 Mask, LHSI->getName()+".mask");
6964 Value *And = InsertNewInstBefore(AndI, ICI);
6965
Owen Anderson1e5f00e2009-07-09 23:48:35 +00006966 return new ICmpInst(*Context,
6967 TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
Owen Andersonb5618da2009-07-03 00:17:18 +00006968 And, Context->getNullValue(And->getType()));
Chris Lattner06205d52007-07-15 20:42:37 +00006969 }
Chris Lattnera74deaf2007-04-03 17:43:25 +00006970 break;
Chris Lattner06205d52007-07-15 20:42:37 +00006971 }
Chris Lattnera74deaf2007-04-03 17:43:25 +00006972
6973 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Chris Lattner06205d52007-07-15 20:42:37 +00006974 case Instruction::AShr: {
Chris Lattnerc44160c2008-03-21 05:19:58 +00006975 // Only handle equality comparisons of shift-by-constant.
Chris Lattner06205d52007-07-15 20:42:37 +00006976 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattnerc44160c2008-03-21 05:19:58 +00006977 if (!ShAmt || !ICI.isEquality()) break;
Chris Lattner06205d52007-07-15 20:42:37 +00006978
Chris Lattnerc44160c2008-03-21 05:19:58 +00006979 // Check that the shift amount is in range. If not, don't perform
6980 // undefined shifts. When the shift is visited it will be
6981 // simplified.
6982 uint32_t TypeBits = RHSV.getBitWidth();
6983 if (ShAmt->uge(TypeBits))
6984 break;
6985
6986 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattner06205d52007-07-15 20:42:37 +00006987
Chris Lattnerc44160c2008-03-21 05:19:58 +00006988 // If we are comparing against bits always shifted out, the
6989 // comparison cannot succeed.
6990 APInt Comp = RHSV << ShAmtVal;
6991 if (LHSI->getOpcode() == Instruction::LShr)
6992 Comp = Comp.lshr(ShAmtVal);
6993 else
6994 Comp = Comp.ashr(ShAmtVal);
6995
6996 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6997 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Andersonb5618da2009-07-03 00:17:18 +00006998 Constant *Cst = Context->getConstantInt(Type::Int1Ty, IsICMP_NE);
Chris Lattnerc44160c2008-03-21 05:19:58 +00006999 return ReplaceInstUsesWith(ICI, Cst);
7000 }
7001
7002 // Otherwise, check to see if the bits shifted out are known to be zero.
7003 // If so, we can compare against the unshifted value:
7004 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Cheng1c89ca72008-04-23 00:38:06 +00007005 if (LHSI->hasOneUse() &&
7006 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattnerc44160c2008-03-21 05:19:58 +00007007 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
Owen Anderson1e5f00e2009-07-09 23:48:35 +00007008 return new ICmpInst(*Context, ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersonb5618da2009-07-03 00:17:18 +00007009 Context->getConstantExprShl(RHS, ShAmt));
Chris Lattnerc44160c2008-03-21 05:19:58 +00007010 }
Chris Lattner06205d52007-07-15 20:42:37 +00007011
Evan Cheng1c89ca72008-04-23 00:38:06 +00007012 if (LHSI->hasOneUse()) {
Chris Lattnerc44160c2008-03-21 05:19:58 +00007013 // Otherwise strength reduce the shift into an and.
7014 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
Owen Andersonb5618da2009-07-03 00:17:18 +00007015 Constant *Mask = Context->getConstantInt(Val);
Chris Lattner06205d52007-07-15 20:42:37 +00007016
Chris Lattnerc44160c2008-03-21 05:19:58 +00007017 Instruction *AndI =
Gabor Greife1f6e4b2008-05-16 19:29:10 +00007018 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattnerc44160c2008-03-21 05:19:58 +00007019 Mask, LHSI->getName()+".mask");
7020 Value *And = InsertNewInstBefore(AndI, ICI);
Owen Anderson1e5f00e2009-07-09 23:48:35 +00007021 return new ICmpInst(*Context, ICI.getPredicate(), And,
Owen Andersonb5618da2009-07-03 00:17:18 +00007022 Context->getConstantExprShl(RHS, ShAmt));
Chris Lattnera74deaf2007-04-03 17:43:25 +00007023 }
7024 break;
Chris Lattner06205d52007-07-15 20:42:37 +00007025 }
Chris Lattnera74deaf2007-04-03 17:43:25 +00007026
7027 case Instruction::SDiv:
7028 case Instruction::UDiv:
7029 // Fold: icmp pred ([us]div X, C1), C2 -> range test
7030 // Fold this div into the comparison, producing a range check.
7031 // Determine, based on the divide type, what the range is being
7032 // checked. If there is an overflow on the low or high side, remember
7033 // it, otherwise compute the range [low, hi) bounding the new value.
7034 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner3bbec592007-06-20 23:46:26 +00007035 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
7036 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
7037 DivRHS))
7038 return R;
Chris Lattnera74deaf2007-04-03 17:43:25 +00007039 break;
Nick Lewycky3b592142008-02-03 16:33:09 +00007040
7041 case Instruction::Add:
7042 // Fold: icmp pred (add, X, C1), C2
7043
7044 if (!ICI.isEquality()) {
7045 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7046 if (!LHSC) break;
7047 const APInt &LHSV = LHSC->getValue();
7048
7049 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
7050 .subtract(LHSV);
7051
7052 if (ICI.isSignedPredicate()) {
7053 if (CR.getLower().isSignBit()) {
Owen Anderson1e5f00e2009-07-09 23:48:35 +00007054 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, LHSI->getOperand(0),
Owen Andersonb5618da2009-07-03 00:17:18 +00007055 Context->getConstantInt(CR.getUpper()));
Nick Lewycky3b592142008-02-03 16:33:09 +00007056 } else if (CR.getUpper().isSignBit()) {
Owen Anderson1e5f00e2009-07-09 23:48:35 +00007057 return new ICmpInst(*Context, ICmpInst::ICMP_SGE, LHSI->getOperand(0),
Owen Andersonb5618da2009-07-03 00:17:18 +00007058 Context->getConstantInt(CR.getLower()));
Nick Lewycky3b592142008-02-03 16:33:09 +00007059 }
7060 } else {
7061 if (CR.getLower().isMinValue()) {
Owen Anderson1e5f00e2009-07-09 23:48:35 +00007062 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, LHSI->getOperand(0),
Owen Andersonb5618da2009-07-03 00:17:18 +00007063 Context->getConstantInt(CR.getUpper()));
Nick Lewycky3b592142008-02-03 16:33:09 +00007064 } else if (CR.getUpper().isMinValue()) {
Owen Anderson1e5f00e2009-07-09 23:48:35 +00007065 return new ICmpInst(*Context, ICmpInst::ICMP_UGE, LHSI->getOperand(0),
Owen Andersonb5618da2009-07-03 00:17:18 +00007066 Context->getConstantInt(CR.getLower()));
Nick Lewycky3b592142008-02-03 16:33:09 +00007067 }
7068 }
7069 }
7070 break;
Chris Lattnera74deaf2007-04-03 17:43:25 +00007071 }
7072
7073 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
7074 if (ICI.isEquality()) {
7075 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7076
7077 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
7078 // the second operand is a constant, simplify a bit.
7079 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
7080 switch (BO->getOpcode()) {
7081 case Instruction::SRem:
7082 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
7083 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
7084 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
7085 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
7086 Instruction *NewRem =
Gabor Greife1f6e4b2008-05-16 19:29:10 +00007087 BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
Chris Lattnera74deaf2007-04-03 17:43:25 +00007088 BO->getName());
7089 InsertNewInstBefore(NewRem, ICI);
Owen Anderson1e5f00e2009-07-09 23:48:35 +00007090 return new ICmpInst(*Context, ICI.getPredicate(), NewRem,
Owen Andersonb5618da2009-07-03 00:17:18 +00007091 Context->getNullValue(BO->getType()));
Chris Lattnera74deaf2007-04-03 17:43:25 +00007092 }
7093 }
7094 break;
7095 case Instruction::Add:
7096 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
7097 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7098 if (BO->hasOneUse())
Owen Anderson1e5f00e2009-07-09 23:48:35 +00007099 return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
Owen Andersonb5618da2009-07-03 00:17:18 +00007100 Context->getConstantExprSub(RHS, BOp1C));
Chris Lattnera74deaf2007-04-03 17:43:25 +00007101 } else if (RHSV == 0) {
7102 // Replace ((add A, B) != 0) with (A != -B) if A or B is
7103 // efficiently invertible, or if the add has just this one use.
7104 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
7105
Owen Andersonb5618da2009-07-03 00:17:18 +00007106 if (Value *NegVal = dyn_castNegVal(BOp1, Context))
Owen Anderson1e5f00e2009-07-09 23:48:35 +00007107 return new ICmpInst(*Context, ICI.getPredicate(), BOp0, NegVal);
Owen Andersonb5618da2009-07-03 00:17:18 +00007108 else if (Value *NegVal = dyn_castNegVal(BOp0, Context))
Owen Anderson1e5f00e2009-07-09 23:48:35 +00007109 return new ICmpInst(*Context, ICI.getPredicate(), NegVal, BOp1);
Chris Lattnera74deaf2007-04-03 17:43:25 +00007110 else if (BO->hasOneUse()) {
Owen Anderson53a52212009-07-13 04:09:18 +00007111 Instruction *Neg = BinaryOperator::CreateNeg(*Context, BOp1);
Chris Lattnera74deaf2007-04-03 17:43:25 +00007112 InsertNewInstBefore(Neg, ICI);
7113 Neg->takeName(BO);
Owen Anderson1e5f00e2009-07-09 23:48:35 +00007114 return new ICmpInst(*Context, ICI.getPredicate(), BOp0, Neg);
Chris Lattnera74deaf2007-04-03 17:43:25 +00007115 }
7116 }
7117 break;
7118 case Instruction::Xor:
7119 // For the xor case, we can xor two constants together, eliminating
7120 // the explicit xor.
7121 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
Owen Anderson1e5f00e2009-07-09 23:48:35 +00007122 return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
Owen Andersonb5618da2009-07-03 00:17:18 +00007123 Context->getConstantExprXor(RHS, BOC));
Chris Lattnera74deaf2007-04-03 17:43:25 +00007124
7125 // FALLTHROUGH
7126 case Instruction::Sub:
7127 // Replace (([sub|xor] A, B) != 0) with (A != B)
7128 if (RHSV == 0)
Owen Anderson1e5f00e2009-07-09 23:48:35 +00007129 return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
Chris Lattnera74deaf2007-04-03 17:43:25 +00007130 BO->getOperand(1));
7131 break;
7132
7133 case Instruction::Or:
7134 // If bits are being or'd in that are not present in the constant we
7135 // are comparing against, then the comparison could never succeed!
7136 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Owen Andersonb5618da2009-07-03 00:17:18 +00007137 Constant *NotCI = Context->getConstantExprNot(RHS);
7138 if (!Context->getConstantExprAnd(BOC, NotCI)->isNullValue())
7139 return ReplaceInstUsesWith(ICI,
7140 Context->getConstantInt(Type::Int1Ty,
7141 isICMP_NE));
Chris Lattnera74deaf2007-04-03 17:43:25 +00007142 }
7143 break;
7144
7145 case Instruction::And:
7146 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7147 // If bits are being compared against that are and'd out, then the
7148 // comparison can never succeed!
7149 if ((RHSV & ~BOC->getValue()) != 0)
Owen Andersonb5618da2009-07-03 00:17:18 +00007150 return ReplaceInstUsesWith(ICI,
7151 Context->getConstantInt(Type::Int1Ty,
7152 isICMP_NE));
Chris Lattnera74deaf2007-04-03 17:43:25 +00007153
7154 // If we have ((X & C) == C), turn it into ((X & C) != 0).
7155 if (RHS == BOC && RHSV.isPowerOf2())
Owen Anderson1e5f00e2009-07-09 23:48:35 +00007156 return new ICmpInst(*Context, isICMP_NE ? ICmpInst::ICMP_EQ :
Chris Lattnera74deaf2007-04-03 17:43:25 +00007157 ICmpInst::ICMP_NE, LHSI,
Owen Andersonb5618da2009-07-03 00:17:18 +00007158 Context->getNullValue(RHS->getType()));
Chris Lattnera74deaf2007-04-03 17:43:25 +00007159
7160 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattnera12a6de2008-06-02 01:29:46 +00007161 if (BOC->getValue().isSignBit()) {
Chris Lattnera74deaf2007-04-03 17:43:25 +00007162 Value *X = BO->getOperand(0);
Owen Andersonb5618da2009-07-03 00:17:18 +00007163 Constant *Zero = Context->getNullValue(X->getType());
Chris Lattnera74deaf2007-04-03 17:43:25 +00007164 ICmpInst::Predicate pred = isICMP_NE ?
7165 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
Owen Anderson1e5f00e2009-07-09 23:48:35 +00007166 return new ICmpInst(*Context, pred, X, Zero);
Chris Lattnera74deaf2007-04-03 17:43:25 +00007167 }
7168
7169 // ((X & ~7) == 0) --> X < 8
7170 if (RHSV == 0 && isHighOnes(BOC)) {
7171 Value *X = BO->getOperand(0);
Owen Andersonb5618da2009-07-03 00:17:18 +00007172 Constant *NegX = Context->getConstantExprNeg(BOC);
Chris Lattnera74deaf2007-04-03 17:43:25 +00007173 ICmpInst::Predicate pred = isICMP_NE ?
7174 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
Owen Anderson1e5f00e2009-07-09 23:48:35 +00007175 return new ICmpInst(*Context, pred, X, NegX);
Chris Lattnera74deaf2007-04-03 17:43:25 +00007176 }
7177 }
7178 default: break;
7179 }
7180 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7181 // Handle icmp {eq|ne} <intrinsic>, intcst.
7182 if (II->getIntrinsicID() == Intrinsic::bswap) {
7183 AddToWorkList(II);
7184 ICI.setOperand(0, II->getOperand(1));
Owen Andersonb5618da2009-07-03 00:17:18 +00007185 ICI.setOperand(1, Context->getConstantInt(RHSV.byteSwap()));
Chris Lattnera74deaf2007-04-03 17:43:25 +00007186 return &ICI;
7187 }
7188 }
Chris Lattnera74deaf2007-04-03 17:43:25 +00007189 }
7190 return 0;
7191}
7192
7193/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7194/// We only handle extending casts so far.
7195///
Reid Spencer266e42b2006-12-23 06:05:41 +00007196Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7197 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007198 Value *LHSCIOp = LHSCI->getOperand(0);
7199 const Type *SrcTy = LHSCIOp->getType();
Reid Spencer266e42b2006-12-23 06:05:41 +00007200 const Type *DestTy = LHSCI->getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00007201 Value *RHSCIOp;
7202
Chris Lattner5aa73fe2007-05-05 22:41:33 +00007203 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
7204 // integer type is the same size as the pointer type.
7205 if (LHSCI->getOpcode() == Instruction::PtrToInt &&
7206 getTargetData().getPointerSizeInBits() ==
7207 cast<IntegerType>(DestTy)->getBitWidth()) {
7208 Value *RHSOp = 0;
7209 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Owen Andersonb5618da2009-07-03 00:17:18 +00007210 RHSOp = Context->getConstantExprIntToPtr(RHSC, SrcTy);
Chris Lattner5aa73fe2007-05-05 22:41:33 +00007211 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7212 RHSOp = RHSC->getOperand(0);
7213 // If the pointer types don't match, insert a bitcast.
7214 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner5a866122008-01-13 22:23:22 +00007215 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
Chris Lattner5aa73fe2007-05-05 22:41:33 +00007216 }
7217
7218 if (RHSOp)
Owen Anderson1e5f00e2009-07-09 23:48:35 +00007219 return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSOp);
Chris Lattner5aa73fe2007-05-05 22:41:33 +00007220 }
7221
7222 // The code below only handles extension cast instructions, so far.
7223 // Enforce this.
Reid Spencer266e42b2006-12-23 06:05:41 +00007224 if (LHSCI->getOpcode() != Instruction::ZExt &&
7225 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattner03f06f12005-01-17 03:20:02 +00007226 return 0;
7227
Reid Spencer266e42b2006-12-23 06:05:41 +00007228 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
7229 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00007230
Reid Spencer266e42b2006-12-23 06:05:41 +00007231 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00007232 // Not an extension from the same type?
7233 RHSCIOp = CI->getOperand(0);
Reid Spencer266e42b2006-12-23 06:05:41 +00007234 if (RHSCIOp->getType() != LHSCIOp->getType())
7235 return 0;
Chris Lattner387bf3f2007-01-13 23:11:38 +00007236
Nick Lewycky8ea81e82008-01-28 03:48:02 +00007237 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Chris Lattner387bf3f2007-01-13 23:11:38 +00007238 // and the other is a zext), then we can't handle this.
7239 if (CI->getOpcode() != LHSCI->getOpcode())
7240 return 0;
7241
Nick Lewycky8ea81e82008-01-28 03:48:02 +00007242 // Deal with equality cases early.
7243 if (ICI.isEquality())
Owen Anderson1e5f00e2009-07-09 23:48:35 +00007244 return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewycky8ea81e82008-01-28 03:48:02 +00007245
7246 // A signed comparison of sign extended values simplifies into a
7247 // signed comparison.
7248 if (isSignedCmp && isSignedExt)
Owen Anderson1e5f00e2009-07-09 23:48:35 +00007249 return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewycky8ea81e82008-01-28 03:48:02 +00007250
7251 // The other three cases all fold into an unsigned comparison.
Owen Anderson1e5f00e2009-07-09 23:48:35 +00007252 return new ICmpInst(*Context, ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer279fa252004-11-28 21:31:15 +00007253 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00007254
Reid Spencer266e42b2006-12-23 06:05:41 +00007255 // If we aren't dealing with a constant on the RHS, exit early
7256 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7257 if (!CI)
7258 return 0;
7259
7260 // Compute the constant that would happen if we truncated to SrcTy then
7261 // reextended to DestTy.
Owen Andersonb5618da2009-07-03 00:17:18 +00007262 Constant *Res1 = Context->getConstantExprTrunc(CI, SrcTy);
7263 Constant *Res2 = Context->getConstantExprCast(LHSCI->getOpcode(),
7264 Res1, DestTy);
Reid Spencer266e42b2006-12-23 06:05:41 +00007265
7266 // If the re-extended constant didn't change...
7267 if (Res2 == CI) {
7268 // Make sure that sign of the Cmp and the sign of the Cast are the same.
7269 // For example, we might have:
Dan Gohman4fe64de2009-06-14 23:30:43 +00007270 // %A = sext i16 %X to i32
7271 // %B = icmp ugt i32 %A, 1330
Reid Spencer266e42b2006-12-23 06:05:41 +00007272 // It is incorrect to transform this into
Dan Gohman4fe64de2009-06-14 23:30:43 +00007273 // %B = icmp ugt i16 %X, 1330
Reid Spencer266e42b2006-12-23 06:05:41 +00007274 // because %A may have negative value.
7275 //
Chris Lattner4fa8bb32008-07-11 04:09:09 +00007276 // However, we allow this when the compare is EQ/NE, because they are
7277 // signless.
7278 if (isSignedExt == isSignedCmp || ICI.isEquality())
Owen Anderson1e5f00e2009-07-09 23:48:35 +00007279 return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, Res1);
Chris Lattner4fa8bb32008-07-11 04:09:09 +00007280 return 0;
Reid Spencer266e42b2006-12-23 06:05:41 +00007281 }
7282
7283 // The re-extended constant changed so the constant cannot be represented
7284 // in the shorter type. Consequently, we cannot emit a simple comparison.
7285
7286 // First, handle some easy cases. We know the result cannot be equal at this
7287 // point so handle the ICI.isEquality() cases
7288 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Andersonb5618da2009-07-03 00:17:18 +00007289 return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00007290 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Andersonb5618da2009-07-03 00:17:18 +00007291 return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00007292
7293 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7294 // should have been folded away previously and not enter in here.
7295 Value *Result;
7296 if (isSignedCmp) {
7297 // We're performing a signed comparison.
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00007298 if (cast<ConstantInt>(CI)->getValue().isNegative())
Owen Andersonb5618da2009-07-03 00:17:18 +00007299 Result = Context->getConstantIntFalse(); // X < (small) --> false
Reid Spencer266e42b2006-12-23 06:05:41 +00007300 else
Owen Andersonb5618da2009-07-03 00:17:18 +00007301 Result = Context->getConstantIntTrue(); // X < (large) --> true
Reid Spencer266e42b2006-12-23 06:05:41 +00007302 } else {
7303 // We're performing an unsigned comparison.
7304 if (isSignedExt) {
7305 // We're performing an unsigned comp with a sign extended value.
7306 // This is true if the input is >= 0. [aka >s -1]
Owen Anderson542619e2009-07-13 20:58:05 +00007307 Constant *NegOne = Context->getAllOnesValue(SrcTy);
Owen Anderson1e5f00e2009-07-09 23:48:35 +00007308 Result = InsertNewInstBefore(new ICmpInst(*Context, ICmpInst::ICMP_SGT,
7309 LHSCIOp, NegOne, ICI.getName()), ICI);
Reid Spencer266e42b2006-12-23 06:05:41 +00007310 } else {
7311 // Unsigned extend & unsigned compare -> always true.
Owen Andersonb5618da2009-07-03 00:17:18 +00007312 Result = Context->getConstantIntTrue();
Reid Spencer266e42b2006-12-23 06:05:41 +00007313 }
7314 }
7315
7316 // Finally, return the value computed.
7317 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
Chris Lattner4fa8bb32008-07-11 04:09:09 +00007318 ICI.getPredicate() == ICmpInst::ICMP_SLT)
Reid Spencer266e42b2006-12-23 06:05:41 +00007319 return ReplaceInstUsesWith(ICI, Result);
Chris Lattner4fa8bb32008-07-11 04:09:09 +00007320
7321 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
7322 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7323 "ICmp should be folded!");
7324 if (Constant *CI = dyn_cast<Constant>(Result))
Owen Andersonb5618da2009-07-03 00:17:18 +00007325 return ReplaceInstUsesWith(ICI, Context->getConstantExprNot(CI));
Owen Anderson542619e2009-07-13 20:58:05 +00007326 return BinaryOperator::CreateNot(*Context, Result);
Chris Lattnerd1f46d32005-04-24 06:59:08 +00007327}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00007328
Reid Spencer2341c222007-02-02 02:16:23 +00007329Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7330 return commonShiftTransforms(I);
7331}
7332
7333Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7334 return commonShiftTransforms(I);
7335}
7336
7337Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner0ccb6632007-12-06 01:59:46 +00007338 if (Instruction *R = commonShiftTransforms(I))
7339 return R;
7340
7341 Value *Op0 = I.getOperand(0);
7342
7343 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
7344 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7345 if (CSI->isAllOnesValue())
7346 return ReplaceInstUsesWith(I, CSI);
Dan Gohman4f356bb2009-02-24 02:00:40 +00007347
Dan Gohman0ed77562009-06-16 19:55:29 +00007348 // See if we can turn a signed shr into an unsigned shr.
7349 if (MaskedValueIsZero(Op0,
7350 APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7351 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7352
7353 // Arithmetic shifting an all-sign-bit value is a no-op.
7354 unsigned NumSignBits = ComputeNumSignBits(Op0);
7355 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7356 return ReplaceInstUsesWith(I, Op0);
Dan Gohman4f356bb2009-02-24 02:00:40 +00007357
Chris Lattner0ccb6632007-12-06 01:59:46 +00007358 return 0;
Reid Spencer2341c222007-02-02 02:16:23 +00007359}
7360
7361Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7362 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner113f4f42002-06-25 16:13:24 +00007363 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00007364
7365 // shl X, 0 == X and shr X, 0 == X
7366 // shl 0, X == 0 and shr 0, X == 0
Owen Andersonb5618da2009-07-03 00:17:18 +00007367 if (Op1 == Context->getNullValue(Op1->getType()) ||
7368 Op0 == Context->getNullValue(Op0->getType()))
Chris Lattnere6794492002-08-12 21:17:25 +00007369 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00007370
Reid Spencer266e42b2006-12-23 06:05:41 +00007371 if (isa<UndefValue>(Op0)) {
7372 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner67f05452004-10-16 23:28:04 +00007373 return ReplaceInstUsesWith(I, Op0);
Reid Spencer266e42b2006-12-23 06:05:41 +00007374 else // undef << X -> 0, undef >>u X -> 0
Owen Andersonb5618da2009-07-03 00:17:18 +00007375 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattner81a7a232004-10-16 18:11:37 +00007376 }
7377 if (isa<UndefValue>(Op1)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00007378 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
7379 return ReplaceInstUsesWith(I, Op0);
7380 else // X << undef, X >>u undef -> 0
Owen Andersonb5618da2009-07-03 00:17:18 +00007381 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattner81a7a232004-10-16 18:11:37 +00007382 }
7383
Dan Gohmanbf0002e2009-05-21 02:28:33 +00007384 // See if we can fold away this shift.
Dan Gohman7ccc52f2009-06-15 22:12:54 +00007385 if (SimplifyDemandedInstructionBits(I))
Dan Gohmanbf0002e2009-05-21 02:28:33 +00007386 return &I;
7387
Chris Lattner183b3362004-04-09 19:05:30 +00007388 // Try to fold constant and into select arguments.
7389 if (isa<Constant>(Op0))
7390 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00007391 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00007392 return R;
7393
Reid Spencere0fc4df2006-10-20 07:07:24 +00007394 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc635f472006-12-31 05:48:39 +00007395 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7396 return Res;
Chris Lattner14553932006-01-06 07:12:35 +00007397 return 0;
7398}
7399
Reid Spencere0fc4df2006-10-20 07:07:24 +00007400Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer2341c222007-02-02 02:16:23 +00007401 BinaryOperator &I) {
Chris Lattner3e2cb662009-01-31 08:24:16 +00007402 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner14553932006-01-06 07:12:35 +00007403
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00007404 // See if we can simplify any instructions used by the instruction whose sole
7405 // purpose is to compute bits we don't care about.
Dan Gohman0ed77562009-06-16 19:55:29 +00007406 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00007407
Dan Gohman4fe64de2009-06-14 23:30:43 +00007408 // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7409 // a signed shift.
Chris Lattner14553932006-01-06 07:12:35 +00007410 //
Zhou Shengb25806f2007-03-30 09:29:48 +00007411 if (Op1->uge(TypeBits)) {
Chris Lattnerd5fea612007-02-02 05:29:55 +00007412 if (I.getOpcode() != Instruction::AShr)
Owen Andersonb5618da2009-07-03 00:17:18 +00007413 return ReplaceInstUsesWith(I, Context->getNullValue(Op0->getType()));
Chris Lattner14553932006-01-06 07:12:35 +00007414 else {
Owen Andersonb5618da2009-07-03 00:17:18 +00007415 I.setOperand(1, Context->getConstantInt(I.getType(), TypeBits-1));
Chris Lattner14553932006-01-06 07:12:35 +00007416 return &I;
Chris Lattnerf5ce2542004-02-23 20:30:06 +00007417 }
Chris Lattner14553932006-01-06 07:12:35 +00007418 }
7419
7420 // ((X*C1) << C2) == (X * (C1 << C2))
7421 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7422 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7423 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greife1f6e4b2008-05-16 19:29:10 +00007424 return BinaryOperator::CreateMul(BO->getOperand(0),
Owen Andersonb5618da2009-07-03 00:17:18 +00007425 Context->getConstantExprShl(BOOp, Op1));
Chris Lattner14553932006-01-06 07:12:35 +00007426
7427 // Try to fold constant and into select arguments.
7428 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7429 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7430 return R;
7431 if (isa<PHINode>(Op0))
7432 if (Instruction *NV = FoldOpIntoPhi(I))
7433 return NV;
7434
Chris Lattner74b2ab52007-12-22 09:07:47 +00007435 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7436 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7437 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7438 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7439 // place. Don't try to do this transformation in this case. Also, we
7440 // require that the input operand is a shift-by-constant so that we have
7441 // confidence that the shifts will get folded together. We could do this
7442 // xform in more cases, but it is unlikely to be profitable.
7443 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
7444 isa<ConstantInt>(TrOp->getOperand(1))) {
7445 // Okay, we'll do this xform. Make the shift of shift.
Owen Andersonb5618da2009-07-03 00:17:18 +00007446 Constant *ShAmt = Context->getConstantExprZExt(Op1, TrOp->getType());
Gabor Greife1f6e4b2008-05-16 19:29:10 +00007447 Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
Chris Lattner74b2ab52007-12-22 09:07:47 +00007448 I.getName());
7449 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
7450
7451 // For logical shifts, the truncation has the effect of making the high
7452 // part of the register be zeros. Emulate this by inserting an AND to
7453 // clear the top bits as needed. This 'and' will usually be zapped by
7454 // other xforms later if dead.
Dan Gohman0ed77562009-06-16 19:55:29 +00007455 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7456 unsigned DstSize = TI->getType()->getScalarSizeInBits();
Chris Lattner74b2ab52007-12-22 09:07:47 +00007457 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7458
7459 // The mask we constructed says what the trunc would do if occurring
7460 // between the shifts. We want to know the effect *after* the second
7461 // shift. We know that it is a logical shift by a constant, so adjust the
7462 // mask as appropriate.
7463 if (I.getOpcode() == Instruction::Shl)
7464 MaskV <<= Op1->getZExtValue();
7465 else {
7466 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7467 MaskV = MaskV.lshr(Op1->getZExtValue());
7468 }
7469
Owen Andersonb5618da2009-07-03 00:17:18 +00007470 Instruction *And =
7471 BinaryOperator::CreateAnd(NSh, Context->getConstantInt(MaskV),
7472 TI->getName());
Chris Lattner74b2ab52007-12-22 09:07:47 +00007473 InsertNewInstBefore(And, I); // shift1 & 0x00FF
7474
7475 // Return the value truncated to the interesting size.
7476 return new TruncInst(And, I.getType());
7477 }
7478 }
7479
Chris Lattner14553932006-01-06 07:12:35 +00007480 if (Op0->hasOneUse()) {
Chris Lattner14553932006-01-06 07:12:35 +00007481 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7482 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7483 Value *V1, *V2;
7484 ConstantInt *CC;
7485 switch (Op0BO->getOpcode()) {
Chris Lattner27cb9db2005-09-18 05:12:10 +00007486 default: break;
7487 case Instruction::Add:
7488 case Instruction::And:
7489 case Instruction::Or:
Reid Spencer2f34b982007-02-02 14:41:37 +00007490 case Instruction::Xor: {
Chris Lattner27cb9db2005-09-18 05:12:10 +00007491 // These operators commute.
7492 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00007493 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
Owen Anderson16e76742009-07-10 17:35:01 +00007494 match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
7495 m_Specific(Op1)), *Context)){
Gabor Greife1f6e4b2008-05-16 19:29:10 +00007496 Instruction *YS = BinaryOperator::CreateShl(
Chris Lattner14553932006-01-06 07:12:35 +00007497 Op0BO->getOperand(0), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00007498 Op0BO->getName());
7499 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00007500 Instruction *X =
Gabor Greife1f6e4b2008-05-16 19:29:10 +00007501 BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
Chris Lattner24cd2fa2006-02-09 07:41:14 +00007502 Op0BO->getOperand(1)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00007503 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Shengfd28a332007-03-30 17:20:39 +00007504 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersonb5618da2009-07-03 00:17:18 +00007505 return BinaryOperator::CreateAnd(X, Context->getConstantInt(
Zhou Sheng5e60a4a2007-03-30 05:45:18 +00007506 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner797dee72005-09-18 06:30:59 +00007507 }
Chris Lattner14553932006-01-06 07:12:35 +00007508
Chris Lattner797dee72005-09-18 06:30:59 +00007509 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencer2f34b982007-02-02 14:41:37 +00007510 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattnerfe53cf22007-03-05 00:11:19 +00007511 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencer2f34b982007-02-02 14:41:37 +00007512 match(Op0BOOp1,
Chris Lattner44152742008-11-16 05:38:51 +00007513 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
Owen Anderson16e76742009-07-10 17:35:01 +00007514 m_ConstantInt(CC)), *Context) &&
Chris Lattner44152742008-11-16 05:38:51 +00007515 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
Gabor Greife1f6e4b2008-05-16 19:29:10 +00007516 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer2341c222007-02-02 02:16:23 +00007517 Op0BO->getOperand(0), Op1,
7518 Op0BO->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00007519 InsertNewInstBefore(YS, I); // (Y << C)
7520 Instruction *XM =
Owen Andersonb5618da2009-07-03 00:17:18 +00007521 BinaryOperator::CreateAnd(V1,
7522 Context->getConstantExprShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00007523 V1->getName()+".mask");
7524 InsertNewInstBefore(XM, I); // X & (CC << C)
7525
Gabor Greife1f6e4b2008-05-16 19:29:10 +00007526 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Chris Lattner797dee72005-09-18 06:30:59 +00007527 }
Reid Spencer2f34b982007-02-02 14:41:37 +00007528 }
Chris Lattner14553932006-01-06 07:12:35 +00007529
Reid Spencer2f34b982007-02-02 14:41:37 +00007530 // FALL THROUGH.
7531 case Instruction::Sub: {
Chris Lattner27cb9db2005-09-18 05:12:10 +00007532 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00007533 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
Owen Anderson16e76742009-07-10 17:35:01 +00007534 match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
7535 m_Specific(Op1)), *Context)){
Gabor Greife1f6e4b2008-05-16 19:29:10 +00007536 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer2341c222007-02-02 02:16:23 +00007537 Op0BO->getOperand(1), Op1,
7538 Op0BO->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00007539 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00007540 Instruction *X =
Gabor Greife1f6e4b2008-05-16 19:29:10 +00007541 BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
Chris Lattner24cd2fa2006-02-09 07:41:14 +00007542 Op0BO->getOperand(0)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00007543 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Shengfd28a332007-03-30 17:20:39 +00007544 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersonb5618da2009-07-03 00:17:18 +00007545 return BinaryOperator::CreateAnd(X, Context->getConstantInt(
Zhou Sheng5e60a4a2007-03-30 05:45:18 +00007546 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner797dee72005-09-18 06:30:59 +00007547 }
Chris Lattner14553932006-01-06 07:12:35 +00007548
Chris Lattner1df0e982006-05-31 21:14:00 +00007549 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner797dee72005-09-18 06:30:59 +00007550 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7551 match(Op0BO->getOperand(0),
7552 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Owen Anderson16e76742009-07-10 17:35:01 +00007553 m_ConstantInt(CC)), *Context) && V2 == Op1 &&
Chris Lattner24cd2fa2006-02-09 07:41:14 +00007554 cast<BinaryOperator>(Op0BO->getOperand(0))
7555 ->getOperand(0)->hasOneUse()) {
Gabor Greife1f6e4b2008-05-16 19:29:10 +00007556 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer2341c222007-02-02 02:16:23 +00007557 Op0BO->getOperand(1), Op1,
7558 Op0BO->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00007559 InsertNewInstBefore(YS, I); // (Y << C)
7560 Instruction *XM =
Owen Andersonb5618da2009-07-03 00:17:18 +00007561 BinaryOperator::CreateAnd(V1,
7562 Context->getConstantExprShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00007563 V1->getName()+".mask");
7564 InsertNewInstBefore(XM, I); // X & (CC << C)
7565
Gabor Greife1f6e4b2008-05-16 19:29:10 +00007566 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Chris Lattner797dee72005-09-18 06:30:59 +00007567 }
Chris Lattner14553932006-01-06 07:12:35 +00007568
Chris Lattner27cb9db2005-09-18 05:12:10 +00007569 break;
Reid Spencer2f34b982007-02-02 14:41:37 +00007570 }
Chris Lattner14553932006-01-06 07:12:35 +00007571 }
7572
7573
7574 // If the operand is an bitwise operator with a constant RHS, and the
7575 // shift is the only use, we can pull it out of the shift.
7576 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7577 bool isValid = true; // Valid only for And, Or, Xor
7578 bool highBitSet = false; // Transform if high bit of constant set?
7579
7580 switch (Op0BO->getOpcode()) {
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00007581 default: isValid = false; break; // Do not perform transform!
Chris Lattner44bd3922004-10-08 03:46:20 +00007582 case Instruction::Add:
7583 isValid = isLeftShift;
7584 break;
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00007585 case Instruction::Or:
7586 case Instruction::Xor:
7587 highBitSet = false;
7588 break;
7589 case Instruction::And:
7590 highBitSet = true;
7591 break;
Chris Lattner14553932006-01-06 07:12:35 +00007592 }
7593
7594 // If this is a signed shift right, and the high bit is modified
7595 // by the logical operation, do not perform the transformation.
7596 // The highBitSet boolean indicates the value of the high bit of
7597 // the constant which would cause it to be modified for this
7598 // operation.
7599 //
Chris Lattnerd2bbbab2007-12-06 06:25:04 +00007600 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Sheng23f7a1c2007-03-28 15:02:20 +00007601 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner14553932006-01-06 07:12:35 +00007602
7603 if (isValid) {
Owen Andersonb5618da2009-07-03 00:17:18 +00007604 Constant *NewRHS = Context->getConstantExpr(I.getOpcode(), Op0C, Op1);
Chris Lattner14553932006-01-06 07:12:35 +00007605
7606 Instruction *NewShift =
Gabor Greife1f6e4b2008-05-16 19:29:10 +00007607 BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner14553932006-01-06 07:12:35 +00007608 InsertNewInstBefore(NewShift, I);
Chris Lattner6e0123b2007-02-11 01:23:03 +00007609 NewShift->takeName(Op0BO);
Chris Lattner14553932006-01-06 07:12:35 +00007610
Gabor Greife1f6e4b2008-05-16 19:29:10 +00007611 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Chris Lattner14553932006-01-06 07:12:35 +00007612 NewRHS);
7613 }
7614 }
7615 }
7616 }
7617
Chris Lattnereb372a02006-01-06 07:52:12 +00007618 // Find out if this is a shift of a shift by a constant.
Reid Spencer2341c222007-02-02 02:16:23 +00007619 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7620 if (ShiftOp && !ShiftOp->isShift())
7621 ShiftOp = 0;
Chris Lattnereb372a02006-01-06 07:52:12 +00007622
Reid Spencere0fc4df2006-10-20 07:07:24 +00007623 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00007624 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Shengb25806f2007-03-30 09:29:48 +00007625 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7626 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattner3e009e82007-02-05 00:57:54 +00007627 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7628 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
7629 Value *X = ShiftOp->getOperand(0);
Chris Lattnereb372a02006-01-06 07:52:12 +00007630
Zhou Sheng56cda952007-04-02 08:20:41 +00007631 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Chris Lattner3e009e82007-02-05 00:57:54 +00007632
7633 const IntegerType *Ty = cast<IntegerType>(I.getType());
7634
7635 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner6c344e52007-02-03 23:28:07 +00007636 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattner0a981d12009-03-20 22:41:15 +00007637 // If this is oversized composite shift, then unsigned shifts get 0, ashr
7638 // saturates.
7639 if (AmtSum >= TypeBits) {
7640 if (I.getOpcode() != Instruction::AShr)
Owen Andersonb5618da2009-07-03 00:17:18 +00007641 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattner0a981d12009-03-20 22:41:15 +00007642 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
7643 }
7644
Gabor Greife1f6e4b2008-05-16 19:29:10 +00007645 return BinaryOperator::Create(I.getOpcode(), X,
Owen Andersonb5618da2009-07-03 00:17:18 +00007646 Context->getConstantInt(Ty, AmtSum));
Chris Lattner3e009e82007-02-05 00:57:54 +00007647 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
7648 I.getOpcode() == Instruction::AShr) {
Chris Lattner0a981d12009-03-20 22:41:15 +00007649 if (AmtSum >= TypeBits)
Owen Andersonb5618da2009-07-03 00:17:18 +00007650 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattner0a981d12009-03-20 22:41:15 +00007651
Chris Lattner3e009e82007-02-05 00:57:54 +00007652 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Owen Andersonb5618da2009-07-03 00:17:18 +00007653 return BinaryOperator::CreateLShr(X, Context->getConstantInt(Ty, AmtSum));
Chris Lattner3e009e82007-02-05 00:57:54 +00007654 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
7655 I.getOpcode() == Instruction::LShr) {
7656 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
Chris Lattner0a981d12009-03-20 22:41:15 +00007657 if (AmtSum >= TypeBits)
7658 AmtSum = TypeBits-1;
7659
Chris Lattner3e009e82007-02-05 00:57:54 +00007660 Instruction *Shift =
Owen Andersonb5618da2009-07-03 00:17:18 +00007661 BinaryOperator::CreateAShr(X, Context->getConstantInt(Ty, AmtSum));
Chris Lattner3e009e82007-02-05 00:57:54 +00007662 InsertNewInstBefore(Shift, I);
7663
Zhou Sheng23f7a1c2007-03-28 15:02:20 +00007664 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersonb5618da2009-07-03 00:17:18 +00007665 return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
Chris Lattnereb372a02006-01-06 07:52:12 +00007666 }
7667
Chris Lattner3e009e82007-02-05 00:57:54 +00007668 // Okay, if we get here, one shift must be left, and the other shift must be
7669 // right. See if the amounts are equal.
7670 if (ShiftAmt1 == ShiftAmt2) {
7671 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7672 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer52830322007-03-25 21:11:44 +00007673 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersonb5618da2009-07-03 00:17:18 +00007674 return BinaryOperator::CreateAnd(X, Context->getConstantInt(Mask));
Chris Lattner3e009e82007-02-05 00:57:54 +00007675 }
7676 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7677 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng150f3bb2007-04-01 17:13:37 +00007678 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersonb5618da2009-07-03 00:17:18 +00007679 return BinaryOperator::CreateAnd(X, Context->getConstantInt(Mask));
Chris Lattner3e009e82007-02-05 00:57:54 +00007680 }
7681 // We can simplify ((X << C) >>s C) into a trunc + sext.
7682 // NOTE: we could do this for any C, but that would make 'unusual' integer
7683 // types. For now, just stick to ones well-supported by the code
7684 // generators.
7685 const Type *SExtType = 0;
7686 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Sheng23f7a1c2007-03-28 15:02:20 +00007687 case 1 :
7688 case 8 :
7689 case 16 :
7690 case 32 :
7691 case 64 :
7692 case 128:
Owen Andersonb5618da2009-07-03 00:17:18 +00007693 SExtType = Context->getIntegerType(Ty->getBitWidth() - ShiftAmt1);
Zhou Sheng23f7a1c2007-03-28 15:02:20 +00007694 break;
Chris Lattner3e009e82007-02-05 00:57:54 +00007695 default: break;
7696 }
7697 if (SExtType) {
7698 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7699 InsertNewInstBefore(NewTrunc, I);
7700 return new SExtInst(NewTrunc, Ty);
7701 }
7702 // Otherwise, we can't handle it yet.
7703 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng56cda952007-04-02 08:20:41 +00007704 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnereb372a02006-01-06 07:52:12 +00007705
Chris Lattner83ac5ae92007-02-05 05:57:49 +00007706 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattner3e009e82007-02-05 00:57:54 +00007707 if (I.getOpcode() == Instruction::Shl) {
7708 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7709 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattner9cbfbc22006-01-07 01:32:28 +00007710 Instruction *Shift =
Owen Andersonb5618da2009-07-03 00:17:18 +00007711 BinaryOperator::CreateShl(X, Context->getConstantInt(Ty, ShiftDiff));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00007712 InsertNewInstBefore(Shift, I);
7713
Reid Spencer52830322007-03-25 21:11:44 +00007714 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersonb5618da2009-07-03 00:17:18 +00007715 return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
Chris Lattnereb372a02006-01-06 07:52:12 +00007716 }
Chris Lattner3e009e82007-02-05 00:57:54 +00007717
Chris Lattner83ac5ae92007-02-05 05:57:49 +00007718 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattner3e009e82007-02-05 00:57:54 +00007719 if (I.getOpcode() == Instruction::LShr) {
7720 assert(ShiftOp->getOpcode() == Instruction::Shl);
7721 Instruction *Shift =
Owen Andersonb5618da2009-07-03 00:17:18 +00007722 BinaryOperator::CreateLShr(X, Context->getConstantInt(Ty, ShiftDiff));
Chris Lattner3e009e82007-02-05 00:57:54 +00007723 InsertNewInstBefore(Shift, I);
Chris Lattnereb372a02006-01-06 07:52:12 +00007724
Reid Spencer769a5a82007-03-26 17:18:58 +00007725 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersonb5618da2009-07-03 00:17:18 +00007726 return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
Chris Lattner27cb9db2005-09-18 05:12:10 +00007727 }
Chris Lattner3e009e82007-02-05 00:57:54 +00007728
7729 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7730 } else {
7731 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng56cda952007-04-02 08:20:41 +00007732 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattner3e009e82007-02-05 00:57:54 +00007733
Chris Lattner83ac5ae92007-02-05 05:57:49 +00007734 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattner3e009e82007-02-05 00:57:54 +00007735 if (I.getOpcode() == Instruction::Shl) {
7736 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7737 ShiftOp->getOpcode() == Instruction::AShr);
7738 Instruction *Shift =
Gabor Greife1f6e4b2008-05-16 19:29:10 +00007739 BinaryOperator::Create(ShiftOp->getOpcode(), X,
Owen Andersonb5618da2009-07-03 00:17:18 +00007740 Context->getConstantInt(Ty, ShiftDiff));
Chris Lattner3e009e82007-02-05 00:57:54 +00007741 InsertNewInstBefore(Shift, I);
7742
Reid Spencer52830322007-03-25 21:11:44 +00007743 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersonb5618da2009-07-03 00:17:18 +00007744 return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
Chris Lattner3e009e82007-02-05 00:57:54 +00007745 }
7746
Chris Lattner83ac5ae92007-02-05 05:57:49 +00007747 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattner3e009e82007-02-05 00:57:54 +00007748 if (I.getOpcode() == Instruction::LShr) {
7749 assert(ShiftOp->getOpcode() == Instruction::Shl);
7750 Instruction *Shift =
Owen Andersonb5618da2009-07-03 00:17:18 +00007751 BinaryOperator::CreateShl(X, Context->getConstantInt(Ty, ShiftDiff));
Chris Lattner3e009e82007-02-05 00:57:54 +00007752 InsertNewInstBefore(Shift, I);
7753
Reid Spencer441486c2007-03-26 23:45:51 +00007754 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersonb5618da2009-07-03 00:17:18 +00007755 return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
Chris Lattner3e009e82007-02-05 00:57:54 +00007756 }
7757
7758 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner86102b82005-01-01 16:22:27 +00007759 }
Chris Lattnereb372a02006-01-06 07:52:12 +00007760 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00007761 return 0;
7762}
7763
Chris Lattner48a44f72002-05-02 17:06:02 +00007764
Chris Lattner8f663e82005-10-29 04:36:15 +00007765/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7766/// expression. If so, decompose it, returning some value X, such that Val is
7767/// X*Scale+Offset.
7768///
7769static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Owen Anderson38264b12009-07-06 23:00:19 +00007770 int &Offset, LLVMContext *Context) {
Reid Spencerc635f472006-12-31 05:48:39 +00007771 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
Reid Spencere0fc4df2006-10-20 07:07:24 +00007772 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc635f472006-12-31 05:48:39 +00007773 Offset = CI->getZExtValue();
Chris Lattnerd8675e42007-10-12 05:30:59 +00007774 Scale = 0;
Owen Andersonb5618da2009-07-03 00:17:18 +00007775 return Context->getConstantInt(Type::Int32Ty, 0);
Chris Lattnerd8675e42007-10-12 05:30:59 +00007776 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7777 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7778 if (I->getOpcode() == Instruction::Shl) {
7779 // This is a value scaled by '1 << the shift amt'.
7780 Scale = 1U << RHS->getZExtValue();
7781 Offset = 0;
7782 return I->getOperand(0);
7783 } else if (I->getOpcode() == Instruction::Mul) {
7784 // This value is scaled by 'RHS'.
7785 Scale = RHS->getZExtValue();
7786 Offset = 0;
7787 return I->getOperand(0);
7788 } else if (I->getOpcode() == Instruction::Add) {
7789 // We have X+C. Check to see if we really have (X*C2)+C1,
7790 // where C1 is divisible by C2.
7791 unsigned SubScale;
7792 Value *SubVal =
Owen Andersonb5618da2009-07-03 00:17:18 +00007793 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
7794 Offset, Context);
Chris Lattnerd8675e42007-10-12 05:30:59 +00007795 Offset += RHS->getZExtValue();
7796 Scale = SubScale;
7797 return SubVal;
Chris Lattner8f663e82005-10-29 04:36:15 +00007798 }
7799 }
7800 }
7801
7802 // Otherwise, we can't look past this.
7803 Scale = 1;
7804 Offset = 0;
7805 return Val;
7806}
7807
7808
Chris Lattner216be912005-10-24 06:03:58 +00007809/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7810/// try to eliminate the cast by moving the type information into the alloc.
Chris Lattner1db224d2007-04-27 17:44:50 +00007811Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Chris Lattner216be912005-10-24 06:03:58 +00007812 AllocationInst &AI) {
Chris Lattner1db224d2007-04-27 17:44:50 +00007813 const PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattner216be912005-10-24 06:03:58 +00007814
Chris Lattnerac87beb2005-10-24 06:22:12 +00007815 // Remove any uses of AI that are dead.
7816 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner99c6cf62007-02-15 22:52:10 +00007817
Chris Lattnerac87beb2005-10-24 06:22:12 +00007818 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7819 Instruction *User = cast<Instruction>(*UI++);
7820 if (isInstructionTriviallyDead(User)) {
7821 while (UI != E && *UI == User)
7822 ++UI; // If this instruction uses AI more than once, don't break UI.
7823
Chris Lattnerac87beb2005-10-24 06:22:12 +00007824 ++NumDeadInst;
Bill Wendling5dbf43c2006-11-26 09:46:52 +00007825 DOUT << "IC: DCE: " << *User;
Chris Lattner51f54572007-03-02 19:59:19 +00007826 EraseInstFromFunction(*User);
Chris Lattnerac87beb2005-10-24 06:22:12 +00007827 }
7828 }
7829
Chris Lattner216be912005-10-24 06:03:58 +00007830 // Get the type really allocated and the type casted to.
7831 const Type *AllocElTy = AI.getAllocatedType();
7832 const Type *CastElTy = PTy->getElementType();
7833 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00007834
Chris Lattner945e4372007-02-14 05:52:17 +00007835 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7836 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner355ecc02005-10-24 06:26:18 +00007837 if (CastElTyAlign < AllocElTyAlign) return 0;
7838
Chris Lattner46705b22005-10-24 06:35:18 +00007839 // If the allocation has multiple uses, only promote it if we are strictly
7840 // increasing the alignment of the resultant allocation. If we keep it the
Dale Johannesenad6b4732009-03-05 00:39:02 +00007841 // same, we open the door to infinite loops of various kinds. (A reference
7842 // from a dbg.declare doesn't count as a use for this purpose.)
7843 if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7844 CastElTyAlign == AllocElTyAlign) return 0;
Chris Lattner46705b22005-10-24 06:35:18 +00007845
Duncan Sandsaf9eaa82009-05-09 07:06:46 +00007846 uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7847 uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
Chris Lattnerbb171802005-10-27 05:53:56 +00007848 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00007849
Chris Lattner8270c332005-10-29 03:19:53 +00007850 // See if we can satisfy the modulus by pulling a scale out of the array
7851 // size argument.
Jeff Cohen5a1c7502007-04-04 16:58:57 +00007852 unsigned ArraySizeScale;
7853 int ArrayOffset;
Chris Lattner8f663e82005-10-29 04:36:15 +00007854 Value *NumElements = // See if the array size is a decomposable linear expr.
Owen Andersonb5618da2009-07-03 00:17:18 +00007855 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
7856 ArrayOffset, Context);
Chris Lattner8f663e82005-10-29 04:36:15 +00007857
Chris Lattner8270c332005-10-29 03:19:53 +00007858 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7859 // do the xform.
Chris Lattner8f663e82005-10-29 04:36:15 +00007860 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7861 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattnerb3ecf962005-10-27 06:12:00 +00007862
Chris Lattner8270c332005-10-29 03:19:53 +00007863 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7864 Value *Amt = 0;
7865 if (Scale == 1) {
7866 Amt = NumElements;
7867 } else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00007868 // If the allocation size is constant, form a constant mul expression
Owen Andersonb5618da2009-07-03 00:17:18 +00007869 Amt = Context->getConstantInt(Type::Int32Ty, Scale);
Reid Spencerc635f472006-12-31 05:48:39 +00007870 if (isa<ConstantInt>(NumElements))
Owen Andersonb5618da2009-07-03 00:17:18 +00007871 Amt = Context->getConstantExprMul(cast<ConstantInt>(NumElements),
Dan Gohman7ccc52f2009-06-15 22:12:54 +00007872 cast<ConstantInt>(Amt));
Reid Spencere0fc4df2006-10-20 07:07:24 +00007873 // otherwise multiply the amount and the number of elements
Chris Lattnere5494932009-03-17 17:55:15 +00007874 else {
Gabor Greife1f6e4b2008-05-16 19:29:10 +00007875 Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
Chris Lattner8270c332005-10-29 03:19:53 +00007876 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattnerb3ecf962005-10-27 06:12:00 +00007877 }
Chris Lattnerbb171802005-10-27 05:53:56 +00007878 }
7879
Jeff Cohen5a1c7502007-04-04 16:58:57 +00007880 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Owen Andersonb5618da2009-07-03 00:17:18 +00007881 Value *Off = Context->getConstantInt(Type::Int32Ty, Offset, true);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00007882 Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
Chris Lattner8f663e82005-10-29 04:36:15 +00007883 Amt = InsertNewInstBefore(Tmp, AI);
7884 }
7885
Chris Lattner216be912005-10-24 06:03:58 +00007886 AllocationInst *New;
7887 if (isa<MallocInst>(AI))
Chris Lattner6e0123b2007-02-11 01:23:03 +00007888 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
Chris Lattner216be912005-10-24 06:03:58 +00007889 else
Chris Lattner6e0123b2007-02-11 01:23:03 +00007890 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
Chris Lattner216be912005-10-24 06:03:58 +00007891 InsertNewInstBefore(New, AI);
Chris Lattner6e0123b2007-02-11 01:23:03 +00007892 New->takeName(&AI);
Chris Lattner46705b22005-10-24 06:35:18 +00007893
Dale Johannesenad6b4732009-03-05 00:39:02 +00007894 // If the allocation has one real use plus a dbg.declare, just remove the
7895 // declare.
7896 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7897 EraseInstFromFunction(*DI);
7898 }
7899 // If the allocation has multiple real uses, insert a cast and change all
7900 // things that used it to use the new cast. This will also hack on CI, but it
7901 // will die soon.
7902 else if (!AI.hasOneUse()) {
Chris Lattner46705b22005-10-24 06:35:18 +00007903 AddUsesToWorkList(AI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007904 // New is the allocation instruction, pointer typed. AI is the original
7905 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7906 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner46705b22005-10-24 06:35:18 +00007907 InsertNewInstBefore(NewCast, AI);
7908 AI.replaceAllUsesWith(NewCast);
7909 }
Chris Lattner216be912005-10-24 06:03:58 +00007910 return ReplaceInstUsesWith(CI, New);
7911}
7912
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00007913/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerda1d04a2007-03-03 05:27:34 +00007914/// and return it as type Ty without inserting any new casts and without
7915/// changing the computed value. This is used by code that tries to decide
7916/// whether promoting or shrinking integer operations to wider or smaller types
7917/// will allow us to eliminate a truncate or extend.
7918///
7919/// This is a truncation operation if Ty is smaller than V->getType(), or an
7920/// extension operation if Ty is larger.
Chris Lattnerb5ee8b32008-06-18 04:00:49 +00007921///
7922/// If CastOpc is a truncation, then Ty will be a type smaller than V. We
7923/// should return true if trunc(V) can be computed by computing V in the smaller
7924/// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
7925/// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7926/// efficiently truncated.
7927///
7928/// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7929/// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7930/// the final result.
Dan Gohman7ccc52f2009-06-15 22:12:54 +00007931bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Chengbeac6f82009-01-16 02:11:43 +00007932 unsigned CastOpc,
7933 int &NumCastsRemoved){
Chris Lattnerda1d04a2007-03-03 05:27:34 +00007934 // We can always evaluate constants in another type.
Dan Gohman7ccc52f2009-06-15 22:12:54 +00007935 if (isa<Constant>(V))
Chris Lattnerda1d04a2007-03-03 05:27:34 +00007936 return true;
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00007937
7938 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerda1d04a2007-03-03 05:27:34 +00007939 if (!I) return false;
7940
Dan Gohman7ccc52f2009-06-15 22:12:54 +00007941 const Type *OrigTy = V->getType();
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00007942
Chris Lattnerb0418fc2007-08-02 06:11:14 +00007943 // If this is an extension or truncate, we can often eliminate it.
7944 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7945 // If this is a cast from the destination type, we can trivially eliminate
7946 // it, and this will remove a cast overall.
7947 if (I->getOperand(0)->getType() == Ty) {
7948 // If the first operand is itself a cast, and is eliminable, do not count
7949 // this as an eliminable cast. We would prefer to eliminate those two
7950 // casts first.
Chris Lattnerb5ee8b32008-06-18 04:00:49 +00007951 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
Chris Lattnerb0418fc2007-08-02 06:11:14 +00007952 ++NumCastsRemoved;
7953 return true;
7954 }
7955 }
7956
7957 // We can't extend or shrink something that has multiple uses: doing so would
7958 // require duplicating the instruction in general, which isn't profitable.
7959 if (!I->hasOneUse()) return false;
7960
Evan Cheng60e19a42009-01-15 17:01:23 +00007961 unsigned Opc = I->getOpcode();
7962 switch (Opc) {
Chris Lattnerda1d04a2007-03-03 05:27:34 +00007963 case Instruction::Add:
7964 case Instruction::Sub:
Nick Lewycky9f1a4dc2008-07-05 21:19:34 +00007965 case Instruction::Mul:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00007966 case Instruction::And:
7967 case Instruction::Or:
7968 case Instruction::Xor:
7969 // These operators can all arbitrarily be extended or truncated.
Chris Lattnerb0418fc2007-08-02 06:11:14 +00007970 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Chengbeac6f82009-01-16 02:11:43 +00007971 NumCastsRemoved) &&
Chris Lattnerb0418fc2007-08-02 06:11:14 +00007972 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
Evan Chengbeac6f82009-01-16 02:11:43 +00007973 NumCastsRemoved);
Chris Lattnerda1d04a2007-03-03 05:27:34 +00007974
Chris Lattner960acb02006-11-29 07:18:39 +00007975 case Instruction::Shl:
Chris Lattnerda1d04a2007-03-03 05:27:34 +00007976 // If we are truncating the result of this SHL, and if it's a shift of a
7977 // constant amount, we can always perform a SHL in a smaller type.
7978 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00007979 uint32_t BitWidth = Ty->getScalarSizeInBits();
7980 if (BitWidth < OrigTy->getScalarSizeInBits() &&
Zhou Shengfd28a332007-03-30 17:20:39 +00007981 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattnerb0418fc2007-08-02 06:11:14 +00007982 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Chengbeac6f82009-01-16 02:11:43 +00007983 NumCastsRemoved);
Chris Lattnerda1d04a2007-03-03 05:27:34 +00007984 }
7985 break;
7986 case Instruction::LShr:
Chris Lattnerda1d04a2007-03-03 05:27:34 +00007987 // If this is a truncate of a logical shr, we can truncate it to a smaller
7988 // lshr iff we know that the bits we would otherwise be shifting in are
7989 // already zeros.
7990 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00007991 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7992 uint32_t BitWidth = Ty->getScalarSizeInBits();
Zhou Shengfd28a332007-03-30 17:20:39 +00007993 if (BitWidth < OrigBitWidth &&
Chris Lattnerda1d04a2007-03-03 05:27:34 +00007994 MaskedValueIsZero(I->getOperand(0),
Zhou Shengfd28a332007-03-30 17:20:39 +00007995 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7996 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattnerb0418fc2007-08-02 06:11:14 +00007997 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Chengbeac6f82009-01-16 02:11:43 +00007998 NumCastsRemoved);
Chris Lattnerda1d04a2007-03-03 05:27:34 +00007999 }
8000 }
Chris Lattner960acb02006-11-29 07:18:39 +00008001 break;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008002 case Instruction::ZExt:
8003 case Instruction::SExt:
Chris Lattnerb0418fc2007-08-02 06:11:14 +00008004 case Instruction::Trunc:
8005 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattnerdc2cf222007-08-02 17:23:38 +00008006 // can safely replace it. Note that replacing it does not reduce the number
8007 // of casts in the input.
Evan Cheng60e19a42009-01-15 17:01:23 +00008008 if (Opc == CastOpc)
8009 return true;
8010
8011 // sext (zext ty1), ty2 -> zext ty2
Evan Chengff716cb2009-01-15 17:09:07 +00008012 if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00008013 return true;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008014 break;
Nick Lewycky9f1a4dc2008-07-05 21:19:34 +00008015 case Instruction::Select: {
8016 SelectInst *SI = cast<SelectInst>(I);
8017 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
Evan Chengbeac6f82009-01-16 02:11:43 +00008018 NumCastsRemoved) &&
Nick Lewycky9f1a4dc2008-07-05 21:19:34 +00008019 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
Evan Chengbeac6f82009-01-16 02:11:43 +00008020 NumCastsRemoved);
Nick Lewycky9f1a4dc2008-07-05 21:19:34 +00008021 }
Chris Lattnerb5ee8b32008-06-18 04:00:49 +00008022 case Instruction::PHI: {
8023 // We can change a phi if we can change all operands.
8024 PHINode *PN = cast<PHINode>(I);
8025 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
8026 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
Evan Chengbeac6f82009-01-16 02:11:43 +00008027 NumCastsRemoved))
Chris Lattnerb5ee8b32008-06-18 04:00:49 +00008028 return false;
8029 return true;
8030 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008031 default:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00008032 // TODO: Can handle more cases here.
8033 break;
8034 }
8035
8036 return false;
8037}
8038
8039/// EvaluateInDifferentType - Given an expression that
8040/// CanEvaluateInDifferentType returns true for, actually insert the code to
8041/// evaluate the expression.
Reid Spencer74a528b2006-12-13 18:21:21 +00008042Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerda1d04a2007-03-03 05:27:34 +00008043 bool isSigned) {
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00008044 if (Constant *C = dyn_cast<Constant>(V))
Owen Andersonb5618da2009-07-03 00:17:18 +00008045 return Context->getConstantExprIntegerCast(C, Ty,
8046 isSigned /*Sext or ZExt*/);
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00008047
8048 // Otherwise, it must be an instruction.
8049 Instruction *I = cast<Instruction>(V);
Chris Lattnerd0622b62006-05-20 23:14:03 +00008050 Instruction *Res = 0;
Evan Cheng60e19a42009-01-15 17:01:23 +00008051 unsigned Opc = I->getOpcode();
8052 switch (Opc) {
Chris Lattnerda1d04a2007-03-03 05:27:34 +00008053 case Instruction::Add:
8054 case Instruction::Sub:
Nick Lewycky78712e52008-01-22 05:08:48 +00008055 case Instruction::Mul:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00008056 case Instruction::And:
8057 case Instruction::Or:
Chris Lattnerda1d04a2007-03-03 05:27:34 +00008058 case Instruction::Xor:
Chris Lattner960acb02006-11-29 07:18:39 +00008059 case Instruction::AShr:
8060 case Instruction::LShr:
8061 case Instruction::Shl: {
Reid Spencer74a528b2006-12-13 18:21:21 +00008062 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerda1d04a2007-03-03 05:27:34 +00008063 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Evan Cheng60e19a42009-01-15 17:01:23 +00008064 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Chris Lattner960acb02006-11-29 07:18:39 +00008065 break;
8066 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008067 case Instruction::Trunc:
8068 case Instruction::ZExt:
8069 case Instruction::SExt:
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008070 // If the source type of the cast is the type we're trying for then we can
Chris Lattnerb0418fc2007-08-02 06:11:14 +00008071 // just return the source. There's no need to insert it because it is not
8072 // new.
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00008073 if (I->getOperand(0)->getType() == Ty)
8074 return I->getOperand(0);
8075
Chris Lattnerb5ee8b32008-06-18 04:00:49 +00008076 // Otherwise, must be the same type of cast, so just reinsert a new one.
Gabor Greife1f6e4b2008-05-16 19:29:10 +00008077 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
Chris Lattnerb5ee8b32008-06-18 04:00:49 +00008078 Ty);
Chris Lattnerb0418fc2007-08-02 06:11:14 +00008079 break;
Nick Lewycky9f1a4dc2008-07-05 21:19:34 +00008080 case Instruction::Select: {
8081 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8082 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
8083 Res = SelectInst::Create(I->getOperand(0), True, False);
8084 break;
8085 }
Chris Lattnerb5ee8b32008-06-18 04:00:49 +00008086 case Instruction::PHI: {
8087 PHINode *OPN = cast<PHINode>(I);
8088 PHINode *NPN = PHINode::Create(Ty);
8089 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
8090 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
8091 NPN->addIncoming(V, OPN->getIncomingBlock(i));
8092 }
8093 Res = NPN;
8094 break;
8095 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008096 default:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00008097 // TODO: Can handle more cases here.
Torok Edwin56d06592009-07-11 20:10:48 +00008098 LLVM_UNREACHABLE("Unreachable!");
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00008099 break;
8100 }
8101
Chris Lattnerb5ee8b32008-06-18 04:00:49 +00008102 Res->takeName(I);
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00008103 return InsertNewInstBefore(Res, *I);
8104}
8105
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008106/// @brief Implement the transforms common to all CastInst visitors.
8107Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner55d4bda2003-06-23 21:59:52 +00008108 Value *Src = CI.getOperand(0);
8109
Dan Gohmanb5650eb2007-05-11 21:10:54 +00008110 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008111 // eliminate it now.
Chris Lattner86102b82005-01-01 16:22:27 +00008112 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008113 if (Instruction::CastOps opc =
8114 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
8115 // The first cast (CSrc) is eliminable so we need to fix up or replace
8116 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greife1f6e4b2008-05-16 19:29:10 +00008117 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner650b6da2002-08-02 20:00:25 +00008118 }
8119 }
Chris Lattner03841652004-05-25 04:29:21 +00008120
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008121 // If we are casting a select then fold the cast into the select
Chris Lattner86102b82005-01-01 16:22:27 +00008122 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8123 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8124 return NV;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008125
8126 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner6a4adcd2004-09-29 05:07:12 +00008127 if (isa<PHINode>(Src))
8128 if (Instruction *NV = FoldOpIntoPhi(CI))
8129 return NV;
Chris Lattnerb19a5c62006-04-12 18:09:35 +00008130
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008131 return 0;
8132}
8133
Chris Lattnerfef138b2009-01-09 05:44:56 +00008134/// FindElementAtOffset - Given a type and a constant offset, determine whether
8135/// or not there is a sequence of GEP indices into the type that will land us at
Chris Lattner72cd68f2009-01-24 01:00:13 +00008136/// the specified offset. If so, fill them into NewIndices and return the
8137/// resultant element type, otherwise return null.
8138static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset,
8139 SmallVectorImpl<Value*> &NewIndices,
Owen Andersonb5618da2009-07-03 00:17:18 +00008140 const TargetData *TD,
Owen Anderson38264b12009-07-06 23:00:19 +00008141 LLVMContext *Context) {
Chris Lattner72cd68f2009-01-24 01:00:13 +00008142 if (!Ty->isSized()) return 0;
Chris Lattnerfef138b2009-01-09 05:44:56 +00008143
8144 // Start with the index over the outer type. Note that the type size
8145 // might be zero (even if the offset isn't zero) if the indexed type
8146 // is something like [0 x {int, int}]
8147 const Type *IntPtrTy = TD->getIntPtrType();
8148 int64_t FirstIdx = 0;
Duncan Sandsaf9eaa82009-05-09 07:06:46 +00008149 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
Chris Lattnerfef138b2009-01-09 05:44:56 +00008150 FirstIdx = Offset/TySize;
Chris Lattnerbd3c7c82009-01-11 20:41:36 +00008151 Offset -= FirstIdx*TySize;
Chris Lattnerfef138b2009-01-09 05:44:56 +00008152
Chris Lattner171d2d42009-01-11 20:15:20 +00008153 // Handle hosts where % returns negative instead of values [0..TySize).
Chris Lattnerfef138b2009-01-09 05:44:56 +00008154 if (Offset < 0) {
8155 --FirstIdx;
8156 Offset += TySize;
8157 assert(Offset >= 0);
8158 }
8159 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8160 }
8161
Owen Andersonb5618da2009-07-03 00:17:18 +00008162 NewIndices.push_back(Context->getConstantInt(IntPtrTy, FirstIdx));
Chris Lattnerfef138b2009-01-09 05:44:56 +00008163
8164 // Index into the types. If we fail, set OrigBase to null.
8165 while (Offset) {
Chris Lattner171d2d42009-01-11 20:15:20 +00008166 // Indexing into tail padding between struct/array elements.
8167 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
Chris Lattner72cd68f2009-01-24 01:00:13 +00008168 return 0;
Chris Lattner171d2d42009-01-11 20:15:20 +00008169
Chris Lattnerfef138b2009-01-09 05:44:56 +00008170 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8171 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattner171d2d42009-01-11 20:15:20 +00008172 assert(Offset < (int64_t)SL->getSizeInBytes() &&
8173 "Offset must stay within the indexed type");
8174
Chris Lattnerfef138b2009-01-09 05:44:56 +00008175 unsigned Elt = SL->getElementContainingOffset(Offset);
Owen Andersonb5618da2009-07-03 00:17:18 +00008176 NewIndices.push_back(Context->getConstantInt(Type::Int32Ty, Elt));
Chris Lattnerfef138b2009-01-09 05:44:56 +00008177
8178 Offset -= SL->getElementOffset(Elt);
8179 Ty = STy->getElementType(Elt);
Chris Lattnerb1915162009-01-11 20:23:52 +00008180 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Duncan Sandsaf9eaa82009-05-09 07:06:46 +00008181 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
Chris Lattner171d2d42009-01-11 20:15:20 +00008182 assert(EltSize && "Cannot index into a zero-sized array");
Owen Andersonb5618da2009-07-03 00:17:18 +00008183 NewIndices.push_back(Context->getConstantInt(IntPtrTy,Offset/EltSize));
Chris Lattner171d2d42009-01-11 20:15:20 +00008184 Offset %= EltSize;
Chris Lattnerb1915162009-01-11 20:23:52 +00008185 Ty = AT->getElementType();
Chris Lattnerfef138b2009-01-09 05:44:56 +00008186 } else {
Chris Lattner171d2d42009-01-11 20:15:20 +00008187 // Otherwise, we can't index into the middle of this atomic type, bail.
Chris Lattner72cd68f2009-01-24 01:00:13 +00008188 return 0;
Chris Lattnerfef138b2009-01-09 05:44:56 +00008189 }
8190 }
8191
Chris Lattner72cd68f2009-01-24 01:00:13 +00008192 return Ty;
Chris Lattnerfef138b2009-01-09 05:44:56 +00008193}
8194
Chris Lattner1db224d2007-04-27 17:44:50 +00008195/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8196Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8197 Value *Src = CI.getOperand(0);
8198
Chris Lattner1db224d2007-04-27 17:44:50 +00008199 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattneracbf6a42007-04-28 00:57:34 +00008200 // If casting the result of a getelementptr instruction with no offset, turn
8201 // this into a cast of the original pointer!
Chris Lattner1db224d2007-04-27 17:44:50 +00008202 if (GEP->hasAllZeroIndices()) {
8203 // Changing the cast operand is usually not a good idea but it is safe
8204 // here because the pointer operand is being replaced with another
8205 // pointer operand so the opcode doesn't need to change.
Chris Lattneracbf6a42007-04-28 00:57:34 +00008206 AddToWorkList(GEP);
Chris Lattner1db224d2007-04-27 17:44:50 +00008207 CI.setOperand(0, GEP->getOperand(0));
8208 return &CI;
8209 }
Chris Lattneracbf6a42007-04-28 00:57:34 +00008210
8211 // If the GEP has a single use, and the base pointer is a bitcast, and the
8212 // GEP computes a constant offset, see if we can convert these three
8213 // instructions into fewer. This typically happens with unions and other
8214 // non-type-safe code.
8215 if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
8216 if (GEP->hasAllConstantIndices()) {
8217 // We are guaranteed to get a constant from EmitGEPOffset.
Owen Andersonb5618da2009-07-03 00:17:18 +00008218 ConstantInt *OffsetV =
8219 cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
Chris Lattneracbf6a42007-04-28 00:57:34 +00008220 int64_t Offset = OffsetV->getSExtValue();
8221
8222 // Get the base pointer input of the bitcast, and the type it points to.
8223 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8224 const Type *GEPIdxTy =
8225 cast<PointerType>(OrigBase->getType())->getElementType();
Chris Lattnerfef138b2009-01-09 05:44:56 +00008226 SmallVector<Value*, 8> NewIndices;
Owen Andersonb5618da2009-07-03 00:17:18 +00008227 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
Chris Lattnerfef138b2009-01-09 05:44:56 +00008228 // If we were able to index down into an element, create the GEP
8229 // and bitcast the result. This eliminates one bitcast, potentially
8230 // two.
8231 Instruction *NGEP = GetElementPtrInst::Create(OrigBase,
8232 NewIndices.begin(),
8233 NewIndices.end(), "");
8234 InsertNewInstBefore(NGEP, CI);
8235 NGEP->takeName(GEP);
Chris Lattneracbf6a42007-04-28 00:57:34 +00008236
Chris Lattnerfef138b2009-01-09 05:44:56 +00008237 if (isa<BitCastInst>(CI))
8238 return new BitCastInst(NGEP, CI.getType());
8239 assert(isa<PtrToIntInst>(CI));
8240 return new PtrToIntInst(NGEP, CI.getType());
Chris Lattneracbf6a42007-04-28 00:57:34 +00008241 }
8242 }
8243 }
Chris Lattner1db224d2007-04-27 17:44:50 +00008244 }
8245
8246 return commonCastTransforms(CI);
8247}
8248
Chris Lattnereb510d62009-04-08 05:41:03 +00008249/// isSafeIntegerType - Return true if this is a basic integer type, not a crazy
8250/// type like i42. We don't want to introduce operations on random non-legal
8251/// integer types where they don't already exist in the code. In the future,
8252/// we should consider making this based off target-data, so that 32-bit targets
8253/// won't get i64 operations etc.
8254static bool isSafeIntegerType(const Type *Ty) {
8255 switch (Ty->getPrimitiveSizeInBits()) {
8256 case 8:
8257 case 16:
8258 case 32:
8259 case 64:
8260 return true;
8261 default:
8262 return false;
8263 }
8264}
Chris Lattner1db224d2007-04-27 17:44:50 +00008265
Eli Friedmanf13aa442009-07-13 20:53:00 +00008266/// Only the TRUNC, ZEXT, SEXT. This function implements the common transforms
8267/// for all those cases.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008268/// @brief Implement the transforms common to CastInst with integer operands
8269Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8270 if (Instruction *Result = commonCastTransforms(CI))
8271 return Result;
8272
8273 Value *Src = CI.getOperand(0);
8274 const Type *SrcTy = Src->getType();
8275 const Type *DestTy = CI.getType();
Dan Gohman7ccc52f2009-06-15 22:12:54 +00008276 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8277 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008278
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008279 // See if we can simplify any instructions used by the LHS whose sole
8280 // purpose is to compute bits we don't care about.
Chris Lattner83c6a142009-01-31 08:15:18 +00008281 if (SimplifyDemandedInstructionBits(CI))
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008282 return &CI;
8283
8284 // If the source isn't an instruction or has more than one use then we
8285 // can't do anything more.
Reid Spencer266e42b2006-12-23 06:05:41 +00008286 Instruction *SrcI = dyn_cast<Instruction>(Src);
8287 if (!SrcI || !Src->hasOneUse())
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008288 return 0;
8289
Chris Lattnerda1d04a2007-03-03 05:27:34 +00008290 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008291 int NumCastsRemoved = 0;
Chris Lattnerda1d04a2007-03-03 05:27:34 +00008292 if (!isa<BitCastInst>(CI) &&
Chris Lattnereb510d62009-04-08 05:41:03 +00008293 // Only do this if the dest type is a simple type, don't convert the
8294 // expression tree to something weird like i93 unless the source is also
8295 // strange.
Dan Gohman7ccc52f2009-06-15 22:12:54 +00008296 (isSafeIntegerType(DestTy->getScalarType()) ||
8297 !isSafeIntegerType(SrcI->getType()->getScalarType())) &&
8298 CanEvaluateInDifferentType(SrcI, DestTy,
Evan Chengbeac6f82009-01-16 02:11:43 +00008299 CI.getOpcode(), NumCastsRemoved)) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008300 // If this cast is a truncate, evaluting in a different type always
Chris Lattnerb0418fc2007-08-02 06:11:14 +00008301 // eliminates the cast, so it is always a win. If this is a zero-extension,
8302 // we need to do an AND to maintain the clear top-part of the computation,
8303 // so we require that the input have eliminated at least one cast. If this
8304 // is a sign extension, we insert two new casts (to do the extension) so we
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008305 // require that two casts have been eliminated.
Evan Cheng60e19a42009-01-15 17:01:23 +00008306 bool DoXForm = false;
8307 bool JustReplace = false;
Chris Lattnerda1d04a2007-03-03 05:27:34 +00008308 switch (CI.getOpcode()) {
8309 default:
8310 // All the others use floating point so we shouldn't actually
8311 // get here because of the check above.
Torok Edwin56d06592009-07-11 20:10:48 +00008312 LLVM_UNREACHABLE("Unknown cast type");
Chris Lattnerda1d04a2007-03-03 05:27:34 +00008313 case Instruction::Trunc:
8314 DoXForm = true;
8315 break;
Evan Chengbeac6f82009-01-16 02:11:43 +00008316 case Instruction::ZExt: {
Chris Lattnerda1d04a2007-03-03 05:27:34 +00008317 DoXForm = NumCastsRemoved >= 1;
Chris Lattner9e2b9f32009-01-31 19:05:27 +00008318 if (!DoXForm && 0) {
Evan Chengbeac6f82009-01-16 02:11:43 +00008319 // If it's unnecessary to issue an AND to clear the high bits, it's
8320 // always profitable to do this xform.
Chris Lattner9e2b9f32009-01-31 19:05:27 +00008321 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
Evan Chengbeac6f82009-01-16 02:11:43 +00008322 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8323 if (MaskedValueIsZero(TryRes, Mask))
8324 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner9e2b9f32009-01-31 19:05:27 +00008325
8326 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Chengbeac6f82009-01-16 02:11:43 +00008327 if (TryI->use_empty())
8328 EraseInstFromFunction(*TryI);
8329 }
Chris Lattnerda1d04a2007-03-03 05:27:34 +00008330 break;
Evan Chengbeac6f82009-01-16 02:11:43 +00008331 }
Evan Cheng60e19a42009-01-15 17:01:23 +00008332 case Instruction::SExt: {
Chris Lattnerda1d04a2007-03-03 05:27:34 +00008333 DoXForm = NumCastsRemoved >= 2;
Chris Lattner9e2b9f32009-01-31 19:05:27 +00008334 if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
Evan Chengbeac6f82009-01-16 02:11:43 +00008335 // If we do not have to emit the truncate + sext pair, then it's always
8336 // profitable to do this xform.
Evan Cheng60e19a42009-01-15 17:01:23 +00008337 //
8338 // It's not safe to eliminate the trunc + sext pair if one of the
8339 // eliminated cast is a truncate. e.g.
8340 // t2 = trunc i32 t1 to i16
8341 // t3 = sext i16 t2 to i32
8342 // !=
8343 // i32 t1
Chris Lattner9e2b9f32009-01-31 19:05:27 +00008344 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
Evan Chengbeac6f82009-01-16 02:11:43 +00008345 unsigned NumSignBits = ComputeNumSignBits(TryRes);
8346 if (NumSignBits > (DestBitSize - SrcBitSize))
8347 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner9e2b9f32009-01-31 19:05:27 +00008348
8349 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Chengbeac6f82009-01-16 02:11:43 +00008350 if (TryI->use_empty())
8351 EraseInstFromFunction(*TryI);
Evan Cheng60e19a42009-01-15 17:01:23 +00008352 }
Chris Lattnerda1d04a2007-03-03 05:27:34 +00008353 break;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008354 }
Evan Cheng60e19a42009-01-15 17:01:23 +00008355 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008356
8357 if (DoXForm) {
Chris Lattner9e2b9f32009-01-31 19:05:27 +00008358 DOUT << "ICE: EvaluateInDifferentType converting expression type to avoid"
8359 << " cast: " << CI;
Reid Spencer74a528b2006-12-13 18:21:21 +00008360 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
8361 CI.getOpcode() == Instruction::SExt);
Evan Chengbeac6f82009-01-16 02:11:43 +00008362 if (JustReplace)
Chris Lattner9e2b9f32009-01-31 19:05:27 +00008363 // Just replace this cast with the result.
8364 return ReplaceInstUsesWith(CI, Res);
Evan Chengbeac6f82009-01-16 02:11:43 +00008365
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008366 assert(Res->getType() == DestTy);
8367 switch (CI.getOpcode()) {
Torok Edwin56d06592009-07-11 20:10:48 +00008368 default: LLVM_UNREACHABLE("Unknown cast type!");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008369 case Instruction::Trunc:
8370 case Instruction::BitCast:
8371 // Just replace this cast with the result.
8372 return ReplaceInstUsesWith(CI, Res);
8373 case Instruction::ZExt: {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008374 assert(SrcBitSize < DestBitSize && "Not a zext?");
Evan Chengbeac6f82009-01-16 02:11:43 +00008375
8376 // If the high bits are already zero, just replace this cast with the
8377 // result.
8378 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8379 if (MaskedValueIsZero(Res, Mask))
8380 return ReplaceInstUsesWith(CI, Res);
8381
8382 // We need to emit an AND to clear the high bits.
Owen Andersonb5618da2009-07-03 00:17:18 +00008383 Constant *C = Context->getConstantInt(APInt::getLowBitsSet(DestBitSize,
Chris Lattner9d5aace2007-04-02 05:48:58 +00008384 SrcBitSize));
Gabor Greife1f6e4b2008-05-16 19:29:10 +00008385 return BinaryOperator::CreateAnd(Res, C);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008386 }
Evan Chengbeac6f82009-01-16 02:11:43 +00008387 case Instruction::SExt: {
8388 // If the high bits are already filled with sign bit, just replace this
8389 // cast with the result.
8390 unsigned NumSignBits = ComputeNumSignBits(Res);
8391 if (NumSignBits > (DestBitSize - SrcBitSize))
Evan Cheng60e19a42009-01-15 17:01:23 +00008392 return ReplaceInstUsesWith(CI, Res);
8393
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008394 // We need to emit a cast to truncate, then a cast to sext.
Gabor Greife1f6e4b2008-05-16 19:29:10 +00008395 return CastInst::Create(Instruction::SExt,
Reid Spencer13bc5d72006-12-12 09:18:51 +00008396 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
8397 CI), DestTy);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008398 }
Evan Chengbeac6f82009-01-16 02:11:43 +00008399 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008400 }
8401 }
8402
8403 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8404 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8405
8406 switch (SrcI->getOpcode()) {
8407 case Instruction::Add:
8408 case Instruction::Mul:
8409 case Instruction::And:
8410 case Instruction::Or:
8411 case Instruction::Xor:
Chris Lattnera74deaf2007-04-03 17:43:25 +00008412 // If we are discarding information, rewrite.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008413 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
8414 // Don't insert two casts if they cannot be eliminated. We allow
8415 // two casts to be inserted if the sizes are the same. This could
8416 // only be converting signedness, which is a noop.
8417 if (DestBitSize == SrcBitSize ||
Reid Spencer266e42b2006-12-23 06:05:41 +00008418 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
8419 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer2a499b02006-12-13 17:19:09 +00008420 Instruction::CastOps opcode = CI.getOpcode();
Eli Friedman55e4bec2008-11-30 21:09:11 +00008421 Value *Op0c = InsertCastBefore(opcode, Op0, DestTy, *SrcI);
8422 Value *Op1c = InsertCastBefore(opcode, Op1, DestTy, *SrcI);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00008423 return BinaryOperator::Create(
Reid Spencer13bc5d72006-12-12 09:18:51 +00008424 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008425 }
8426 }
8427
8428 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
8429 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
8430 SrcI->getOpcode() == Instruction::Xor &&
Owen Andersonb5618da2009-07-03 00:17:18 +00008431 Op1 == Context->getConstantIntTrue() &&
Reid Spencer266e42b2006-12-23 06:05:41 +00008432 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Eli Friedman55e4bec2008-11-30 21:09:11 +00008433 Value *New = InsertCastBefore(Instruction::ZExt, Op0, DestTy, CI);
Owen Andersonb5618da2009-07-03 00:17:18 +00008434 return BinaryOperator::CreateXor(New,
8435 Context->getConstantInt(CI.getType(), 1));
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008436 }
8437 break;
8438 case Instruction::SDiv:
8439 case Instruction::UDiv:
8440 case Instruction::SRem:
8441 case Instruction::URem:
8442 // If we are just changing the sign, rewrite.
8443 if (DestBitSize == SrcBitSize) {
8444 // Don't insert two casts if they cannot be eliminated. We allow
8445 // two casts to be inserted if the sizes are the same. This could
8446 // only be converting signedness, which is a noop.
Reid Spencer266e42b2006-12-23 06:05:41 +00008447 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
8448 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Eli Friedman55e4bec2008-11-30 21:09:11 +00008449 Value *Op0c = InsertCastBefore(Instruction::BitCast,
8450 Op0, DestTy, *SrcI);
8451 Value *Op1c = InsertCastBefore(Instruction::BitCast,
8452 Op1, DestTy, *SrcI);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00008453 return BinaryOperator::Create(
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008454 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8455 }
8456 }
8457 break;
8458
8459 case Instruction::Shl:
8460 // Allow changing the sign of the source operand. Do not allow
8461 // changing the size of the shift, UNLESS the shift amount is a
8462 // constant. We must not change variable sized shifts to a smaller
8463 // size, because it is undefined to shift more bits out than exist
8464 // in the value.
8465 if (DestBitSize == SrcBitSize ||
8466 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00008467 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
8468 Instruction::BitCast : Instruction::Trunc);
Eli Friedman55e4bec2008-11-30 21:09:11 +00008469 Value *Op0c = InsertCastBefore(opcode, Op0, DestTy, *SrcI);
8470 Value *Op1c = InsertCastBefore(opcode, Op1, DestTy, *SrcI);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00008471 return BinaryOperator::CreateShl(Op0c, Op1c);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008472 }
8473 break;
8474 case Instruction::AShr:
8475 // If this is a signed shr, and if all bits shifted in are about to be
8476 // truncated off, turn it into an unsigned shr to allow greater
8477 // simplifications.
8478 if (DestBitSize < SrcBitSize &&
8479 isa<ConstantInt>(Op1)) {
Zhou Shengfd28a332007-03-30 17:20:39 +00008480 uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008481 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
8482 // Insert the new logical shift right.
Gabor Greife1f6e4b2008-05-16 19:29:10 +00008483 return BinaryOperator::CreateLShr(Op0, Op1);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008484 }
8485 }
8486 break;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008487 }
8488 return 0;
8489}
8490
Chris Lattner74ff60f2007-04-11 06:57:46 +00008491Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattnerd747f012006-11-29 07:04:07 +00008492 if (Instruction *Result = commonIntCastTransforms(CI))
8493 return Result;
8494
8495 Value *Src = CI.getOperand(0);
8496 const Type *Ty = CI.getType();
Dan Gohman7ccc52f2009-06-15 22:12:54 +00008497 uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8498 uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
Chris Lattnerd9eb4112009-03-24 18:15:30 +00008499
8500 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
Dan Gohman0ed77562009-06-16 19:55:29 +00008501 if (DestBitWidth == 1 &&
8502 isa<VectorType>(Ty) == isa<VectorType>(Src->getType())) {
Owen Andersonb5618da2009-07-03 00:17:18 +00008503 Constant *One = Context->getConstantInt(Src->getType(), 1);
Chris Lattnerd9eb4112009-03-24 18:15:30 +00008504 Src = InsertNewInstBefore(BinaryOperator::CreateAnd(Src, One, "tmp"), CI);
Owen Andersonb5618da2009-07-03 00:17:18 +00008505 Value *Zero = Context->getNullValue(Src->getType());
Owen Anderson1e5f00e2009-07-09 23:48:35 +00008506 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Src, Zero);
Chris Lattnerd9eb4112009-03-24 18:15:30 +00008507 }
Dan Gohman7ccc52f2009-06-15 22:12:54 +00008508
Chris Lattnerd9eb4112009-03-24 18:15:30 +00008509 // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8510 ConstantInt *ShAmtV = 0;
8511 Value *ShiftOp = 0;
8512 if (Src->hasOneUse() &&
Owen Anderson16e76742009-07-10 17:35:01 +00008513 match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)), *Context)) {
Chris Lattnerd9eb4112009-03-24 18:15:30 +00008514 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8515
8516 // Get a mask for the bits shifting in.
8517 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8518 if (MaskedValueIsZero(ShiftOp, Mask)) {
8519 if (ShAmt >= DestBitWidth) // All zeros.
Owen Andersonb5618da2009-07-03 00:17:18 +00008520 return ReplaceInstUsesWith(CI, Context->getNullValue(Ty));
Chris Lattnerd9eb4112009-03-24 18:15:30 +00008521
8522 // Okay, we can shrink this. Truncate the input, then return a new
8523 // shift.
8524 Value *V1 = InsertCastBefore(Instruction::Trunc, ShiftOp, Ty, CI);
Owen Andersonb5618da2009-07-03 00:17:18 +00008525 Value *V2 = Context->getConstantExprTrunc(ShAmtV, Ty);
Chris Lattnerd9eb4112009-03-24 18:15:30 +00008526 return BinaryOperator::CreateLShr(V1, V2);
Chris Lattnerd747f012006-11-29 07:04:07 +00008527 }
8528 }
8529
8530 return 0;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008531}
8532
Evan Chengc3cf9f82008-03-24 00:21:34 +00008533/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8534/// in order to eliminate the icmp.
8535Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8536 bool DoXform) {
8537 // If we are just checking for a icmp eq of a single bit and zext'ing it
8538 // to an integer, then shift the bit to the appropriate place and then
8539 // cast to integer to avoid the comparison.
8540 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8541 const APInt &Op1CV = Op1C->getValue();
8542
8543 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
8544 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
8545 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8546 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8547 if (!DoXform) return ICI;
8548
8549 Value *In = ICI->getOperand(0);
Owen Andersonb5618da2009-07-03 00:17:18 +00008550 Value *Sh = Context->getConstantInt(In->getType(),
Dan Gohman7ccc52f2009-06-15 22:12:54 +00008551 In->getType()->getScalarSizeInBits()-1);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00008552 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
Evan Chengc3cf9f82008-03-24 00:21:34 +00008553 In->getName()+".lobit"),
8554 CI);
8555 if (In->getType() != CI.getType())
Gabor Greife1f6e4b2008-05-16 19:29:10 +00008556 In = CastInst::CreateIntegerCast(In, CI.getType(),
Evan Chengc3cf9f82008-03-24 00:21:34 +00008557 false/*ZExt*/, "tmp", &CI);
8558
8559 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
Owen Andersonb5618da2009-07-03 00:17:18 +00008560 Constant *One = Context->getConstantInt(In->getType(), 1);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00008561 In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
Evan Chengc3cf9f82008-03-24 00:21:34 +00008562 In->getName()+".not"),
8563 CI);
8564 }
8565
8566 return ReplaceInstUsesWith(CI, In);
8567 }
8568
8569
8570
8571 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
8572 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8573 // zext (X == 1) to i32 --> X iff X has only the low bit set.
8574 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
8575 // zext (X != 0) to i32 --> X iff X has only the low bit set.
8576 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
8577 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
8578 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8579 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
8580 // This only works for EQ and NE
8581 ICI->isEquality()) {
8582 // If Op1C some other power of two, convert:
8583 uint32_t BitWidth = Op1C->getType()->getBitWidth();
8584 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8585 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8586 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8587
8588 APInt KnownZeroMask(~KnownZero);
8589 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8590 if (!DoXform) return ICI;
8591
8592 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8593 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8594 // (X&4) == 2 --> false
8595 // (X&4) != 2 --> true
Owen Andersonb5618da2009-07-03 00:17:18 +00008596 Constant *Res = Context->getConstantInt(Type::Int1Ty, isNE);
8597 Res = Context->getConstantExprZExt(Res, CI.getType());
Evan Chengc3cf9f82008-03-24 00:21:34 +00008598 return ReplaceInstUsesWith(CI, Res);
8599 }
8600
8601 uint32_t ShiftAmt = KnownZeroMask.logBase2();
8602 Value *In = ICI->getOperand(0);
8603 if (ShiftAmt) {
8604 // Perform a logical shr by shiftamt.
8605 // Insert the shift to put the result in the low bit.
Gabor Greife1f6e4b2008-05-16 19:29:10 +00008606 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
Owen Andersonb5618da2009-07-03 00:17:18 +00008607 Context->getConstantInt(In->getType(), ShiftAmt),
Evan Chengc3cf9f82008-03-24 00:21:34 +00008608 In->getName()+".lobit"), CI);
8609 }
8610
8611 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
Owen Andersonb5618da2009-07-03 00:17:18 +00008612 Constant *One = Context->getConstantInt(In->getType(), 1);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00008613 In = BinaryOperator::CreateXor(In, One, "tmp");
Evan Chengc3cf9f82008-03-24 00:21:34 +00008614 InsertNewInstBefore(cast<Instruction>(In), CI);
8615 }
8616
8617 if (CI.getType() == In->getType())
8618 return ReplaceInstUsesWith(CI, In);
8619 else
Gabor Greife1f6e4b2008-05-16 19:29:10 +00008620 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chengc3cf9f82008-03-24 00:21:34 +00008621 }
8622 }
8623 }
8624
8625 return 0;
8626}
8627
Chris Lattner74ff60f2007-04-11 06:57:46 +00008628Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008629 // If one of the common conversion will work ..
8630 if (Instruction *Result = commonIntCastTransforms(CI))
8631 return Result;
8632
8633 Value *Src = CI.getOperand(0);
8634
Chris Lattner24f31a02009-02-17 20:47:23 +00008635 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8636 // types and if the sizes are just right we can convert this into a logical
8637 // 'and' which will be much cheaper than the pair of casts.
8638 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
8639 // Get the sizes of the types involved. We know that the intermediate type
8640 // will be smaller than A or C, but don't know the relation between A and C.
8641 Value *A = CSrc->getOperand(0);
Dan Gohman7ccc52f2009-06-15 22:12:54 +00008642 unsigned SrcSize = A->getType()->getScalarSizeInBits();
8643 unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8644 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattner24f31a02009-02-17 20:47:23 +00008645 // If we're actually extending zero bits, then if
8646 // SrcSize < DstSize: zext(a & mask)
8647 // SrcSize == DstSize: a & mask
8648 // SrcSize > DstSize: trunc(a) & mask
8649 if (SrcSize < DstSize) {
8650 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersonb5618da2009-07-03 00:17:18 +00008651 Constant *AndConst = Context->getConstantInt(A->getType(), AndValue);
Chris Lattner24f31a02009-02-17 20:47:23 +00008652 Instruction *And =
8653 BinaryOperator::CreateAnd(A, AndConst, CSrc->getName()+".mask");
8654 InsertNewInstBefore(And, CI);
8655 return new ZExtInst(And, CI.getType());
8656 } else if (SrcSize == DstSize) {
8657 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersonb5618da2009-07-03 00:17:18 +00008658 return BinaryOperator::CreateAnd(A, Context->getConstantInt(A->getType(),
Dan Gohman7ccc52f2009-06-15 22:12:54 +00008659 AndValue));
Chris Lattner24f31a02009-02-17 20:47:23 +00008660 } else if (SrcSize > DstSize) {
8661 Instruction *Trunc = new TruncInst(A, CI.getType(), "tmp");
8662 InsertNewInstBefore(Trunc, CI);
8663 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
Owen Andersonb5618da2009-07-03 00:17:18 +00008664 return BinaryOperator::CreateAnd(Trunc,
8665 Context->getConstantInt(Trunc->getType(),
Dan Gohman7ccc52f2009-06-15 22:12:54 +00008666 AndValue));
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008667 }
8668 }
8669
Evan Chengc3cf9f82008-03-24 00:21:34 +00008670 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8671 return transformZExtICmp(ICI, CI);
Chris Lattnerd0f79422007-04-11 06:53:04 +00008672
Evan Chengc3cf9f82008-03-24 00:21:34 +00008673 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8674 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8675 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8676 // of the (zext icmp) will be transformed.
8677 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8678 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8679 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8680 (transformZExtICmp(LHS, CI, false) ||
8681 transformZExtICmp(RHS, CI, false))) {
8682 Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8683 Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00008684 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Chris Lattner7ddbff02007-04-11 05:45:39 +00008685 }
Evan Chengc3cf9f82008-03-24 00:21:34 +00008686 }
8687
Dan Gohman56bd02c2009-06-18 16:30:21 +00008688 // zext(trunc(t) & C) -> (t & zext(C)).
Dan Gohman7f836c7c2009-06-17 23:17:05 +00008689 if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8690 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8691 if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8692 Value *TI0 = TI->getOperand(0);
Dan Gohman56bd02c2009-06-18 16:30:21 +00008693 if (TI0->getType() == CI.getType())
8694 return
8695 BinaryOperator::CreateAnd(TI0,
Owen Andersonb5618da2009-07-03 00:17:18 +00008696 Context->getConstantExprZExt(C, CI.getType()));
Dan Gohman7f836c7c2009-06-17 23:17:05 +00008697 }
8698
Dan Gohman56bd02c2009-06-18 16:30:21 +00008699 // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8700 if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8701 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8702 if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8703 if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8704 And->getOperand(1) == C)
8705 if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8706 Value *TI0 = TI->getOperand(0);
8707 if (TI0->getType() == CI.getType()) {
Owen Andersonb5618da2009-07-03 00:17:18 +00008708 Constant *ZC = Context->getConstantExprZExt(C, CI.getType());
Dan Gohman56bd02c2009-06-18 16:30:21 +00008709 Instruction *NewAnd = BinaryOperator::CreateAnd(TI0, ZC, "tmp");
8710 InsertNewInstBefore(NewAnd, *And);
8711 return BinaryOperator::CreateXor(NewAnd, ZC);
8712 }
8713 }
8714
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008715 return 0;
8716}
8717
Chris Lattner74ff60f2007-04-11 06:57:46 +00008718Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattner20f23722007-04-11 06:12:58 +00008719 if (Instruction *I = commonIntCastTransforms(CI))
8720 return I;
8721
Chris Lattner74ff60f2007-04-11 06:57:46 +00008722 Value *Src = CI.getOperand(0);
8723
Dan Gohman13cbcf1c182008-10-30 20:40:10 +00008724 // Canonicalize sign-extend from i1 to a select.
8725 if (Src->getType() == Type::Int1Ty)
8726 return SelectInst::Create(Src,
Owen Anderson542619e2009-07-13 20:58:05 +00008727 Context->getAllOnesValue(CI.getType()),
Owen Andersonb5618da2009-07-03 00:17:18 +00008728 Context->getNullValue(CI.getType()));
Dan Gohman81ab7532008-05-20 21:01:12 +00008729
8730 // See if the value being truncated is already sign extended. If so, just
8731 // eliminate the trunc/sext pair.
8732 if (getOpcode(Src) == Instruction::Trunc) {
8733 Value *Op = cast<User>(Src)->getOperand(0);
Dan Gohman7ccc52f2009-06-15 22:12:54 +00008734 unsigned OpBits = Op->getType()->getScalarSizeInBits();
8735 unsigned MidBits = Src->getType()->getScalarSizeInBits();
8736 unsigned DestBits = CI.getType()->getScalarSizeInBits();
Dan Gohman81ab7532008-05-20 21:01:12 +00008737 unsigned NumSignBits = ComputeNumSignBits(Op);
8738
8739 if (OpBits == DestBits) {
8740 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
8741 // bits, it is already ready.
8742 if (NumSignBits > DestBits-MidBits)
8743 return ReplaceInstUsesWith(CI, Op);
8744 } else if (OpBits < DestBits) {
8745 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
8746 // bits, just sext from i32.
8747 if (NumSignBits > OpBits-MidBits)
8748 return new SExtInst(Op, CI.getType(), "tmp");
8749 } else {
8750 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
8751 // bits, just truncate to i32.
8752 if (NumSignBits > OpBits-MidBits)
8753 return new TruncInst(Op, CI.getType(), "tmp");
8754 }
8755 }
Chris Lattnerf5b353c2008-08-06 07:35:52 +00008756
8757 // If the input is a shl/ashr pair of a same constant, then this is a sign
8758 // extension from a smaller value. If we could trust arbitrary bitwidth
8759 // integers, we could turn this into a truncate to the smaller bit and then
8760 // use a sext for the whole extension. Since we don't, look deeper and check
8761 // for a truncate. If the source and dest are the same type, eliminate the
8762 // trunc and extend and just do shifts. For example, turn:
8763 // %a = trunc i32 %i to i8
8764 // %b = shl i8 %a, 6
8765 // %c = ashr i8 %b, 6
8766 // %d = sext i8 %c to i32
8767 // into:
8768 // %a = shl i32 %i, 30
8769 // %d = ashr i32 %a, 30
8770 Value *A = 0;
8771 ConstantInt *BA = 0, *CA = 0;
8772 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
Owen Anderson16e76742009-07-10 17:35:01 +00008773 m_ConstantInt(CA)), *Context) &&
Chris Lattnerf5b353c2008-08-06 07:35:52 +00008774 BA == CA && isa<TruncInst>(A)) {
8775 Value *I = cast<TruncInst>(A)->getOperand(0);
8776 if (I->getType() == CI.getType()) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00008777 unsigned MidSize = Src->getType()->getScalarSizeInBits();
8778 unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnerf5b353c2008-08-06 07:35:52 +00008779 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
Owen Andersonb5618da2009-07-03 00:17:18 +00008780 Constant *ShAmtV = Context->getConstantInt(CI.getType(), ShAmt);
Chris Lattnerf5b353c2008-08-06 07:35:52 +00008781 I = InsertNewInstBefore(BinaryOperator::CreateShl(I, ShAmtV,
8782 CI.getName()), CI);
8783 return BinaryOperator::CreateAShr(I, ShAmtV);
8784 }
8785 }
8786
Chris Lattner20f23722007-04-11 06:12:58 +00008787 return 0;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008788}
8789
Chris Lattnerfa1e7ee2008-01-27 05:29:54 +00008790/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8791/// in the specified FP type without changing its value.
Owen Andersonb5618da2009-07-03 00:17:18 +00008792static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
Owen Anderson38264b12009-07-06 23:00:19 +00008793 LLVMContext *Context) {
Dale Johannesen4f0bd682008-10-09 23:00:39 +00008794 bool losesInfo;
Chris Lattnerfa1e7ee2008-01-27 05:29:54 +00008795 APFloat F = CFP->getValueAPF();
Dale Johannesen4f0bd682008-10-09 23:00:39 +00008796 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8797 if (!losesInfo)
Owen Andersonb5618da2009-07-03 00:17:18 +00008798 return Context->getConstantFP(F);
Chris Lattnerfa1e7ee2008-01-27 05:29:54 +00008799 return 0;
8800}
8801
8802/// LookThroughFPExtensions - If this is an fp extension instruction, look
8803/// through it until we get the source value.
Owen Anderson38264b12009-07-06 23:00:19 +00008804static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
Chris Lattnerfa1e7ee2008-01-27 05:29:54 +00008805 if (Instruction *I = dyn_cast<Instruction>(V))
8806 if (I->getOpcode() == Instruction::FPExt)
Owen Andersonb5618da2009-07-03 00:17:18 +00008807 return LookThroughFPExtensions(I->getOperand(0), Context);
Chris Lattnerfa1e7ee2008-01-27 05:29:54 +00008808
8809 // If this value is a constant, return the constant in the smallest FP type
8810 // that can accurately represent it. This allows us to turn
8811 // (float)((double)X+2.0) into x+2.0f.
8812 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8813 if (CFP->getType() == Type::PPC_FP128Ty)
8814 return V; // No constant folding of this.
8815 // See if the value can be truncated to float and then reextended.
Owen Andersonb5618da2009-07-03 00:17:18 +00008816 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
Chris Lattnerfa1e7ee2008-01-27 05:29:54 +00008817 return V;
8818 if (CFP->getType() == Type::DoubleTy)
8819 return V; // Won't shrink.
Owen Andersonb5618da2009-07-03 00:17:18 +00008820 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
Chris Lattnerfa1e7ee2008-01-27 05:29:54 +00008821 return V;
8822 // Don't try to shrink to various long double types.
8823 }
8824
8825 return V;
8826}
8827
8828Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8829 if (Instruction *I = commonCastTransforms(CI))
8830 return I;
8831
Dan Gohmana5b96452009-06-04 22:49:04 +00008832 // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
Chris Lattnerfa1e7ee2008-01-27 05:29:54 +00008833 // smaller than the destination type, we can eliminate the truncate by doing
Dan Gohmana5b96452009-06-04 22:49:04 +00008834 // the add as the smaller type. This applies to fadd/fsub/fmul/fdiv as well as
Chris Lattnerfa1e7ee2008-01-27 05:29:54 +00008835 // many builtins (sqrt, etc).
8836 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8837 if (OpI && OpI->hasOneUse()) {
8838 switch (OpI->getOpcode()) {
8839 default: break;
Dan Gohmana5b96452009-06-04 22:49:04 +00008840 case Instruction::FAdd:
8841 case Instruction::FSub:
8842 case Instruction::FMul:
Chris Lattnerfa1e7ee2008-01-27 05:29:54 +00008843 case Instruction::FDiv:
8844 case Instruction::FRem:
8845 const Type *SrcTy = OpI->getType();
Owen Andersonb5618da2009-07-03 00:17:18 +00008846 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
8847 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
Chris Lattnerfa1e7ee2008-01-27 05:29:54 +00008848 if (LHSTrunc->getType() != SrcTy &&
8849 RHSTrunc->getType() != SrcTy) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00008850 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnerfa1e7ee2008-01-27 05:29:54 +00008851 // If the source types were both smaller than the destination type of
8852 // the cast, do this xform.
Dan Gohman7ccc52f2009-06-15 22:12:54 +00008853 if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8854 RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
Chris Lattnerfa1e7ee2008-01-27 05:29:54 +00008855 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8856 CI.getType(), CI);
8857 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8858 CI.getType(), CI);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00008859 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerfa1e7ee2008-01-27 05:29:54 +00008860 }
8861 }
8862 break;
8863 }
8864 }
8865 return 0;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008866}
8867
8868Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8869 return commonCastTransforms(CI);
8870}
8871
Chris Lattnere35fe0f2008-05-19 20:25:04 +00008872Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
Chris Lattner7bdaecb2008-08-06 05:13:06 +00008873 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8874 if (OpI == 0)
8875 return commonCastTransforms(FI);
8876
8877 // fptoui(uitofp(X)) --> X
8878 // fptoui(sitofp(X)) --> X
8879 // This is safe if the intermediate type has enough bits in its mantissa to
8880 // accurately represent all values of X. For example, do not do this with
8881 // i64->float->i64. This is also safe for sitofp case, because any negative
8882 // 'X' value would cause an undefined result for the fptoui.
8883 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8884 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman7ccc52f2009-06-15 22:12:54 +00008885 (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
Chris Lattner7bdaecb2008-08-06 05:13:06 +00008886 OpI->getType()->getFPMantissaWidth())
8887 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattnere35fe0f2008-05-19 20:25:04 +00008888
8889 return commonCastTransforms(FI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008890}
8891
Chris Lattnere35fe0f2008-05-19 20:25:04 +00008892Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
Chris Lattner7bdaecb2008-08-06 05:13:06 +00008893 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8894 if (OpI == 0)
8895 return commonCastTransforms(FI);
8896
8897 // fptosi(sitofp(X)) --> X
8898 // fptosi(uitofp(X)) --> X
8899 // This is safe if the intermediate type has enough bits in its mantissa to
8900 // accurately represent all values of X. For example, do not do this with
8901 // i64->float->i64. This is also safe for sitofp case, because any negative
8902 // 'X' value would cause an undefined result for the fptoui.
8903 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8904 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman7ccc52f2009-06-15 22:12:54 +00008905 (int)FI.getType()->getScalarSizeInBits() <=
Chris Lattner7bdaecb2008-08-06 05:13:06 +00008906 OpI->getType()->getFPMantissaWidth())
8907 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattnere35fe0f2008-05-19 20:25:04 +00008908
8909 return commonCastTransforms(FI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008910}
8911
8912Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8913 return commonCastTransforms(CI);
8914}
8915
8916Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8917 return commonCastTransforms(CI);
8918}
8919
Chris Lattner306813c2009-03-24 18:35:40 +00008920Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8921 // If the destination integer type is smaller than the intptr_t type for
8922 // this target, do a ptrtoint to intptr_t then do a trunc. This allows the
8923 // trunc to be exposed to other transforms. Don't do this for extending
8924 // ptrtoint's, because we don't know if the target sign or zero extends its
8925 // pointers.
Dan Gohman7ccc52f2009-06-15 22:12:54 +00008926 if (CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
Chris Lattner306813c2009-03-24 18:35:40 +00008927 Value *P = InsertNewInstBefore(new PtrToIntInst(CI.getOperand(0),
8928 TD->getIntPtrType(),
8929 "tmp"), CI);
8930 return new TruncInst(P, CI.getType());
8931 }
8932
Chris Lattner1db224d2007-04-27 17:44:50 +00008933 return commonPointerCastTransforms(CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008934}
8935
Chris Lattner2940c5c2008-01-08 07:23:51 +00008936Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
Chris Lattner306813c2009-03-24 18:35:40 +00008937 // If the source integer type is larger than the intptr_t type for
8938 // this target, do a trunc to the intptr_t type, then inttoptr of it. This
8939 // allows the trunc to be exposed to other transforms. Don't do this for
8940 // extending inttoptr's, because we don't know if the target sign or zero
8941 // extends to pointers.
Dan Gohman7ccc52f2009-06-15 22:12:54 +00008942 if (CI.getOperand(0)->getType()->getScalarSizeInBits() >
Chris Lattner306813c2009-03-24 18:35:40 +00008943 TD->getPointerSizeInBits()) {
8944 Value *P = InsertNewInstBefore(new TruncInst(CI.getOperand(0),
8945 TD->getIntPtrType(),
8946 "tmp"), CI);
8947 return new IntToPtrInst(P, CI.getType());
8948 }
8949
Chris Lattner2940c5c2008-01-08 07:23:51 +00008950 if (Instruction *I = commonCastTransforms(CI))
8951 return I;
8952
8953 const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
8954 if (!DestPointee->isSized()) return 0;
8955
8956 // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
8957 ConstantInt *Cst;
8958 Value *X;
8959 if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
Owen Anderson16e76742009-07-10 17:35:01 +00008960 m_ConstantInt(Cst)), *Context)) {
Chris Lattner2940c5c2008-01-08 07:23:51 +00008961 // If the source and destination operands have the same type, see if this
8962 // is a single-index GEP.
8963 if (X->getType() == CI.getType()) {
8964 // Get the size of the pointee type.
Duncan Sandsaf9eaa82009-05-09 07:06:46 +00008965 uint64_t Size = TD->getTypeAllocSize(DestPointee);
Chris Lattner2940c5c2008-01-08 07:23:51 +00008966
8967 // Convert the constant to intptr type.
8968 APInt Offset = Cst->getValue();
8969 Offset.sextOrTrunc(TD->getPointerSizeInBits());
8970
8971 // If Offset is evenly divisible by Size, we can do this xform.
8972 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8973 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
Owen Andersonb5618da2009-07-03 00:17:18 +00008974 return GetElementPtrInst::Create(X, Context->getConstantInt(Offset));
Chris Lattner2940c5c2008-01-08 07:23:51 +00008975 }
8976 }
8977 // TODO: Could handle other cases, e.g. where add is indexing into field of
8978 // struct etc.
8979 } else if (CI.getOperand(0)->hasOneUse() &&
Owen Anderson16e76742009-07-10 17:35:01 +00008980 match(CI.getOperand(0), m_Add(m_Value(X),
8981 m_ConstantInt(Cst)), *Context)) {
Chris Lattner2940c5c2008-01-08 07:23:51 +00008982 // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
8983 // "inttoptr+GEP" instead of "add+intptr".
8984
8985 // Get the size of the pointee type.
Duncan Sandsaf9eaa82009-05-09 07:06:46 +00008986 uint64_t Size = TD->getTypeAllocSize(DestPointee);
Chris Lattner2940c5c2008-01-08 07:23:51 +00008987
8988 // Convert the constant to intptr type.
8989 APInt Offset = Cst->getValue();
8990 Offset.sextOrTrunc(TD->getPointerSizeInBits());
8991
8992 // If Offset is evenly divisible by Size, we can do this xform.
8993 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8994 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8995
8996 Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
8997 "tmp"), CI);
Owen Andersonb5618da2009-07-03 00:17:18 +00008998 return GetElementPtrInst::Create(P,
8999 Context->getConstantInt(Offset), "tmp");
Chris Lattner2940c5c2008-01-08 07:23:51 +00009000 }
9001 }
9002 return 0;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00009003}
9004
Chris Lattner1db224d2007-04-27 17:44:50 +00009005Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00009006 // If the operands are integer typed then apply the integer transforms,
9007 // otherwise just apply the common ones.
9008 Value *Src = CI.getOperand(0);
9009 const Type *SrcTy = Src->getType();
9010 const Type *DestTy = CI.getType();
9011
Eli Friedmanf13aa442009-07-13 20:53:00 +00009012 if (isa<PointerType>(SrcTy)) {
Chris Lattner1db224d2007-04-27 17:44:50 +00009013 if (Instruction *I = commonPointerCastTransforms(CI))
9014 return I;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00009015 } else {
9016 if (Instruction *Result = commonCastTransforms(CI))
9017 return Result;
9018 }
9019
9020
9021 // Get rid of casts from one type to the same type. These are useless and can
9022 // be replaced by the operand.
9023 if (DestTy == Src->getType())
9024 return ReplaceInstUsesWith(CI, Src);
9025
Reid Spencer6c38f0b2006-11-27 01:05:10 +00009026 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattner1db224d2007-04-27 17:44:50 +00009027 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
9028 const Type *DstElTy = DstPTy->getElementType();
9029 const Type *SrcElTy = SrcPTy->getElementType();
9030
Nate Begemanf2b0b0e2008-03-31 00:22:16 +00009031 // If the address spaces don't match, don't eliminate the bitcast, which is
9032 // required for changing types.
9033 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
9034 return 0;
9035
Chris Lattner1db224d2007-04-27 17:44:50 +00009036 // If we are casting a malloc or alloca to a pointer to a type of the same
9037 // size, rewrite the allocation instruction to allocate the "right" type.
9038 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
9039 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
9040 return V;
9041
Chris Lattner361e9812007-05-05 22:32:24 +00009042 // If the source and destination are pointers, and this cast is equivalent
9043 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
Chris Lattner1db224d2007-04-27 17:44:50 +00009044 // This can enhance SROA and other transforms that want type-safe pointers.
Owen Andersonb5618da2009-07-03 00:17:18 +00009045 Constant *ZeroUInt = Context->getNullValue(Type::Int32Ty);
Chris Lattner1db224d2007-04-27 17:44:50 +00009046 unsigned NumZeros = 0;
9047 while (SrcElTy != DstElTy &&
9048 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
9049 SrcElTy->getNumContainedTypes() /* not "{}" */) {
9050 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
9051 ++NumZeros;
9052 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00009053
Chris Lattner1db224d2007-04-27 17:44:50 +00009054 // If we found a path from the src to dest, create the getelementptr now.
9055 if (SrcElTy == DstElTy) {
9056 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Gabor Greife9ecc682008-04-06 20:25:17 +00009057 return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "",
9058 ((Instruction*) NULL));
Chris Lattnerb19a5c62006-04-12 18:09:35 +00009059 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00009060 }
Chris Lattnerdfae8be2003-07-24 17:35:25 +00009061
Reid Spencer6c38f0b2006-11-27 01:05:10 +00009062 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
9063 if (SVI->hasOneUse()) {
9064 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
9065 // a bitconvert to a vector with the same # elts.
Reid Spencerd84d35b2007-02-15 02:26:10 +00009066 if (isa<VectorType>(DestTy) &&
Mon P Wang25f01062008-11-10 04:46:22 +00009067 cast<VectorType>(DestTy)->getNumElements() ==
9068 SVI->getType()->getNumElements() &&
9069 SVI->getType()->getNumElements() ==
9070 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00009071 CastInst *Tmp;
9072 // If either of the operands is a cast from CI.getType(), then
9073 // evaluating the shuffle in the casted destination's type will allow
9074 // us to eliminate at least one cast.
9075 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
9076 Tmp->getOperand(0)->getType() == DestTy) ||
9077 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
9078 Tmp->getOperand(0)->getType() == DestTy)) {
Eli Friedman55e4bec2008-11-30 21:09:11 +00009079 Value *LHS = InsertCastBefore(Instruction::BitCast,
9080 SVI->getOperand(0), DestTy, CI);
9081 Value *RHS = InsertCastBefore(Instruction::BitCast,
9082 SVI->getOperand(1), DestTy, CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00009083 // Return a new shuffle vector. Use the same element ID's, as we
9084 // know the vector types match #elts.
9085 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner99155be2006-05-25 23:24:33 +00009086 }
9087 }
9088 }
9089 }
Chris Lattner260ab202002-04-18 17:39:14 +00009090 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +00009091}
9092
Chris Lattner56e4d3d2004-04-09 23:46:01 +00009093/// GetSelectFoldableOperands - We want to turn code that looks like this:
9094/// %C = or %A, %B
9095/// %D = select %cond, %C, %A
9096/// into:
9097/// %C = select %cond, %B, 0
9098/// %D = or %A, %C
9099///
9100/// Assuming that the specified instruction is an operand to the select, return
9101/// a bitmask indicating which operands of this instruction are foldable if they
9102/// equal the other incoming value of the select.
9103///
9104static unsigned GetSelectFoldableOperands(Instruction *I) {
9105 switch (I->getOpcode()) {
9106 case Instruction::Add:
9107 case Instruction::Mul:
9108 case Instruction::And:
9109 case Instruction::Or:
9110 case Instruction::Xor:
9111 return 3; // Can fold through either operand.
9112 case Instruction::Sub: // Can only fold on the amount subtracted.
9113 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencerfdff9382006-11-08 06:47:33 +00009114 case Instruction::LShr:
9115 case Instruction::AShr:
Misha Brukmanb1c93172005-04-21 23:48:37 +00009116 return 1;
Chris Lattner56e4d3d2004-04-09 23:46:01 +00009117 default:
9118 return 0; // Cannot fold
9119 }
9120}
9121
9122/// GetSelectFoldableConstant - For the same transformation as the previous
9123/// function, return the identity constant that goes into the select.
Owen Andersonb5618da2009-07-03 00:17:18 +00009124static Constant *GetSelectFoldableConstant(Instruction *I,
Owen Anderson38264b12009-07-06 23:00:19 +00009125 LLVMContext *Context) {
Chris Lattner56e4d3d2004-04-09 23:46:01 +00009126 switch (I->getOpcode()) {
Torok Edwinccb29cd2009-07-11 13:10:19 +00009127 default: LLVM_UNREACHABLE("This cannot happen!");
Chris Lattner56e4d3d2004-04-09 23:46:01 +00009128 case Instruction::Add:
9129 case Instruction::Sub:
9130 case Instruction::Or:
9131 case Instruction::Xor:
Chris Lattner56e4d3d2004-04-09 23:46:01 +00009132 case Instruction::Shl:
Reid Spencerfdff9382006-11-08 06:47:33 +00009133 case Instruction::LShr:
9134 case Instruction::AShr:
Owen Andersonb5618da2009-07-03 00:17:18 +00009135 return Context->getNullValue(I->getType());
Chris Lattner56e4d3d2004-04-09 23:46:01 +00009136 case Instruction::And:
Owen Andersonb5618da2009-07-03 00:17:18 +00009137 return Context->getAllOnesValue(I->getType());
Chris Lattner56e4d3d2004-04-09 23:46:01 +00009138 case Instruction::Mul:
Owen Andersonb5618da2009-07-03 00:17:18 +00009139 return Context->getConstantInt(I->getType(), 1);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00009140 }
9141}
9142
Chris Lattner411336f2005-01-19 21:50:18 +00009143/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
9144/// have the same opcode and only one use each. Try to simplify this.
9145Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
9146 Instruction *FI) {
9147 if (TI->getNumOperands() == 1) {
9148 // If this is a non-volatile load or a cast from the same type,
9149 // merge.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00009150 if (TI->isCast()) {
Chris Lattner411336f2005-01-19 21:50:18 +00009151 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
9152 return 0;
9153 } else {
9154 return 0; // unknown unary op.
9155 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00009156
Chris Lattner411336f2005-01-19 21:50:18 +00009157 // Fold this by inserting a select from the input values.
Gabor Greife9ecc682008-04-06 20:25:17 +00009158 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
9159 FI->getOperand(0), SI.getName()+".v");
Chris Lattner411336f2005-01-19 21:50:18 +00009160 InsertNewInstBefore(NewSI, SI);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00009161 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Reid Spencer6c38f0b2006-11-27 01:05:10 +00009162 TI->getType());
Chris Lattner411336f2005-01-19 21:50:18 +00009163 }
9164
Reid Spencer2341c222007-02-02 02:16:23 +00009165 // Only handle binary operators here.
9166 if (!isa<BinaryOperator>(TI))
Chris Lattner411336f2005-01-19 21:50:18 +00009167 return 0;
9168
9169 // Figure out if the operations have any operands in common.
9170 Value *MatchOp, *OtherOpT, *OtherOpF;
9171 bool MatchIsOpZero;
9172 if (TI->getOperand(0) == FI->getOperand(0)) {
9173 MatchOp = TI->getOperand(0);
9174 OtherOpT = TI->getOperand(1);
9175 OtherOpF = FI->getOperand(1);
9176 MatchIsOpZero = true;
9177 } else if (TI->getOperand(1) == FI->getOperand(1)) {
9178 MatchOp = TI->getOperand(1);
9179 OtherOpT = TI->getOperand(0);
9180 OtherOpF = FI->getOperand(0);
9181 MatchIsOpZero = false;
9182 } else if (!TI->isCommutative()) {
9183 return 0;
9184 } else if (TI->getOperand(0) == FI->getOperand(1)) {
9185 MatchOp = TI->getOperand(0);
9186 OtherOpT = TI->getOperand(1);
9187 OtherOpF = FI->getOperand(0);
9188 MatchIsOpZero = true;
9189 } else if (TI->getOperand(1) == FI->getOperand(0)) {
9190 MatchOp = TI->getOperand(1);
9191 OtherOpT = TI->getOperand(0);
9192 OtherOpF = FI->getOperand(1);
9193 MatchIsOpZero = true;
9194 } else {
9195 return 0;
9196 }
9197
9198 // If we reach here, they do have operations in common.
Gabor Greife9ecc682008-04-06 20:25:17 +00009199 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9200 OtherOpF, SI.getName()+".v");
Chris Lattner411336f2005-01-19 21:50:18 +00009201 InsertNewInstBefore(NewSI, SI);
9202
9203 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9204 if (MatchIsOpZero)
Gabor Greife1f6e4b2008-05-16 19:29:10 +00009205 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Chris Lattner411336f2005-01-19 21:50:18 +00009206 else
Gabor Greife1f6e4b2008-05-16 19:29:10 +00009207 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner411336f2005-01-19 21:50:18 +00009208 }
Torok Edwin56d06592009-07-11 20:10:48 +00009209 LLVM_UNREACHABLE("Shouldn't get here");
Reid Spencer2f34b982007-02-02 14:41:37 +00009210 return 0;
Chris Lattner411336f2005-01-19 21:50:18 +00009211}
9212
Evan Cheng826b6f02009-03-31 20:42:45 +00009213static bool isSelect01(Constant *C1, Constant *C2) {
9214 ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9215 if (!C1I)
9216 return false;
9217 ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9218 if (!C2I)
9219 return false;
9220 return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9221}
9222
9223/// FoldSelectIntoOp - Try fold the select into one of the operands to
9224/// facilitate further optimization.
9225Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9226 Value *FalseVal) {
9227 // See the comment above GetSelectFoldableOperands for a description of the
9228 // transformation we are doing here.
9229 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9230 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9231 !isa<Constant>(FalseVal)) {
9232 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9233 unsigned OpToFold = 0;
9234 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9235 OpToFold = 1;
9236 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9237 OpToFold = 2;
9238 }
9239
9240 if (OpToFold) {
Owen Andersonb5618da2009-07-03 00:17:18 +00009241 Constant *C = GetSelectFoldableConstant(TVI, Context);
Evan Cheng826b6f02009-03-31 20:42:45 +00009242 Value *OOp = TVI->getOperand(2-OpToFold);
9243 // Avoid creating select between 2 constants unless it's selecting
9244 // between 0 and 1.
9245 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9246 Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9247 InsertNewInstBefore(NewSel, SI);
9248 NewSel->takeName(TVI);
9249 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9250 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
Torok Edwin56d06592009-07-11 20:10:48 +00009251 LLVM_UNREACHABLE("Unknown instruction!!");
Evan Cheng826b6f02009-03-31 20:42:45 +00009252 }
9253 }
9254 }
9255 }
9256 }
9257
9258 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9259 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9260 !isa<Constant>(TrueVal)) {
9261 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9262 unsigned OpToFold = 0;
9263 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9264 OpToFold = 1;
9265 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9266 OpToFold = 2;
9267 }
9268
9269 if (OpToFold) {
Owen Andersonb5618da2009-07-03 00:17:18 +00009270 Constant *C = GetSelectFoldableConstant(FVI, Context);
Evan Cheng826b6f02009-03-31 20:42:45 +00009271 Value *OOp = FVI->getOperand(2-OpToFold);
9272 // Avoid creating select between 2 constants unless it's selecting
9273 // between 0 and 1.
9274 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9275 Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9276 InsertNewInstBefore(NewSel, SI);
9277 NewSel->takeName(FVI);
9278 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9279 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
Torok Edwin56d06592009-07-11 20:10:48 +00009280 LLVM_UNREACHABLE("Unknown instruction!!");
Evan Cheng826b6f02009-03-31 20:42:45 +00009281 }
9282 }
9283 }
9284 }
9285 }
9286
9287 return 0;
9288}
9289
Dan Gohmandafa9c62008-09-16 18:46:06 +00009290/// visitSelectInstWithICmp - Visit a SelectInst that has an
9291/// ICmpInst as its first operand.
9292///
9293Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9294 ICmpInst *ICI) {
9295 bool Changed = false;
9296 ICmpInst::Predicate Pred = ICI->getPredicate();
9297 Value *CmpLHS = ICI->getOperand(0);
9298 Value *CmpRHS = ICI->getOperand(1);
9299 Value *TrueVal = SI.getTrueValue();
9300 Value *FalseVal = SI.getFalseValue();
9301
9302 // Check cases where the comparison is with a constant that
9303 // can be adjusted to fit the min/max idiom. We may edit ICI in
9304 // place here, so make sure the select is the only user.
9305 if (ICI->hasOneUse())
Dan Gohman13cbcf1c182008-10-30 20:40:10 +00009306 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
Dan Gohmandafa9c62008-09-16 18:46:06 +00009307 switch (Pred) {
9308 default: break;
9309 case ICmpInst::ICMP_ULT:
9310 case ICmpInst::ICMP_SLT: {
9311 // X < MIN ? T : F --> F
9312 if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9313 return ReplaceInstUsesWith(SI, FalseVal);
9314 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
Owen Andersonb5618da2009-07-03 00:17:18 +00009315 Constant *AdjustedRHS = SubOne(CI, Context);
Dan Gohmandafa9c62008-09-16 18:46:06 +00009316 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9317 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9318 Pred = ICmpInst::getSwappedPredicate(Pred);
9319 CmpRHS = AdjustedRHS;
9320 std::swap(FalseVal, TrueVal);
9321 ICI->setPredicate(Pred);
9322 ICI->setOperand(1, CmpRHS);
9323 SI.setOperand(1, TrueVal);
9324 SI.setOperand(2, FalseVal);
9325 Changed = true;
9326 }
9327 break;
9328 }
9329 case ICmpInst::ICMP_UGT:
9330 case ICmpInst::ICMP_SGT: {
9331 // X > MAX ? T : F --> F
9332 if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9333 return ReplaceInstUsesWith(SI, FalseVal);
9334 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
Owen Andersonb5618da2009-07-03 00:17:18 +00009335 Constant *AdjustedRHS = AddOne(CI, Context);
Dan Gohmandafa9c62008-09-16 18:46:06 +00009336 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9337 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9338 Pred = ICmpInst::getSwappedPredicate(Pred);
9339 CmpRHS = AdjustedRHS;
9340 std::swap(FalseVal, TrueVal);
9341 ICI->setPredicate(Pred);
9342 ICI->setOperand(1, CmpRHS);
9343 SI.setOperand(1, TrueVal);
9344 SI.setOperand(2, FalseVal);
9345 Changed = true;
9346 }
9347 break;
9348 }
9349 }
9350
Dan Gohman13cbcf1c182008-10-30 20:40:10 +00009351 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed
9352 // (x >s -1) ? -1 : 0 -> ashr x, 31 -> all ones if not signed
Chris Lattner44152742008-11-16 05:38:51 +00009353 CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
Owen Anderson16e76742009-07-10 17:35:01 +00009354 if (match(TrueVal, m_ConstantInt<-1>(), *Context) &&
9355 match(FalseVal, m_ConstantInt<0>(), *Context))
Chris Lattner44152742008-11-16 05:38:51 +00009356 Pred = ICI->getPredicate();
Owen Anderson16e76742009-07-10 17:35:01 +00009357 else if (match(TrueVal, m_ConstantInt<0>(), *Context) &&
9358 match(FalseVal, m_ConstantInt<-1>(), *Context))
Chris Lattner44152742008-11-16 05:38:51 +00009359 Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9360
Dan Gohman13cbcf1c182008-10-30 20:40:10 +00009361 if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9362 // If we are just checking for a icmp eq of a single bit and zext'ing it
9363 // to an integer, then shift the bit to the appropriate place and then
9364 // cast to integer to avoid the comparison.
9365 const APInt &Op1CV = CI->getValue();
9366
9367 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
9368 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
9369 if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
Chris Lattner44152742008-11-16 05:38:51 +00009370 (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
Dan Gohman13cbcf1c182008-10-30 20:40:10 +00009371 Value *In = ICI->getOperand(0);
Owen Andersonb5618da2009-07-03 00:17:18 +00009372 Value *Sh = Context->getConstantInt(In->getType(),
Dan Gohman7ccc52f2009-06-15 22:12:54 +00009373 In->getType()->getScalarSizeInBits()-1);
Dan Gohman13cbcf1c182008-10-30 20:40:10 +00009374 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
9375 In->getName()+".lobit"),
9376 *ICI);
Dan Gohman83eea0b2008-11-02 00:17:33 +00009377 if (In->getType() != SI.getType())
9378 In = CastInst::CreateIntegerCast(In, SI.getType(),
Dan Gohman13cbcf1c182008-10-30 20:40:10 +00009379 true/*SExt*/, "tmp", ICI);
9380
9381 if (Pred == ICmpInst::ICMP_SGT)
Owen Anderson542619e2009-07-13 20:58:05 +00009382 In = InsertNewInstBefore(BinaryOperator::CreateNot(*Context, In,
Dan Gohman13cbcf1c182008-10-30 20:40:10 +00009383 In->getName()+".not"), *ICI);
9384
9385 return ReplaceInstUsesWith(SI, In);
9386 }
9387 }
9388 }
9389
Dan Gohmandafa9c62008-09-16 18:46:06 +00009390 if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9391 // Transform (X == Y) ? X : Y -> Y
9392 if (Pred == ICmpInst::ICMP_EQ)
9393 return ReplaceInstUsesWith(SI, FalseVal);
9394 // Transform (X != Y) ? X : Y -> X
9395 if (Pred == ICmpInst::ICMP_NE)
9396 return ReplaceInstUsesWith(SI, TrueVal);
9397 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9398
9399 } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9400 // Transform (X == Y) ? Y : X -> X
9401 if (Pred == ICmpInst::ICMP_EQ)
9402 return ReplaceInstUsesWith(SI, FalseVal);
9403 // Transform (X != Y) ? Y : X -> Y
9404 if (Pred == ICmpInst::ICMP_NE)
9405 return ReplaceInstUsesWith(SI, TrueVal);
9406 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9407 }
9408
9409 /// NOTE: if we wanted to, this is where to detect integer ABS
9410
9411 return Changed ? &SI : 0;
9412}
9413
Chris Lattnerb909e8b2004-03-12 05:52:32 +00009414Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattner533bc492004-03-30 19:37:13 +00009415 Value *CondVal = SI.getCondition();
9416 Value *TrueVal = SI.getTrueValue();
9417 Value *FalseVal = SI.getFalseValue();
9418
9419 // select true, X, Y -> X
9420 // select false, X, Y -> Y
Zhou Sheng75b871f2007-01-11 12:24:14 +00009421 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencercddc9df2007-01-12 04:24:46 +00009422 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattner533bc492004-03-30 19:37:13 +00009423
9424 // select C, X, X -> X
9425 if (TrueVal == FalseVal)
9426 return ReplaceInstUsesWith(SI, TrueVal);
9427
Chris Lattner81a7a232004-10-16 18:11:37 +00009428 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
9429 return ReplaceInstUsesWith(SI, FalseVal);
9430 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
9431 return ReplaceInstUsesWith(SI, TrueVal);
9432 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
9433 if (isa<Constant>(TrueVal))
9434 return ReplaceInstUsesWith(SI, TrueVal);
9435 else
9436 return ReplaceInstUsesWith(SI, FalseVal);
9437 }
9438
Reid Spencer542964f2007-01-11 18:21:29 +00009439 if (SI.getType() == Type::Int1Ty) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +00009440 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencercddc9df2007-01-12 04:24:46 +00009441 if (C->getZExtValue()) {
Chris Lattner1c631e82004-04-08 04:43:23 +00009442 // Change: A = select B, true, C --> A = or B, C
Gabor Greife1f6e4b2008-05-16 19:29:10 +00009443 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00009444 } else {
9445 // Change: A = select B, false, C --> A = and !B, C
9446 Value *NotCond =
Owen Anderson542619e2009-07-13 20:58:05 +00009447 InsertNewInstBefore(BinaryOperator::CreateNot(*Context, CondVal,
Chris Lattner1c631e82004-04-08 04:43:23 +00009448 "not."+CondVal->getName()), SI);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00009449 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00009450 }
Reid Spencer7a9c62b2007-01-12 07:05:14 +00009451 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencercddc9df2007-01-12 04:24:46 +00009452 if (C->getZExtValue() == false) {
Chris Lattner1c631e82004-04-08 04:43:23 +00009453 // Change: A = select B, C, false --> A = and B, C
Gabor Greife1f6e4b2008-05-16 19:29:10 +00009454 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00009455 } else {
9456 // Change: A = select B, C, true --> A = or !B, C
9457 Value *NotCond =
Owen Anderson542619e2009-07-13 20:58:05 +00009458 InsertNewInstBefore(BinaryOperator::CreateNot(*Context, CondVal,
Chris Lattner1c631e82004-04-08 04:43:23 +00009459 "not."+CondVal->getName()), SI);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00009460 return BinaryOperator::CreateOr(NotCond, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00009461 }
9462 }
Chris Lattnerc00e8ad2007-11-25 21:27:53 +00009463
9464 // select a, b, a -> a&b
9465 // select a, a, b -> a|b
9466 if (CondVal == TrueVal)
Gabor Greife1f6e4b2008-05-16 19:29:10 +00009467 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattnerc00e8ad2007-11-25 21:27:53 +00009468 else if (CondVal == FalseVal)
Gabor Greife1f6e4b2008-05-16 19:29:10 +00009469 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Zhou Sheng75b871f2007-01-11 12:24:14 +00009470 }
Chris Lattner1c631e82004-04-08 04:43:23 +00009471
Chris Lattner183b3362004-04-09 19:05:30 +00009472 // Selecting between two integer constants?
9473 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9474 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattner20f23722007-04-11 06:12:58 +00009475 // select C, 1, 0 -> zext C to int
Reid Spencer959a21d2007-03-23 21:24:59 +00009476 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greife1f6e4b2008-05-16 19:29:10 +00009477 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer959a21d2007-03-23 21:24:59 +00009478 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattner20f23722007-04-11 06:12:58 +00009479 // select C, 0, 1 -> zext !C to int
Chris Lattner183b3362004-04-09 19:05:30 +00009480 Value *NotCond =
Owen Anderson542619e2009-07-13 20:58:05 +00009481 InsertNewInstBefore(BinaryOperator::CreateNot(*Context, CondVal,
Chris Lattnercf7baf32004-04-09 18:19:44 +00009482 "not."+CondVal->getName()), SI);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00009483 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattnercf7baf32004-04-09 18:19:44 +00009484 }
Chris Lattner35167c32004-06-09 07:59:58 +00009485
Reid Spencer266e42b2006-12-23 06:05:41 +00009486 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattner380c7e92006-09-20 04:44:59 +00009487 // If one of the constants is zero (we know they can't both be) and we
Chris Lattner20f23722007-04-11 06:12:58 +00009488 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattner380c7e92006-09-20 04:44:59 +00009489 // non-constant value, eliminate this whole mess. This corresponds to
9490 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer959a21d2007-03-23 21:24:59 +00009491 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattnerb3f24c92006-09-18 04:22:48 +00009492 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner35167c32004-06-09 07:59:58 +00009493 cast<Constant>(IC->getOperand(1))->isNullValue())
9494 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9495 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00009496 isa<ConstantInt>(ICA->getOperand(1)) &&
9497 (ICA->getOperand(1) == TrueValC ||
9498 ICA->getOperand(1) == FalseValC) &&
Chris Lattner35167c32004-06-09 07:59:58 +00009499 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9500 // Okay, now we know that everything is set up, we just don't
Reid Spencer266e42b2006-12-23 06:05:41 +00009501 // know whether we have a icmp_ne or icmp_eq and whether the
9502 // true or false val is the zero.
Reid Spencer959a21d2007-03-23 21:24:59 +00009503 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencer266e42b2006-12-23 06:05:41 +00009504 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner35167c32004-06-09 07:59:58 +00009505 Value *V = ICA;
9506 if (ShouldNotVal)
Gabor Greife1f6e4b2008-05-16 19:29:10 +00009507 V = InsertNewInstBefore(BinaryOperator::Create(
Chris Lattner35167c32004-06-09 07:59:58 +00009508 Instruction::Xor, V, ICA->getOperand(1)), SI);
9509 return ReplaceInstUsesWith(SI, V);
9510 }
Chris Lattner380c7e92006-09-20 04:44:59 +00009511 }
Chris Lattner533bc492004-03-30 19:37:13 +00009512 }
Chris Lattner623fba12004-04-10 22:21:27 +00009513
9514 // See if we are selecting two values based on a comparison of the two values.
Reid Spencer266e42b2006-12-23 06:05:41 +00009515 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9516 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattner623fba12004-04-10 22:21:27 +00009517 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen9d559cf2007-10-03 17:45:27 +00009518 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9519 // This is not safe in general for floating point:
9520 // consider X== -0, Y== +0.
9521 // It becomes safe if either operand is a nonzero constant.
9522 ConstantFP *CFPt, *CFPf;
9523 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9524 !CFPt->getValueAPF().isZero()) ||
9525 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9526 !CFPf->getValueAPF().isZero()))
Chris Lattner623fba12004-04-10 22:21:27 +00009527 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen9d559cf2007-10-03 17:45:27 +00009528 }
Chris Lattner623fba12004-04-10 22:21:27 +00009529 // Transform (X != Y) ? X : Y -> X
Reid Spencer266e42b2006-12-23 06:05:41 +00009530 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattner623fba12004-04-10 22:21:27 +00009531 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohmandafa9c62008-09-16 18:46:06 +00009532 // NOTE: if we wanted to, this is where to detect MIN/MAX
Chris Lattner623fba12004-04-10 22:21:27 +00009533
Reid Spencer266e42b2006-12-23 06:05:41 +00009534 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattner623fba12004-04-10 22:21:27 +00009535 // Transform (X == Y) ? Y : X -> X
Dale Johannesen9d559cf2007-10-03 17:45:27 +00009536 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9537 // This is not safe in general for floating point:
9538 // consider X== -0, Y== +0.
9539 // It becomes safe if either operand is a nonzero constant.
9540 ConstantFP *CFPt, *CFPf;
9541 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9542 !CFPt->getValueAPF().isZero()) ||
9543 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9544 !CFPf->getValueAPF().isZero()))
9545 return ReplaceInstUsesWith(SI, FalseVal);
9546 }
Chris Lattner623fba12004-04-10 22:21:27 +00009547 // Transform (X != Y) ? Y : X -> Y
Reid Spencer266e42b2006-12-23 06:05:41 +00009548 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9549 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohmandafa9c62008-09-16 18:46:06 +00009550 // NOTE: if we wanted to, this is where to detect MIN/MAX
Reid Spencer266e42b2006-12-23 06:05:41 +00009551 }
Dan Gohmandafa9c62008-09-16 18:46:06 +00009552 // NOTE: if we wanted to, this is where to detect ABS
Reid Spencer266e42b2006-12-23 06:05:41 +00009553 }
9554
9555 // See if we are selecting two values based on a comparison of the two values.
Dan Gohmandafa9c62008-09-16 18:46:06 +00009556 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9557 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9558 return Result;
Misha Brukmanb1c93172005-04-21 23:48:37 +00009559
Chris Lattnera04c9042005-01-13 22:52:24 +00009560 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9561 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9562 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattnera04c9042005-01-13 22:52:24 +00009563 Instruction *AddOp = 0, *SubOp = 0;
9564
Chris Lattner411336f2005-01-19 21:50:18 +00009565 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9566 if (TI->getOpcode() == FI->getOpcode())
9567 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9568 return IV;
9569
9570 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
9571 // even legal for FP.
Dan Gohmana5b96452009-06-04 22:49:04 +00009572 if ((TI->getOpcode() == Instruction::Sub &&
9573 FI->getOpcode() == Instruction::Add) ||
9574 (TI->getOpcode() == Instruction::FSub &&
9575 FI->getOpcode() == Instruction::FAdd)) {
Chris Lattnera04c9042005-01-13 22:52:24 +00009576 AddOp = FI; SubOp = TI;
Dan Gohmana5b96452009-06-04 22:49:04 +00009577 } else if ((FI->getOpcode() == Instruction::Sub &&
9578 TI->getOpcode() == Instruction::Add) ||
9579 (FI->getOpcode() == Instruction::FSub &&
9580 TI->getOpcode() == Instruction::FAdd)) {
Chris Lattnera04c9042005-01-13 22:52:24 +00009581 AddOp = TI; SubOp = FI;
9582 }
9583
9584 if (AddOp) {
9585 Value *OtherAddOp = 0;
9586 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9587 OtherAddOp = AddOp->getOperand(1);
9588 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9589 OtherAddOp = AddOp->getOperand(0);
9590 }
9591
9592 if (OtherAddOp) {
Chris Lattnerb580d262006-02-24 18:05:58 +00009593 // So at this point we know we have (Y -> OtherAddOp):
9594 // select C, (add X, Y), (sub X, Z)
9595 Value *NegVal; // Compute -Z
9596 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
Owen Andersonb5618da2009-07-03 00:17:18 +00009597 NegVal = Context->getConstantExprNeg(C);
Chris Lattnerb580d262006-02-24 18:05:58 +00009598 } else {
9599 NegVal = InsertNewInstBefore(
Owen Anderson53a52212009-07-13 04:09:18 +00009600 BinaryOperator::CreateNeg(*Context, SubOp->getOperand(1),
9601 "tmp"), SI);
Chris Lattnera04c9042005-01-13 22:52:24 +00009602 }
Chris Lattnerb580d262006-02-24 18:05:58 +00009603
9604 Value *NewTrueOp = OtherAddOp;
9605 Value *NewFalseOp = NegVal;
9606 if (AddOp != TI)
9607 std::swap(NewTrueOp, NewFalseOp);
9608 Instruction *NewSel =
Gabor Greif697e94c2008-05-15 10:04:30 +00009609 SelectInst::Create(CondVal, NewTrueOp,
9610 NewFalseOp, SI.getName() + ".p");
Chris Lattnerb580d262006-02-24 18:05:58 +00009611
9612 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00009613 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Chris Lattnera04c9042005-01-13 22:52:24 +00009614 }
9615 }
9616 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00009617
Chris Lattner56e4d3d2004-04-09 23:46:01 +00009618 // See if we can fold the select into one of our operands.
Chris Lattner03c49532007-01-15 02:27:26 +00009619 if (SI.getType()->isInteger()) {
Evan Cheng826b6f02009-03-31 20:42:45 +00009620 Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9621 if (FoldI)
9622 return FoldI;
Chris Lattner56e4d3d2004-04-09 23:46:01 +00009623 }
Chris Lattnerd6f636a2005-04-24 07:30:14 +00009624
9625 if (BinaryOperator::isNot(CondVal)) {
9626 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9627 SI.setOperand(1, FalseVal);
9628 SI.setOperand(2, TrueVal);
9629 return &SI;
9630 }
9631
Chris Lattnerb909e8b2004-03-12 05:52:32 +00009632 return 0;
9633}
9634
Dan Gohman99b7b3f2008-04-10 18:43:06 +00009635/// EnforceKnownAlignment - If the specified pointer points to an object that
9636/// we control, modify the object's alignment to PrefAlign. This isn't
9637/// often possible though. If alignment is important, a more reliable approach
9638/// is to simply align all global variables and allocation instructions to
9639/// their preferred alignment from the beginning.
9640///
9641static unsigned EnforceKnownAlignment(Value *V,
9642 unsigned Align, unsigned PrefAlign) {
Chris Lattnera8e4b4b2007-08-09 19:05:49 +00009643
Dan Gohman99b7b3f2008-04-10 18:43:06 +00009644 User *U = dyn_cast<User>(V);
9645 if (!U) return Align;
9646
9647 switch (getOpcode(U)) {
9648 default: break;
9649 case Instruction::BitCast:
9650 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9651 case Instruction::GetElementPtr: {
Chris Lattner82f2ef22006-03-06 20:18:44 +00009652 // If all indexes are zero, it is just the alignment of the base pointer.
9653 bool AllZeroOperands = true;
Gabor Greif431e9562008-06-12 21:51:29 +00009654 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
Gabor Greiff6d8e772008-06-12 21:37:33 +00009655 if (!isa<Constant>(*i) ||
9656 !cast<Constant>(*i)->isNullValue()) {
Chris Lattner82f2ef22006-03-06 20:18:44 +00009657 AllZeroOperands = false;
9658 break;
9659 }
Chris Lattnera8e4b4b2007-08-09 19:05:49 +00009660
9661 if (AllZeroOperands) {
9662 // Treat this like a bitcast.
Dan Gohman99b7b3f2008-04-10 18:43:06 +00009663 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattnera8e4b4b2007-08-09 19:05:49 +00009664 }
Dan Gohman99b7b3f2008-04-10 18:43:06 +00009665 break;
Chris Lattner82f2ef22006-03-06 20:18:44 +00009666 }
Dan Gohman99b7b3f2008-04-10 18:43:06 +00009667 }
9668
9669 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9670 // If there is a large requested alignment and we can, bump up the alignment
9671 // of the global.
9672 if (!GV->isDeclaration()) {
Dan Gohmanf68d29e2009-02-16 23:02:21 +00009673 if (GV->getAlignment() >= PrefAlign)
9674 Align = GV->getAlignment();
9675 else {
9676 GV->setAlignment(PrefAlign);
9677 Align = PrefAlign;
9678 }
Dan Gohman99b7b3f2008-04-10 18:43:06 +00009679 }
9680 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
9681 // If there is a requested alignment and if this is an alloca, round up. We
9682 // don't do this for malloc, because some systems can't respect the request.
9683 if (isa<AllocaInst>(AI)) {
Dan Gohmanf68d29e2009-02-16 23:02:21 +00009684 if (AI->getAlignment() >= PrefAlign)
9685 Align = AI->getAlignment();
9686 else {
9687 AI->setAlignment(PrefAlign);
9688 Align = PrefAlign;
9689 }
Dan Gohman99b7b3f2008-04-10 18:43:06 +00009690 }
9691 }
9692
9693 return Align;
9694}
9695
9696/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9697/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
9698/// and it is more than the alignment of the ultimate object, see if we can
9699/// increase the alignment of the ultimate object, making this check succeed.
9700unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9701 unsigned PrefAlign) {
9702 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9703 sizeof(PrefAlign) * CHAR_BIT;
9704 APInt Mask = APInt::getAllOnesValue(BitWidth);
9705 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9706 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9707 unsigned TrailZ = KnownZero.countTrailingOnes();
9708 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9709
9710 if (PrefAlign > Align)
9711 Align = EnforceKnownAlignment(V, Align, PrefAlign);
9712
9713 // We don't need to make any adjustment.
9714 return Align;
Chris Lattner82f2ef22006-03-06 20:18:44 +00009715}
9716
Chris Lattner57974c82008-01-13 23:50:23 +00009717Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohman99b7b3f2008-04-10 18:43:06 +00009718 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
Dan Gohman648c5e92009-02-22 18:06:32 +00009719 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattner57974c82008-01-13 23:50:23 +00009720 unsigned MinAlign = std::min(DstAlign, SrcAlign);
Chris Lattnerdc35e5b2009-03-08 03:59:00 +00009721 unsigned CopyAlign = MI->getAlignment();
Chris Lattner57974c82008-01-13 23:50:23 +00009722
9723 if (CopyAlign < MinAlign) {
Owen Anderson29fd3132009-07-09 18:36:20 +00009724 MI->setAlignment(Context->getConstantInt(MI->getAlignmentType(),
9725 MinAlign, false));
Chris Lattner57974c82008-01-13 23:50:23 +00009726 return MI;
9727 }
9728
9729 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9730 // load/store.
9731 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9732 if (MemOpLength == 0) return 0;
9733
Chris Lattner92bd7852008-01-14 00:28:35 +00009734 // Source and destination pointer types are always "i8*" for intrinsic. See
9735 // if the size is something we can handle with a single primitive load/store.
9736 // A single load+store correctly handles overlapping memory in the memmove
9737 // case.
Chris Lattner57974c82008-01-13 23:50:23 +00009738 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner2dc44262008-04-30 06:39:11 +00009739 if (Size == 0) return MI; // Delete this mem transfer.
9740
9741 if (Size > 8 || (Size&(Size-1)))
Chris Lattner92bd7852008-01-14 00:28:35 +00009742 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattner57974c82008-01-13 23:50:23 +00009743
Chris Lattner92bd7852008-01-14 00:28:35 +00009744 // Use an integer load+store unless we can find something better.
Owen Andersonb5618da2009-07-03 00:17:18 +00009745 Type *NewPtrTy =
9746 Context->getPointerTypeUnqual(Context->getIntegerType(Size<<3));
Chris Lattner92bd7852008-01-14 00:28:35 +00009747
9748 // Memcpy forces the use of i8* for the source and destination. That means
9749 // that if you're using memcpy to move one double around, you'll get a cast
9750 // from double* to i8*. We'd much rather use a double load+store rather than
9751 // an i64 load+store, here because this improves the odds that the source or
9752 // dest address will be promotable. See if we can find a better type than the
9753 // integer datatype.
9754 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9755 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9756 if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9757 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
9758 // down through these levels if so.
Dan Gohman53b26982008-05-23 01:52:21 +00009759 while (!SrcETy->isSingleValueType()) {
Chris Lattner92bd7852008-01-14 00:28:35 +00009760 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9761 if (STy->getNumElements() == 1)
9762 SrcETy = STy->getElementType(0);
9763 else
9764 break;
9765 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9766 if (ATy->getNumElements() == 1)
9767 SrcETy = ATy->getElementType();
9768 else
9769 break;
9770 } else
9771 break;
9772 }
9773
Dan Gohman53b26982008-05-23 01:52:21 +00009774 if (SrcETy->isSingleValueType())
Owen Andersonb5618da2009-07-03 00:17:18 +00009775 NewPtrTy = Context->getPointerTypeUnqual(SrcETy);
Chris Lattner92bd7852008-01-14 00:28:35 +00009776 }
9777 }
9778
9779
Chris Lattner57974c82008-01-13 23:50:23 +00009780 // If the memcpy/memmove provides better alignment info than we can
9781 // infer, use it.
9782 SrcAlign = std::max(SrcAlign, CopyAlign);
9783 DstAlign = std::max(DstAlign, CopyAlign);
9784
9785 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
9786 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
Chris Lattner92bd7852008-01-14 00:28:35 +00009787 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9788 InsertNewInstBefore(L, *MI);
9789 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9790
9791 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersonb5618da2009-07-03 00:17:18 +00009792 MI->setOperand(3, Context->getNullValue(MemOpLength->getType()));
Chris Lattner92bd7852008-01-14 00:28:35 +00009793 return MI;
Chris Lattner57974c82008-01-13 23:50:23 +00009794}
Chris Lattnerb909e8b2004-03-12 05:52:32 +00009795
Chris Lattner2dc44262008-04-30 06:39:11 +00009796Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9797 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
Chris Lattnerdc35e5b2009-03-08 03:59:00 +00009798 if (MI->getAlignment() < Alignment) {
Owen Anderson29fd3132009-07-09 18:36:20 +00009799 MI->setAlignment(Context->getConstantInt(MI->getAlignmentType(),
9800 Alignment, false));
Chris Lattner2dc44262008-04-30 06:39:11 +00009801 return MI;
9802 }
9803
9804 // Extract the length and alignment and fill if they are constant.
9805 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9806 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9807 if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
9808 return 0;
9809 uint64_t Len = LenC->getZExtValue();
Chris Lattnerdc35e5b2009-03-08 03:59:00 +00009810 Alignment = MI->getAlignment();
Chris Lattner2dc44262008-04-30 06:39:11 +00009811
9812 // If the length is zero, this is a no-op
9813 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9814
9815 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9816 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
Owen Andersonb5618da2009-07-03 00:17:18 +00009817 const Type *ITy = Context->getIntegerType(Len*8); // n=1 -> i8.
Chris Lattner2dc44262008-04-30 06:39:11 +00009818
9819 Value *Dest = MI->getDest();
Owen Andersonb5618da2009-07-03 00:17:18 +00009820 Dest = InsertBitCastBefore(Dest, Context->getPointerTypeUnqual(ITy), *MI);
Chris Lattner2dc44262008-04-30 06:39:11 +00009821
9822 // Alignment 0 is identity for alignment 1 for memset, but not store.
9823 if (Alignment == 0) Alignment = 1;
9824
9825 // Extract the fill value and store.
9826 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
Owen Andersonb5618da2009-07-03 00:17:18 +00009827 InsertNewInstBefore(new StoreInst(Context->getConstantInt(ITy, Fill),
9828 Dest, false, Alignment), *MI);
Chris Lattner2dc44262008-04-30 06:39:11 +00009829
9830 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersonb5618da2009-07-03 00:17:18 +00009831 MI->setLength(Context->getNullValue(LenC->getType()));
Chris Lattner2dc44262008-04-30 06:39:11 +00009832 return MI;
9833 }
9834
9835 return 0;
9836}
9837
9838
Chris Lattnerc66b2232006-01-13 20:11:04 +00009839/// visitCallInst - CallInst simplification. This mostly only handles folding
9840/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
9841/// the heavy lifting.
9842///
Chris Lattner970c33a2003-06-19 17:00:31 +00009843Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattner149546a2009-05-13 17:39:14 +00009844 // If the caller function is nounwind, mark the call as nounwind, even if the
9845 // callee isn't.
9846 if (CI.getParent()->getParent()->doesNotThrow() &&
9847 !CI.doesNotThrow()) {
9848 CI.setDoesNotThrow();
9849 return &CI;
9850 }
9851
9852
9853
Chris Lattnerc66b2232006-01-13 20:11:04 +00009854 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9855 if (!II) return visitCallSite(&CI);
9856
Chris Lattner51ea1272004-02-28 05:22:00 +00009857 // Intrinsics cannot occur in an invoke, so handle them here instead of in
9858 // visitCallSite.
Chris Lattnerc66b2232006-01-13 20:11:04 +00009859 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner00648e12004-10-12 04:52:52 +00009860 bool Changed = false;
9861
9862 // memmove/cpy/set of zero bytes is a noop.
9863 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9864 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9865
Chris Lattner00648e12004-10-12 04:52:52 +00009866 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencere0fc4df2006-10-20 07:07:24 +00009867 if (CI->getZExtValue() == 1) {
Chris Lattner00648e12004-10-12 04:52:52 +00009868 // Replace the instruction with just byte operations. We would
9869 // transform other cases to loads/stores, but we don't know if
9870 // alignment is sufficient.
9871 }
Chris Lattner51ea1272004-02-28 05:22:00 +00009872 }
9873
Chris Lattner00648e12004-10-12 04:52:52 +00009874 // If we have a memmove and the source operation is a constant global,
9875 // then the source and dest pointers can't alias, so we can change this
9876 // into a call to memcpy.
Chris Lattner57974c82008-01-13 23:50:23 +00009877 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Chris Lattner00648e12004-10-12 04:52:52 +00009878 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9879 if (GVSrc->isConstant()) {
9880 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattnerdd708342008-11-21 16:42:48 +00009881 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9882 const Type *Tys[1];
9883 Tys[0] = CI.getOperand(3)->getType();
9884 CI.setOperand(0,
9885 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
Chris Lattner00648e12004-10-12 04:52:52 +00009886 Changed = true;
9887 }
Chris Lattnerecdefb52008-05-28 05:30:41 +00009888
9889 // memmove(x,x,size) -> noop.
9890 if (MMI->getSource() == MMI->getDest())
9891 return EraseInstFromFunction(CI);
Chris Lattner82f2ef22006-03-06 20:18:44 +00009892 }
Chris Lattner00648e12004-10-12 04:52:52 +00009893
Chris Lattner82f2ef22006-03-06 20:18:44 +00009894 // If we can determine a pointer alignment that is bigger than currently
9895 // set, update the alignment.
Chris Lattner334268a2009-03-08 03:37:16 +00009896 if (isa<MemTransferInst>(MI)) {
Chris Lattner57974c82008-01-13 23:50:23 +00009897 if (Instruction *I = SimplifyMemTransfer(MI))
9898 return I;
Chris Lattner2dc44262008-04-30 06:39:11 +00009899 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9900 if (Instruction *I = SimplifyMemSet(MSI))
9901 return I;
Chris Lattner82f2ef22006-03-06 20:18:44 +00009902 }
9903
Chris Lattnerc66b2232006-01-13 20:11:04 +00009904 if (Changed) return II;
Chris Lattneref36dcd2008-06-18 04:33:20 +00009905 }
9906
9907 switch (II->getIntrinsicID()) {
9908 default: break;
9909 case Intrinsic::bswap:
9910 // bswap(bswap(x)) -> x
9911 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9912 if (Operand->getIntrinsicID() == Intrinsic::bswap)
9913 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9914 break;
9915 case Intrinsic::ppc_altivec_lvx:
9916 case Intrinsic::ppc_altivec_lvxl:
9917 case Intrinsic::x86_sse_loadu_ps:
9918 case Intrinsic::x86_sse2_loadu_pd:
9919 case Intrinsic::x86_sse2_loadu_dq:
9920 // Turn PPC lvx -> load if the pointer is known aligned.
9921 // Turn X86 loadups -> load if the pointer is known aligned.
9922 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9923 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
Owen Andersonb5618da2009-07-03 00:17:18 +00009924 Context->getPointerTypeUnqual(II->getType()),
Chris Lattneref36dcd2008-06-18 04:33:20 +00009925 CI);
9926 return new LoadInst(Ptr);
Chris Lattner2deeaea2006-10-05 06:55:50 +00009927 }
Chris Lattneref36dcd2008-06-18 04:33:20 +00009928 break;
9929 case Intrinsic::ppc_altivec_stvx:
9930 case Intrinsic::ppc_altivec_stvxl:
9931 // Turn stvx -> store if the pointer is known aligned.
9932 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9933 const Type *OpPtrTy =
Owen Andersonb5618da2009-07-03 00:17:18 +00009934 Context->getPointerTypeUnqual(II->getOperand(1)->getType());
Chris Lattneref36dcd2008-06-18 04:33:20 +00009935 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
9936 return new StoreInst(II->getOperand(1), Ptr);
9937 }
9938 break;
9939 case Intrinsic::x86_sse_storeu_ps:
9940 case Intrinsic::x86_sse2_storeu_pd:
9941 case Intrinsic::x86_sse2_storeu_dq:
Chris Lattneref36dcd2008-06-18 04:33:20 +00009942 // Turn X86 storeu -> store if the pointer is known aligned.
9943 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9944 const Type *OpPtrTy =
Owen Andersonb5618da2009-07-03 00:17:18 +00009945 Context->getPointerTypeUnqual(II->getOperand(2)->getType());
Chris Lattneref36dcd2008-06-18 04:33:20 +00009946 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
9947 return new StoreInst(II->getOperand(2), Ptr);
9948 }
9949 break;
9950
9951 case Intrinsic::x86_sse_cvttss2si: {
9952 // These intrinsics only demands the 0th element of its input vector. If
9953 // we can simplify the input based on that, do so now.
Evan Cheng8542caa2009-02-03 10:05:09 +00009954 unsigned VWidth =
9955 cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9956 APInt DemandedElts(VWidth, 1);
9957 APInt UndefElts(VWidth, 0);
9958 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
Chris Lattneref36dcd2008-06-18 04:33:20 +00009959 UndefElts)) {
9960 II->setOperand(1, V);
9961 return II;
9962 }
9963 break;
9964 }
9965
9966 case Intrinsic::ppc_altivec_vperm:
9967 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9968 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9969 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
Chris Lattner2deeaea2006-10-05 06:55:50 +00009970
Chris Lattneref36dcd2008-06-18 04:33:20 +00009971 // Check that all of the elements are integer constants or undefs.
9972 bool AllEltsOk = true;
9973 for (unsigned i = 0; i != 16; ++i) {
9974 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
9975 !isa<UndefValue>(Mask->getOperand(i))) {
9976 AllEltsOk = false;
9977 break;
9978 }
9979 }
9980
9981 if (AllEltsOk) {
9982 // Cast the input vectors to byte vectors.
9983 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
9984 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
Owen Andersonb5618da2009-07-03 00:17:18 +00009985 Value *Result = Context->getUndef(Op0->getType());
Chris Lattnere79d2492006-04-06 19:19:17 +00009986
Chris Lattneref36dcd2008-06-18 04:33:20 +00009987 // Only extract each element once.
9988 Value *ExtractedElts[32];
9989 memset(ExtractedElts, 0, sizeof(ExtractedElts));
9990
Chris Lattnere79d2492006-04-06 19:19:17 +00009991 for (unsigned i = 0; i != 16; ++i) {
Chris Lattneref36dcd2008-06-18 04:33:20 +00009992 if (isa<UndefValue>(Mask->getOperand(i)))
9993 continue;
9994 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9995 Idx &= 31; // Match the hardware behavior.
9996
9997 if (ExtractedElts[Idx] == 0) {
9998 Instruction *Elt =
9999 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
10000 InsertNewInstBefore(Elt, CI);
10001 ExtractedElts[Idx] = Elt;
Chris Lattnere79d2492006-04-06 19:19:17 +000010002 }
Chris Lattnere79d2492006-04-06 19:19:17 +000010003
Chris Lattneref36dcd2008-06-18 04:33:20 +000010004 // Insert this value into the result vector.
10005 Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
10006 i, "tmp");
10007 InsertNewInstBefore(cast<Instruction>(Result), CI);
Chris Lattnere79d2492006-04-06 19:19:17 +000010008 }
Chris Lattneref36dcd2008-06-18 04:33:20 +000010009 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere79d2492006-04-06 19:19:17 +000010010 }
Chris Lattneref36dcd2008-06-18 04:33:20 +000010011 }
10012 break;
Chris Lattnere79d2492006-04-06 19:19:17 +000010013
Chris Lattneref36dcd2008-06-18 04:33:20 +000010014 case Intrinsic::stackrestore: {
10015 // If the save is right next to the restore, remove the restore. This can
10016 // happen when variable allocas are DCE'd.
10017 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
10018 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
10019 BasicBlock::iterator BI = SS;
10020 if (&*++BI == II)
10021 return EraseInstFromFunction(CI);
Chris Lattner503221f2006-01-13 21:28:09 +000010022 }
Chris Lattneref36dcd2008-06-18 04:33:20 +000010023 }
10024
10025 // Scan down this block to see if there is another stack restore in the
10026 // same block without an intervening call/alloca.
10027 BasicBlock::iterator BI = II;
10028 TerminatorInst *TI = II->getParent()->getTerminator();
10029 bool CannotRemove = false;
10030 for (++BI; &*BI != TI; ++BI) {
10031 if (isa<AllocaInst>(BI)) {
10032 CannotRemove = true;
10033 break;
10034 }
Chris Lattnerc9c81fb2008-06-25 05:59:28 +000010035 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
10036 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
10037 // If there is a stackrestore below this one, remove this one.
10038 if (II->getIntrinsicID() == Intrinsic::stackrestore)
10039 return EraseInstFromFunction(CI);
10040 // Otherwise, ignore the intrinsic.
10041 } else {
10042 // If we found a non-intrinsic call, we can't remove the stack
10043 // restore.
Chris Lattner024f8c82008-02-18 06:12:38 +000010044 CannotRemove = true;
10045 break;
10046 }
Chris Lattneref36dcd2008-06-18 04:33:20 +000010047 }
Chris Lattner503221f2006-01-13 21:28:09 +000010048 }
Chris Lattneref36dcd2008-06-18 04:33:20 +000010049
10050 // If the stack restore is in a return/unwind block and if there are no
10051 // allocas or calls between the restore and the return, nuke the restore.
10052 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
10053 return EraseInstFromFunction(CI);
10054 break;
10055 }
Chris Lattner00648e12004-10-12 04:52:52 +000010056 }
10057
Chris Lattnerc66b2232006-01-13 20:11:04 +000010058 return visitCallSite(II);
Chris Lattner970c33a2003-06-19 17:00:31 +000010059}
10060
10061// InvokeInst simplification
10062//
10063Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattneraec3d942003-10-07 22:32:43 +000010064 return visitCallSite(&II);
Chris Lattner970c33a2003-06-19 17:00:31 +000010065}
10066
Dale Johannesen0d1d3df2008-04-25 21:16:07 +000010067/// isSafeToEliminateVarargsCast - If this cast does not affect the value
10068/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesenf6e15a42008-04-23 18:34:37 +000010069static bool isSafeToEliminateVarargsCast(const CallSite CS,
10070 const CastInst * const CI,
10071 const TargetData * const TD,
10072 const int ix) {
10073 if (!CI->isLosslessCast())
10074 return false;
10075
10076 // The size of ByVal arguments is derived from the type, so we
10077 // can't change to a type with a different size. If the size were
10078 // passed explicitly we could avoid this check.
Devang Patel4c758ea2008-09-25 21:00:45 +000010079 if (!CS.paramHasAttr(ix, Attribute::ByVal))
Dale Johannesenf6e15a42008-04-23 18:34:37 +000010080 return true;
10081
10082 const Type* SrcTy =
10083 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
10084 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
10085 if (!SrcTy->isSized() || !DstTy->isSized())
10086 return false;
Duncan Sandsaf9eaa82009-05-09 07:06:46 +000010087 if (TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
Dale Johannesenf6e15a42008-04-23 18:34:37 +000010088 return false;
10089 return true;
10090}
10091
Chris Lattneraec3d942003-10-07 22:32:43 +000010092// visitCallSite - Improvements for call and invoke instructions.
10093//
10094Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +000010095 bool Changed = false;
10096
10097 // If the callee is a constexpr cast of a function, attempt to move the cast
10098 // to the arguments of the call/invoke.
Chris Lattneraec3d942003-10-07 22:32:43 +000010099 if (transformConstExprCastCall(CS)) return 0;
10100
Chris Lattner75b4d1d2003-10-07 22:54:13 +000010101 Value *Callee = CS.getCalledValue();
Chris Lattner81a7a232004-10-16 18:11:37 +000010102
Chris Lattner61d9d812005-05-13 07:09:09 +000010103 if (Function *CalleeF = dyn_cast<Function>(Callee))
10104 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
10105 Instruction *OldCall = CS.getInstruction();
10106 // If the call and callee calling conventions don't match, this call must
10107 // be unreachable, as the call is undefined.
Owen Andersonb5618da2009-07-03 00:17:18 +000010108 new StoreInst(Context->getConstantIntTrue(),
10109 Context->getUndef(Context->getPointerTypeUnqual(Type::Int1Ty)),
10110 OldCall);
Chris Lattner61d9d812005-05-13 07:09:09 +000010111 if (!OldCall->use_empty())
Owen Andersonb5618da2009-07-03 00:17:18 +000010112 OldCall->replaceAllUsesWith(Context->getUndef(OldCall->getType()));
Chris Lattner61d9d812005-05-13 07:09:09 +000010113 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
10114 return EraseInstFromFunction(*OldCall);
10115 return 0;
10116 }
10117
Chris Lattner8ba9ec92004-10-18 02:59:09 +000010118 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
10119 // This instruction is not reachable, just remove it. We insert a store to
10120 // undef so that we know that this code is not reachable, despite the fact
10121 // that we can't modify the CFG here.
Owen Andersonb5618da2009-07-03 00:17:18 +000010122 new StoreInst(Context->getConstantIntTrue(),
10123 Context->getUndef(Context->getPointerTypeUnqual(Type::Int1Ty)),
Chris Lattner8ba9ec92004-10-18 02:59:09 +000010124 CS.getInstruction());
10125
10126 if (!CS.getInstruction()->use_empty())
10127 CS.getInstruction()->
Owen Andersonb5618da2009-07-03 00:17:18 +000010128 replaceAllUsesWith(Context->getUndef(CS.getInstruction()->getType()));
Chris Lattner8ba9ec92004-10-18 02:59:09 +000010129
10130 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
10131 // Don't break the CFG, insert a dummy cond branch.
Gabor Greife9ecc682008-04-06 20:25:17 +000010132 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
Owen Andersonb5618da2009-07-03 00:17:18 +000010133 Context->getConstantIntTrue(), II);
Chris Lattner81a7a232004-10-16 18:11:37 +000010134 }
Chris Lattner8ba9ec92004-10-18 02:59:09 +000010135 return EraseInstFromFunction(*CS.getInstruction());
10136 }
Chris Lattner81a7a232004-10-16 18:11:37 +000010137
Duncan Sands6d5da712007-09-17 10:26:40 +000010138 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
10139 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
10140 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
10141 return transformCallThroughTrampoline(CS);
10142
Chris Lattner75b4d1d2003-10-07 22:54:13 +000010143 const PointerType *PTy = cast<PointerType>(Callee->getType());
10144 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10145 if (FTy->isVarArg()) {
Dale Johannesen493527d2008-04-23 01:03:05 +000010146 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Chris Lattner75b4d1d2003-10-07 22:54:13 +000010147 // See if we can optimize any arguments passed through the varargs area of
10148 // the call.
10149 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesenf6e15a42008-04-23 18:34:37 +000010150 E = CS.arg_end(); I != E; ++I, ++ix) {
10151 CastInst *CI = dyn_cast<CastInst>(*I);
10152 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
10153 *I = CI->getOperand(0);
10154 Changed = true;
Chris Lattner75b4d1d2003-10-07 22:54:13 +000010155 }
Dale Johannesenf6e15a42008-04-23 18:34:37 +000010156 }
Chris Lattner75b4d1d2003-10-07 22:54:13 +000010157 }
Misha Brukmanb1c93172005-04-21 23:48:37 +000010158
Duncan Sandsaa31b922007-12-19 21:13:37 +000010159 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sands8e4847e2007-12-16 15:51:49 +000010160 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsaa31b922007-12-19 21:13:37 +000010161 CS.setDoesNotThrow();
Duncan Sands8e4847e2007-12-16 15:51:49 +000010162 Changed = true;
10163 }
10164
Chris Lattner75b4d1d2003-10-07 22:54:13 +000010165 return Changed ? CS.getInstruction() : 0;
Chris Lattneraec3d942003-10-07 22:32:43 +000010166}
10167
Chris Lattner970c33a2003-06-19 17:00:31 +000010168// transformConstExprCastCall - If the callee is a constexpr cast of a function,
10169// attempt to move the cast to the arguments of the call/invoke.
10170//
10171bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10172 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10173 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer6c38f0b2006-11-27 01:05:10 +000010174 if (CE->getOpcode() != Instruction::BitCast ||
10175 !isa<Function>(CE->getOperand(0)))
Chris Lattner970c33a2003-06-19 17:00:31 +000010176 return false;
Reid Spencer87436872004-07-18 00:38:32 +000010177 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner970c33a2003-06-19 17:00:31 +000010178 Instruction *Caller = CS.getInstruction();
Devang Patel4c758ea2008-09-25 21:00:45 +000010179 const AttrListPtr &CallerPAL = CS.getAttributes();
Chris Lattner970c33a2003-06-19 17:00:31 +000010180
10181 // Okay, this is a cast from a function to a different type. Unless doing so
10182 // would cause a type conversion of one of our arguments, change this call to
10183 // be a direct call with arguments casted to the appropriate types.
10184 //
10185 const FunctionType *FT = Callee->getFunctionType();
10186 const Type *OldRetTy = Caller->getType();
Duncan Sands0397cd22008-06-01 07:38:42 +000010187 const Type *NewRetTy = FT->getReturnType();
Chris Lattner970c33a2003-06-19 17:00:31 +000010188
Duncan Sands0397cd22008-06-01 07:38:42 +000010189 if (isa<StructType>(NewRetTy))
Devang Patel70c238a2008-03-11 18:04:06 +000010190 return false; // TODO: Handle multiple return values.
10191
Chris Lattner1f7942f2004-01-14 06:06:08 +000010192 // Check to see if we are changing the return type...
Duncan Sands0397cd22008-06-01 07:38:42 +000010193 if (OldRetTy != NewRetTy) {
Bill Wendling37169522008-05-14 22:45:20 +000010194 if (Callee->isDeclaration() &&
Duncan Sands0397cd22008-06-01 07:38:42 +000010195 // Conversion is ok if changing from one pointer type to another or from
10196 // a pointer to an integer of the same size.
10197 !((isa<PointerType>(OldRetTy) || OldRetTy == TD->getIntPtrType()) &&
Duncan Sands4b50fde2008-06-17 15:55:30 +000010198 (isa<PointerType>(NewRetTy) || NewRetTy == TD->getIntPtrType())))
Chris Lattner400f9592007-01-06 02:09:32 +000010199 return false; // Cannot transform this return value.
Chris Lattner1f7942f2004-01-14 06:06:08 +000010200
Duncan Sands55e50902008-01-06 10:12:28 +000010201 if (!Caller->use_empty() &&
Duncan Sands55e50902008-01-06 10:12:28 +000010202 // void -> non-void is handled specially
Duncan Sands0397cd22008-06-01 07:38:42 +000010203 NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
Duncan Sands55e50902008-01-06 10:12:28 +000010204 return false; // Cannot transform this return value.
10205
Chris Lattner8a923e72008-03-12 17:45:29 +000010206 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Devang Patela05633e2008-09-26 22:53:05 +000010207 Attributes RAttrs = CallerPAL.getRetAttributes();
Devang Patel4c758ea2008-09-25 21:00:45 +000010208 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
Duncan Sandsb18c30a2008-01-07 17:16:06 +000010209 return false; // Attribute not compatible with transformed value.
10210 }
Duncan Sands404eb052008-01-06 18:27:01 +000010211
Chris Lattner1f7942f2004-01-14 06:06:08 +000010212 // If the callsite is an invoke instruction, and the return value is used by
10213 // a PHI node in a successor, we cannot change the return type of the call
10214 // because there is no place to put the cast instruction (without breaking
10215 // the critical edge). Bail out in this case.
10216 if (!Caller->use_empty())
10217 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10218 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10219 UI != E; ++UI)
10220 if (PHINode *PN = dyn_cast<PHINode>(*UI))
10221 if (PN->getParent() == II->getNormalDest() ||
Chris Lattnerfae8ab32004-02-08 21:44:31 +000010222 PN->getParent() == II->getUnwindDest())
Chris Lattner1f7942f2004-01-14 06:06:08 +000010223 return false;
10224 }
Chris Lattner970c33a2003-06-19 17:00:31 +000010225
10226 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10227 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanb1c93172005-04-21 23:48:37 +000010228
Chris Lattner970c33a2003-06-19 17:00:31 +000010229 CallSite::arg_iterator AI = CS.arg_begin();
10230 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10231 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthebfa24e2006-06-28 01:01:52 +000010232 const Type *ActTy = (*AI)->getType();
Duncan Sands55e50902008-01-06 10:12:28 +000010233
10234 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sands404eb052008-01-06 18:27:01 +000010235 return false; // Cannot transform this parameter value.
10236
Devang Patela05633e2008-09-26 22:53:05 +000010237 if (CallerPAL.getParamAttributes(i + 1)
10238 & Attribute::typeIncompatible(ParamTy))
Chris Lattner8a923e72008-03-12 17:45:29 +000010239 return false; // Attribute not compatible with transformed value.
Duncan Sands55e50902008-01-06 10:12:28 +000010240
Duncan Sands0397cd22008-06-01 07:38:42 +000010241 // Converting from one pointer type to another or between a pointer and an
10242 // integer of the same size is safe even if we do not have a body.
Chris Lattner400f9592007-01-06 02:09:32 +000010243 bool isConvertible = ActTy == ParamTy ||
Duncan Sands0397cd22008-06-01 07:38:42 +000010244 ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
10245 (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType()));
Reid Spencer5301e7c2007-01-30 20:08:39 +000010246 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner970c33a2003-06-19 17:00:31 +000010247 }
10248
10249 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5301e7c2007-01-30 20:08:39 +000010250 Callee->isDeclaration())
Chris Lattner8a923e72008-03-12 17:45:29 +000010251 return false; // Do not delete arguments unless we have a function body.
Chris Lattner970c33a2003-06-19 17:00:31 +000010252
Chris Lattner8a923e72008-03-12 17:45:29 +000010253 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10254 !CallerPAL.isEmpty())
Duncan Sands404eb052008-01-06 18:27:01 +000010255 // In this case we have more arguments than the new function type, but we
Duncan Sands781f6542008-01-13 08:02:44 +000010256 // won't be dropping them. Check that these extra arguments have attributes
10257 // that are compatible with being a vararg call argument.
Chris Lattner8a923e72008-03-12 17:45:29 +000010258 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10259 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sands781f6542008-01-13 08:02:44 +000010260 break;
Devang Patelba3fa6c2008-09-23 23:03:40 +000010261 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Devang Patel4c758ea2008-09-25 21:00:45 +000010262 if (PAttrs & Attribute::VarArgsIncompatible)
Duncan Sands781f6542008-01-13 08:02:44 +000010263 return false;
10264 }
Duncan Sands404eb052008-01-06 18:27:01 +000010265
Chris Lattner970c33a2003-06-19 17:00:31 +000010266 // Okay, we decided that this is a safe thing to do: go ahead and start
10267 // inserting cast instructions as necessary...
10268 std::vector<Value*> Args;
10269 Args.reserve(NumActualArgs);
Devang Patel4c758ea2008-09-25 21:00:45 +000010270 SmallVector<AttributeWithIndex, 8> attrVec;
Duncan Sands404eb052008-01-06 18:27:01 +000010271 attrVec.reserve(NumCommonArgs);
10272
10273 // Get any return attributes.
Devang Patela05633e2008-09-26 22:53:05 +000010274 Attributes RAttrs = CallerPAL.getRetAttributes();
Duncan Sands404eb052008-01-06 18:27:01 +000010275
10276 // If the return value is not being used, the type may not be compatible
10277 // with the existing attributes. Wipe out any problematic attributes.
Devang Patel4c758ea2008-09-25 21:00:45 +000010278 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
Duncan Sands404eb052008-01-06 18:27:01 +000010279
10280 // Add the new return attributes.
10281 if (RAttrs)
Devang Patel4c758ea2008-09-25 21:00:45 +000010282 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
Chris Lattner970c33a2003-06-19 17:00:31 +000010283
10284 AI = CS.arg_begin();
10285 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10286 const Type *ParamTy = FT->getParamType(i);
10287 if ((*AI)->getType() == ParamTy) {
10288 Args.push_back(*AI);
10289 } else {
Reid Spencer668d90f2006-12-18 08:47:13 +000010290 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc635f472006-12-31 05:48:39 +000010291 false, ParamTy, false);
Gabor Greife1f6e4b2008-05-16 19:29:10 +000010292 CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
Reid Spencer6c38f0b2006-11-27 01:05:10 +000010293 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner970c33a2003-06-19 17:00:31 +000010294 }
Duncan Sands404eb052008-01-06 18:27:01 +000010295
10296 // Add any parameter attributes.
Devang Patela05633e2008-09-26 22:53:05 +000010297 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel4c758ea2008-09-25 21:00:45 +000010298 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Chris Lattner970c33a2003-06-19 17:00:31 +000010299 }
10300
10301 // If the function takes more arguments than the call was taking, add them
10302 // now...
10303 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
Owen Andersonb5618da2009-07-03 00:17:18 +000010304 Args.push_back(Context->getNullValue(FT->getParamType(i)));
Chris Lattner970c33a2003-06-19 17:00:31 +000010305
10306 // If we are removing arguments to the function, emit an obnoxious warning...
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +000010307 if (FT->getNumParams() < NumActualArgs) {
Chris Lattner970c33a2003-06-19 17:00:31 +000010308 if (!FT->isVarArg()) {
Bill Wendlingf3baad32006-12-07 01:30:32 +000010309 cerr << "WARNING: While resolving call to function '"
10310 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner970c33a2003-06-19 17:00:31 +000010311 } else {
10312 // Add all of the arguments in their promoted form to the arg list...
10313 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10314 const Type *PTy = getPromotedType((*AI)->getType());
10315 if (PTy != (*AI)->getType()) {
10316 // Must promote to pass through va_arg area!
Reid Spencerc635f472006-12-31 05:48:39 +000010317 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
10318 PTy, false);
Gabor Greife1f6e4b2008-05-16 19:29:10 +000010319 Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
Chris Lattner970c33a2003-06-19 17:00:31 +000010320 InsertNewInstBefore(Cast, *Caller);
10321 Args.push_back(Cast);
10322 } else {
10323 Args.push_back(*AI);
10324 }
Duncan Sands404eb052008-01-06 18:27:01 +000010325
Duncan Sands781f6542008-01-13 08:02:44 +000010326 // Add any parameter attributes.
Devang Patela05633e2008-09-26 22:53:05 +000010327 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel4c758ea2008-09-25 21:00:45 +000010328 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Duncan Sands781f6542008-01-13 08:02:44 +000010329 }
Chris Lattner970c33a2003-06-19 17:00:31 +000010330 }
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +000010331 }
Chris Lattner970c33a2003-06-19 17:00:31 +000010332
Devang Patela05633e2008-09-26 22:53:05 +000010333 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
10334 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10335
Duncan Sands0397cd22008-06-01 07:38:42 +000010336 if (NewRetTy == Type::VoidTy)
Chris Lattner6e0123b2007-02-11 01:23:03 +000010337 Caller->setName(""); // Void type should not have a name.
Chris Lattner970c33a2003-06-19 17:00:31 +000010338
Devang Patel4c758ea2008-09-25 21:00:45 +000010339 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),attrVec.end());
Duncan Sands404eb052008-01-06 18:27:01 +000010340
Chris Lattner970c33a2003-06-19 17:00:31 +000010341 Instruction *NC;
10342 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greife9ecc682008-04-06 20:25:17 +000010343 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greif697e94c2008-05-15 10:04:30 +000010344 Args.begin(), Args.end(),
10345 Caller->getName(), Caller);
Reid Spencerdff9d692007-07-30 19:53:57 +000010346 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Devang Patel4c758ea2008-09-25 21:00:45 +000010347 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner970c33a2003-06-19 17:00:31 +000010348 } else {
Gabor Greife9ecc682008-04-06 20:25:17 +000010349 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10350 Caller->getName(), Caller);
Duncan Sandsad0ea2d2007-11-27 13:23:08 +000010351 CallInst *CI = cast<CallInst>(Caller);
10352 if (CI->isTailCall())
Chris Lattner6aacb0f2005-05-06 06:48:21 +000010353 cast<CallInst>(NC)->setTailCall();
Duncan Sandsad0ea2d2007-11-27 13:23:08 +000010354 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Devang Patel4c758ea2008-09-25 21:00:45 +000010355 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner970c33a2003-06-19 17:00:31 +000010356 }
10357
Chris Lattner6e0123b2007-02-11 01:23:03 +000010358 // Insert a cast of the return type as necessary.
Chris Lattner970c33a2003-06-19 17:00:31 +000010359 Value *NV = NC;
Duncan Sands55e50902008-01-06 10:12:28 +000010360 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Chris Lattner970c33a2003-06-19 17:00:31 +000010361 if (NV->getType() != Type::VoidTy) {
Reid Spencerc635f472006-12-31 05:48:39 +000010362 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sands55e50902008-01-06 10:12:28 +000010363 OldRetTy, false);
Gabor Greife1f6e4b2008-05-16 19:29:10 +000010364 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Chris Lattner686767f2003-10-30 00:46:41 +000010365
10366 // If this is an invoke instruction, we should insert it after the first
10367 // non-phi, instruction in the normal successor block.
10368 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohmanf96e1372008-05-23 21:05:58 +000010369 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Chris Lattner686767f2003-10-30 00:46:41 +000010370 InsertNewInstBefore(NC, *I);
10371 } else {
10372 // Otherwise, it's a call, just insert cast right after the call instr
10373 InsertNewInstBefore(NC, *Caller);
10374 }
Chris Lattner51ea1272004-02-28 05:22:00 +000010375 AddUsersToWorkList(*Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +000010376 } else {
Owen Andersonb5618da2009-07-03 00:17:18 +000010377 NV = Context->getUndef(Caller->getType());
Chris Lattner970c33a2003-06-19 17:00:31 +000010378 }
10379 }
10380
10381 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10382 Caller->replaceAllUsesWith(NV);
Chris Lattner51f54572007-03-02 19:59:19 +000010383 Caller->eraseFromParent();
Chris Lattnerb15e2b12007-03-02 21:28:56 +000010384 RemoveFromWorkList(Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +000010385 return true;
10386}
10387
Duncan Sands6d5da712007-09-17 10:26:40 +000010388// transformCallThroughTrampoline - Turn a call to a function created by the
10389// init_trampoline intrinsic into a direct call to the underlying function.
10390//
10391Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10392 Value *Callee = CS.getCalledValue();
10393 const PointerType *PTy = cast<PointerType>(Callee->getType());
10394 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Devang Patel4c758ea2008-09-25 21:00:45 +000010395 const AttrListPtr &Attrs = CS.getAttributes();
Duncan Sandsb5ca2e92008-01-14 19:52:09 +000010396
10397 // If the call already has the 'nest' attribute somewhere then give up -
10398 // otherwise 'nest' would occur twice after splicing in the chain.
Devang Patel4c758ea2008-09-25 21:00:45 +000010399 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Duncan Sandsb5ca2e92008-01-14 19:52:09 +000010400 return 0;
Duncan Sands6d5da712007-09-17 10:26:40 +000010401
10402 IntrinsicInst *Tramp =
10403 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10404
Anton Korobeynikovfc2edad2008-05-07 22:54:15 +000010405 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sands6d5da712007-09-17 10:26:40 +000010406 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10407 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10408
Devang Patel4c758ea2008-09-25 21:00:45 +000010409 const AttrListPtr &NestAttrs = NestF->getAttributes();
Chris Lattner8a923e72008-03-12 17:45:29 +000010410 if (!NestAttrs.isEmpty()) {
Duncan Sands6d5da712007-09-17 10:26:40 +000010411 unsigned NestIdx = 1;
10412 const Type *NestTy = 0;
Devang Patel4c758ea2008-09-25 21:00:45 +000010413 Attributes NestAttr = Attribute::None;
Duncan Sands6d5da712007-09-17 10:26:40 +000010414
10415 // Look for a parameter marked with the 'nest' attribute.
10416 for (FunctionType::param_iterator I = NestFTy->param_begin(),
10417 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Devang Patel4c758ea2008-09-25 21:00:45 +000010418 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
Duncan Sands6d5da712007-09-17 10:26:40 +000010419 // Record the parameter type and any other attributes.
10420 NestTy = *I;
Devang Patela05633e2008-09-26 22:53:05 +000010421 NestAttr = NestAttrs.getParamAttributes(NestIdx);
Duncan Sands6d5da712007-09-17 10:26:40 +000010422 break;
10423 }
10424
10425 if (NestTy) {
10426 Instruction *Caller = CS.getInstruction();
10427 std::vector<Value*> NewArgs;
10428 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10429
Devang Patel4c758ea2008-09-25 21:00:45 +000010430 SmallVector<AttributeWithIndex, 8> NewAttrs;
Chris Lattner8a923e72008-03-12 17:45:29 +000010431 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sandsb5ca2e92008-01-14 19:52:09 +000010432
Duncan Sands6d5da712007-09-17 10:26:40 +000010433 // Insert the nest argument into the call argument list, which may
Duncan Sandsb5ca2e92008-01-14 19:52:09 +000010434 // mean appending it. Likewise for attributes.
10435
Devang Patela05633e2008-09-26 22:53:05 +000010436 // Add any result attributes.
10437 if (Attributes Attr = Attrs.getRetAttributes())
Devang Patel4c758ea2008-09-25 21:00:45 +000010438 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
Duncan Sandsb5ca2e92008-01-14 19:52:09 +000010439
Duncan Sands6d5da712007-09-17 10:26:40 +000010440 {
10441 unsigned Idx = 1;
10442 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10443 do {
10444 if (Idx == NestIdx) {
Duncan Sandsb5ca2e92008-01-14 19:52:09 +000010445 // Add the chain argument and attributes.
Duncan Sands6d5da712007-09-17 10:26:40 +000010446 Value *NestVal = Tramp->getOperand(3);
10447 if (NestVal->getType() != NestTy)
10448 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10449 NewArgs.push_back(NestVal);
Devang Patel4c758ea2008-09-25 21:00:45 +000010450 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
Duncan Sands6d5da712007-09-17 10:26:40 +000010451 }
10452
10453 if (I == E)
10454 break;
10455
Duncan Sandsb5ca2e92008-01-14 19:52:09 +000010456 // Add the original argument and attributes.
Duncan Sands6d5da712007-09-17 10:26:40 +000010457 NewArgs.push_back(*I);
Devang Patela05633e2008-09-26 22:53:05 +000010458 if (Attributes Attr = Attrs.getParamAttributes(Idx))
Duncan Sandsb5ca2e92008-01-14 19:52:09 +000010459 NewAttrs.push_back
Devang Patel4c758ea2008-09-25 21:00:45 +000010460 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sands6d5da712007-09-17 10:26:40 +000010461
10462 ++Idx, ++I;
10463 } while (1);
10464 }
10465
Devang Patela05633e2008-09-26 22:53:05 +000010466 // Add any function attributes.
10467 if (Attributes Attr = Attrs.getFnAttributes())
10468 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10469
Duncan Sands6d5da712007-09-17 10:26:40 +000010470 // The trampoline may have been bitcast to a bogus type (FTy).
10471 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sandsb5ca2e92008-01-14 19:52:09 +000010472 // with the chain parameter inserted.
Duncan Sands6d5da712007-09-17 10:26:40 +000010473
Duncan Sands6d5da712007-09-17 10:26:40 +000010474 std::vector<const Type*> NewTypes;
Duncan Sands6d5da712007-09-17 10:26:40 +000010475 NewTypes.reserve(FTy->getNumParams()+1);
10476
Duncan Sands6d5da712007-09-17 10:26:40 +000010477 // Insert the chain's type into the list of parameter types, which may
Duncan Sandsb5ca2e92008-01-14 19:52:09 +000010478 // mean appending it.
Duncan Sands6d5da712007-09-17 10:26:40 +000010479 {
10480 unsigned Idx = 1;
10481 FunctionType::param_iterator I = FTy->param_begin(),
10482 E = FTy->param_end();
10483
10484 do {
Duncan Sandsb5ca2e92008-01-14 19:52:09 +000010485 if (Idx == NestIdx)
10486 // Add the chain's type.
Duncan Sands6d5da712007-09-17 10:26:40 +000010487 NewTypes.push_back(NestTy);
Duncan Sands6d5da712007-09-17 10:26:40 +000010488
10489 if (I == E)
10490 break;
10491
Duncan Sandsb5ca2e92008-01-14 19:52:09 +000010492 // Add the original type.
Duncan Sands6d5da712007-09-17 10:26:40 +000010493 NewTypes.push_back(*I);
Duncan Sands6d5da712007-09-17 10:26:40 +000010494
10495 ++Idx, ++I;
10496 } while (1);
10497 }
10498
10499 // Replace the trampoline call with a direct call. Let the generic
10500 // code sort out any function type mismatches.
10501 FunctionType *NewFTy =
Owen Andersonb5618da2009-07-03 00:17:18 +000010502 Context->getFunctionType(FTy->getReturnType(), NewTypes,
10503 FTy->isVarArg());
10504 Constant *NewCallee =
10505 NestF->getType() == Context->getPointerTypeUnqual(NewFTy) ?
10506 NestF : Context->getConstantExprBitCast(NestF,
10507 Context->getPointerTypeUnqual(NewFTy));
Devang Patel4c758ea2008-09-25 21:00:45 +000010508 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),NewAttrs.end());
Duncan Sands6d5da712007-09-17 10:26:40 +000010509
10510 Instruction *NewCaller;
10511 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greife9ecc682008-04-06 20:25:17 +000010512 NewCaller = InvokeInst::Create(NewCallee,
10513 II->getNormalDest(), II->getUnwindDest(),
10514 NewArgs.begin(), NewArgs.end(),
10515 Caller->getName(), Caller);
Duncan Sands6d5da712007-09-17 10:26:40 +000010516 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Devang Patel4c758ea2008-09-25 21:00:45 +000010517 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sands6d5da712007-09-17 10:26:40 +000010518 } else {
Gabor Greife9ecc682008-04-06 20:25:17 +000010519 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10520 Caller->getName(), Caller);
Duncan Sands6d5da712007-09-17 10:26:40 +000010521 if (cast<CallInst>(Caller)->isTailCall())
10522 cast<CallInst>(NewCaller)->setTailCall();
10523 cast<CallInst>(NewCaller)->
10524 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Devang Patel4c758ea2008-09-25 21:00:45 +000010525 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sands6d5da712007-09-17 10:26:40 +000010526 }
10527 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10528 Caller->replaceAllUsesWith(NewCaller);
10529 Caller->eraseFromParent();
10530 RemoveFromWorkList(Caller);
10531 return 0;
10532 }
10533 }
10534
10535 // Replace the trampoline call with a direct call. Since there is no 'nest'
10536 // parameter, there is no need to adjust the argument list. Let the generic
10537 // code sort out any function type mismatches.
10538 Constant *NewCallee =
Owen Andersonb5618da2009-07-03 00:17:18 +000010539 NestF->getType() == PTy ? NestF :
10540 Context->getConstantExprBitCast(NestF, PTy);
Duncan Sands6d5da712007-09-17 10:26:40 +000010541 CS.setCalledFunction(NewCallee);
10542 return CS.getInstruction();
10543}
10544
Chris Lattnercadac0c2006-11-01 04:51:18 +000010545/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
10546/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
10547/// and a single binop.
10548Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10549 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Chris Lattner084b3a42008-12-01 03:42:51 +000010550 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
Chris Lattnercadac0c2006-11-01 04:51:18 +000010551 unsigned Opc = FirstInst->getOpcode();
Chris Lattnercd62f112006-11-08 19:29:23 +000010552 Value *LHSVal = FirstInst->getOperand(0);
10553 Value *RHSVal = FirstInst->getOperand(1);
10554
10555 const Type *LHSType = LHSVal->getType();
10556 const Type *RHSType = RHSVal->getType();
Chris Lattnercadac0c2006-11-01 04:51:18 +000010557
10558 // Scan to see if all operands are the same opcode, all have one use, and all
10559 // kill their operands (i.e. the operands have one use).
Chris Lattner9d02a702008-12-01 02:34:36 +000010560 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
Chris Lattnercadac0c2006-11-01 04:51:18 +000010561 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnerdc826fc2006-11-01 04:55:47 +000010562 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencer266e42b2006-12-23 06:05:41 +000010563 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattnereebea432006-11-01 07:43:41 +000010564 // types or GEP's with different index types.
10565 I->getOperand(0)->getType() != LHSType ||
10566 I->getOperand(1)->getType() != RHSType)
Chris Lattnercadac0c2006-11-01 04:51:18 +000010567 return 0;
Reid Spencer266e42b2006-12-23 06:05:41 +000010568
10569 // If they are CmpInst instructions, check their predicates
10570 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10571 if (cast<CmpInst>(I)->getPredicate() !=
10572 cast<CmpInst>(FirstInst)->getPredicate())
10573 return 0;
Chris Lattnercd62f112006-11-08 19:29:23 +000010574
10575 // Keep track of which operand needs a phi node.
10576 if (I->getOperand(0) != LHSVal) LHSVal = 0;
10577 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattnercadac0c2006-11-01 04:51:18 +000010578 }
10579
Chris Lattner084b3a42008-12-01 03:42:51 +000010580 // Otherwise, this is safe to transform!
Chris Lattner4f218d52006-11-08 19:42:28 +000010581
Chris Lattnercadac0c2006-11-01 04:51:18 +000010582 Value *InLHS = FirstInst->getOperand(0);
Chris Lattnercadac0c2006-11-01 04:51:18 +000010583 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner4f218d52006-11-08 19:42:28 +000010584 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnercd62f112006-11-08 19:29:23 +000010585 if (LHSVal == 0) {
Gabor Greif697e94c2008-05-15 10:04:30 +000010586 NewLHS = PHINode::Create(LHSType,
10587 FirstInst->getOperand(0)->getName() + ".pn");
Chris Lattnercd62f112006-11-08 19:29:23 +000010588 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10589 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattnereebea432006-11-01 07:43:41 +000010590 InsertNewInstBefore(NewLHS, PN);
10591 LHSVal = NewLHS;
10592 }
Chris Lattnercd62f112006-11-08 19:29:23 +000010593
10594 if (RHSVal == 0) {
Gabor Greif697e94c2008-05-15 10:04:30 +000010595 NewRHS = PHINode::Create(RHSType,
10596 FirstInst->getOperand(1)->getName() + ".pn");
Chris Lattnercd62f112006-11-08 19:29:23 +000010597 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10598 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattnereebea432006-11-01 07:43:41 +000010599 InsertNewInstBefore(NewRHS, PN);
10600 RHSVal = NewRHS;
10601 }
10602
Chris Lattnercd62f112006-11-08 19:29:23 +000010603 // Add all operands to the new PHIs.
Chris Lattner9d02a702008-12-01 02:34:36 +000010604 if (NewLHS || NewRHS) {
10605 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10606 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10607 if (NewLHS) {
10608 Value *NewInLHS = InInst->getOperand(0);
10609 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10610 }
10611 if (NewRHS) {
10612 Value *NewInRHS = InInst->getOperand(1);
10613 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10614 }
Chris Lattnercd62f112006-11-08 19:29:23 +000010615 }
10616 }
10617
Chris Lattnercadac0c2006-11-01 04:51:18 +000010618 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greife1f6e4b2008-05-16 19:29:10 +000010619 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Chris Lattner084b3a42008-12-01 03:42:51 +000010620 CmpInst *CIOp = cast<CmpInst>(FirstInst);
Owen Anderson1e5f00e2009-07-09 23:48:35 +000010621 return CmpInst::Create(*Context, CIOp->getOpcode(), CIOp->getPredicate(),
10622 LHSVal, RHSVal);
Chris Lattnercadac0c2006-11-01 04:51:18 +000010623}
10624
Chris Lattner9d02a702008-12-01 02:34:36 +000010625Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10626 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10627
10628 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
10629 FirstInst->op_end());
Chris Lattnerbef6b202009-02-21 00:46:50 +000010630 // This is true if all GEP bases are allocas and if all indices into them are
10631 // constants.
10632 bool AllBasePointersAreAllocas = true;
Chris Lattner9d02a702008-12-01 02:34:36 +000010633
10634 // Scan to see if all operands are the same opcode, all have one use, and all
10635 // kill their operands (i.e. the operands have one use).
10636 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10637 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10638 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10639 GEP->getNumOperands() != FirstInst->getNumOperands())
10640 return 0;
10641
Chris Lattnerbef6b202009-02-21 00:46:50 +000010642 // Keep track of whether or not all GEPs are of alloca pointers.
10643 if (AllBasePointersAreAllocas &&
10644 (!isa<AllocaInst>(GEP->getOperand(0)) ||
10645 !GEP->hasAllConstantIndices()))
10646 AllBasePointersAreAllocas = false;
10647
Chris Lattner9d02a702008-12-01 02:34:36 +000010648 // Compare the operand lists.
10649 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10650 if (FirstInst->getOperand(op) == GEP->getOperand(op))
10651 continue;
10652
10653 // Don't merge two GEPs when two operands differ (introducing phi nodes)
10654 // if one of the PHIs has a constant for the index. The index may be
10655 // substantially cheaper to compute for the constants, so making it a
10656 // variable index could pessimize the path. This also handles the case
10657 // for struct indices, which must always be constant.
10658 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10659 isa<ConstantInt>(GEP->getOperand(op)))
10660 return 0;
10661
10662 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10663 return 0;
10664 FixedOperands[op] = 0; // Needs a PHI.
10665 }
10666 }
10667
Chris Lattnerbef6b202009-02-21 00:46:50 +000010668 // If all of the base pointers of the PHI'd GEPs are from allocas, don't
Chris Lattnerd5420f02009-02-23 05:56:17 +000010669 // bother doing this transformation. At best, this will just save a bit of
Chris Lattnerbef6b202009-02-21 00:46:50 +000010670 // offset calculation, but all the predecessors will have to materialize the
10671 // stack address into a register anyway. We'd actually rather *clone* the
10672 // load up into the predecessors so that we have a load of a gep of an alloca,
10673 // which can usually all be folded into the load.
10674 if (AllBasePointersAreAllocas)
10675 return 0;
10676
Chris Lattner9d02a702008-12-01 02:34:36 +000010677 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
10678 // that is variable.
10679 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10680
10681 bool HasAnyPHIs = false;
10682 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10683 if (FixedOperands[i]) continue; // operand doesn't need a phi.
10684 Value *FirstOp = FirstInst->getOperand(i);
10685 PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10686 FirstOp->getName()+".pn");
10687 InsertNewInstBefore(NewPN, PN);
10688
10689 NewPN->reserveOperandSpace(e);
10690 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10691 OperandPhis[i] = NewPN;
10692 FixedOperands[i] = NewPN;
10693 HasAnyPHIs = true;
10694 }
10695
10696
10697 // Add all operands to the new PHIs.
10698 if (HasAnyPHIs) {
10699 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10700 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10701 BasicBlock *InBB = PN.getIncomingBlock(i);
10702
10703 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10704 if (PHINode *OpPhi = OperandPhis[op])
10705 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10706 }
10707 }
10708
10709 Value *Base = FixedOperands[0];
10710 return GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10711 FixedOperands.end());
10712}
10713
10714
Chris Lattnerd5420f02009-02-23 05:56:17 +000010715/// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10716/// sink the load out of the block that defines it. This means that it must be
Chris Lattnerbef6b202009-02-21 00:46:50 +000010717/// obvious the value of the load is not changed from the point of the load to
10718/// the end of the block it is in.
Chris Lattnerc9042052007-02-01 22:30:07 +000010719///
10720/// Finally, it is safe, but not profitable, to sink a load targetting a
10721/// non-address-taken alloca. Doing so will cause us to not promote the alloca
10722/// to a register.
Chris Lattnerbef6b202009-02-21 00:46:50 +000010723static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
Chris Lattner14f82c72006-11-01 07:13:54 +000010724 BasicBlock::iterator BBI = L, E = L->getParent()->end();
10725
10726 for (++BBI; BBI != E; ++BBI)
10727 if (BBI->mayWriteToMemory())
10728 return false;
Chris Lattnerc9042052007-02-01 22:30:07 +000010729
10730 // Check for non-address taken alloca. If not address-taken already, it isn't
10731 // profitable to do this xform.
10732 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10733 bool isAddressTaken = false;
10734 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10735 UI != E; ++UI) {
10736 if (isa<LoadInst>(UI)) continue;
10737 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10738 // If storing TO the alloca, then the address isn't taken.
10739 if (SI->getOperand(1) == AI) continue;
10740 }
10741 isAddressTaken = true;
10742 break;
10743 }
10744
Chris Lattnerbef6b202009-02-21 00:46:50 +000010745 if (!isAddressTaken && AI->isStaticAlloca())
Chris Lattnerc9042052007-02-01 22:30:07 +000010746 return false;
10747 }
10748
Chris Lattnerbef6b202009-02-21 00:46:50 +000010749 // If this load is a load from a GEP with a constant offset from an alloca,
10750 // then we don't want to sink it. In its present form, it will be
10751 // load [constant stack offset]. Sinking it will cause us to have to
10752 // materialize the stack addresses in each predecessor in a register only to
10753 // do a shared load from register in the successor.
10754 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10755 if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10756 if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10757 return false;
10758
Chris Lattner14f82c72006-11-01 07:13:54 +000010759 return true;
10760}
10761
Chris Lattner970c33a2003-06-19 17:00:31 +000010762
Chris Lattner7515cab2004-11-14 19:13:23 +000010763// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10764// operator and they all are only used by the PHI, PHI together their
10765// inputs, and do the operation once, to the result of the PHI.
10766Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10767 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10768
10769 // Scan the instruction, looking for input operations that can be folded away.
10770 // If all input operands to the phi are the same instruction (e.g. a cast from
10771 // the same type or "+42") we can pull the operation through the PHI, reducing
10772 // code size and simplifying code.
10773 Constant *ConstantOp = 0;
10774 const Type *CastSrcTy = 0;
Chris Lattner14f82c72006-11-01 07:13:54 +000010775 bool isVolatile = false;
Chris Lattner7515cab2004-11-14 19:13:23 +000010776 if (isa<CastInst>(FirstInst)) {
10777 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer2341c222007-02-02 02:16:23 +000010778 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencer266e42b2006-12-23 06:05:41 +000010779 // Can fold binop, compare or shift here if the RHS is a constant,
10780 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattner7515cab2004-11-14 19:13:23 +000010781 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattnercadac0c2006-11-01 04:51:18 +000010782 if (ConstantOp == 0)
10783 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner14f82c72006-11-01 07:13:54 +000010784 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10785 isVolatile = LI->isVolatile();
10786 // We can't sink the load if the loaded value could be modified between the
10787 // load and the PHI.
10788 if (LI->getParent() != PN.getIncomingBlock(0) ||
Chris Lattnerbef6b202009-02-21 00:46:50 +000010789 !isSafeAndProfitableToSinkLoad(LI))
Chris Lattner14f82c72006-11-01 07:13:54 +000010790 return 0;
Chris Lattner501d78f2008-07-08 17:18:32 +000010791
10792 // If the PHI is of volatile loads and the load block has multiple
10793 // successors, sinking it would remove a load of the volatile value from
10794 // the path through the other successor.
10795 if (isVolatile &&
10796 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10797 return 0;
10798
Chris Lattnereebea432006-11-01 07:43:41 +000010799 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner9d02a702008-12-01 02:34:36 +000010800 return FoldPHIArgGEPIntoPHI(PN);
Chris Lattner7515cab2004-11-14 19:13:23 +000010801 } else {
10802 return 0; // Cannot fold this operation.
10803 }
10804
10805 // Check to see if all arguments are the same operation.
10806 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10807 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10808 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencer266e42b2006-12-23 06:05:41 +000010809 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattner7515cab2004-11-14 19:13:23 +000010810 return 0;
10811 if (CastSrcTy) {
10812 if (I->getOperand(0)->getType() != CastSrcTy)
10813 return 0; // Cast operation must match.
Chris Lattner14f82c72006-11-01 07:13:54 +000010814 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencer266e42b2006-12-23 06:05:41 +000010815 // We can't sink the load if the loaded value could be modified between
10816 // the load and the PHI.
Chris Lattner14f82c72006-11-01 07:13:54 +000010817 if (LI->isVolatile() != isVolatile ||
10818 LI->getParent() != PN.getIncomingBlock(i) ||
Chris Lattnerbef6b202009-02-21 00:46:50 +000010819 !isSafeAndProfitableToSinkLoad(LI))
Chris Lattner14f82c72006-11-01 07:13:54 +000010820 return 0;
Chris Lattnerd9e3b5c2008-04-29 17:28:22 +000010821
Chris Lattner501d78f2008-07-08 17:18:32 +000010822 // If the PHI is of volatile loads and the load block has multiple
10823 // successors, sinking it would remove a load of the volatile value from
10824 // the path through the other successor.
Chris Lattnerd9e3b5c2008-04-29 17:28:22 +000010825 if (isVolatile &&
10826 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10827 return 0;
Chris Lattnerd9e3b5c2008-04-29 17:28:22 +000010828
Chris Lattner7515cab2004-11-14 19:13:23 +000010829 } else if (I->getOperand(1) != ConstantOp) {
10830 return 0;
10831 }
10832 }
10833
10834 // Okay, they are all the same operation. Create a new PHI node of the
10835 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greife9ecc682008-04-06 20:25:17 +000010836 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10837 PN.getName()+".in");
Chris Lattnerd8e20182005-01-29 00:39:08 +000010838 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattner46dd5a62004-11-14 19:29:34 +000010839
10840 Value *InVal = FirstInst->getOperand(0);
10841 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattner7515cab2004-11-14 19:13:23 +000010842
10843 // Add all operands to the new PHI.
Chris Lattner46dd5a62004-11-14 19:29:34 +000010844 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10845 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10846 if (NewInVal != InVal)
10847 InVal = 0;
10848 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10849 }
10850
10851 Value *PhiVal;
10852 if (InVal) {
10853 // The new PHI unions all of the same values together. This is really
10854 // common, so we handle it intelligently here for compile-time speed.
10855 PhiVal = InVal;
10856 delete NewPN;
10857 } else {
10858 InsertNewInstBefore(NewPN, PN);
10859 PhiVal = NewPN;
10860 }
Misha Brukmanb1c93172005-04-21 23:48:37 +000010861
Chris Lattner7515cab2004-11-14 19:13:23 +000010862 // Insert and return the new operation.
Reid Spencer6c38f0b2006-11-27 01:05:10 +000010863 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greife1f6e4b2008-05-16 19:29:10 +000010864 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattner9233c122008-04-29 17:13:43 +000010865 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greife1f6e4b2008-05-16 19:29:10 +000010866 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner9233c122008-04-29 17:13:43 +000010867 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Owen Anderson1e5f00e2009-07-09 23:48:35 +000010868 return CmpInst::Create(*Context, CIOp->getOpcode(), CIOp->getPredicate(),
Reid Spencer266e42b2006-12-23 06:05:41 +000010869 PhiVal, ConstantOp);
Chris Lattner9233c122008-04-29 17:13:43 +000010870 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10871
10872 // If this was a volatile load that we are merging, make sure to loop through
10873 // and mark all the input loads as non-volatile. If we don't do this, we will
10874 // insert a new volatile load and the old ones will not be deletable.
10875 if (isVolatile)
10876 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10877 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10878
10879 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattner7515cab2004-11-14 19:13:23 +000010880}
Chris Lattner48a44f72002-05-02 17:06:02 +000010881
Chris Lattner71536432005-01-17 05:10:15 +000010882/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10883/// that is dead.
Chris Lattnerd2602d52007-03-26 20:40:50 +000010884static bool DeadPHICycle(PHINode *PN,
10885 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattner71536432005-01-17 05:10:15 +000010886 if (PN->use_empty()) return true;
10887 if (!PN->hasOneUse()) return false;
10888
10889 // Remember this node, and if we find the cycle, return.
Chris Lattnerd2602d52007-03-26 20:40:50 +000010890 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattner71536432005-01-17 05:10:15 +000010891 return true;
Chris Lattner0e258b82007-08-28 04:23:55 +000010892
10893 // Don't scan crazily complex things.
10894 if (PotentiallyDeadPHIs.size() == 16)
10895 return false;
Chris Lattner71536432005-01-17 05:10:15 +000010896
10897 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10898 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanb1c93172005-04-21 23:48:37 +000010899
Chris Lattner71536432005-01-17 05:10:15 +000010900 return false;
10901}
10902
Chris Lattnerd8515f82007-11-06 21:52:06 +000010903/// PHIsEqualValue - Return true if this phi node is always equal to
10904/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
10905/// z = some value; x = phi (y, z); y = phi (x, z)
10906static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
10907 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10908 // See if we already saw this PHI node.
10909 if (!ValueEqualPHIs.insert(PN))
10910 return true;
10911
10912 // Don't scan crazily complex things.
10913 if (ValueEqualPHIs.size() == 16)
10914 return false;
10915
10916 // Scan the operands to see if they are either phi nodes or are equal to
10917 // the value.
10918 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10919 Value *Op = PN->getIncomingValue(i);
10920 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10921 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10922 return false;
10923 } else if (Op != NonPhiInVal)
10924 return false;
10925 }
10926
10927 return true;
10928}
10929
10930
Chris Lattnerbbbdd852002-05-06 18:06:38 +000010931// PHINode simplification
10932//
Chris Lattner113f4f42002-06-25 16:13:24 +000010933Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonbbf89902006-07-10 22:15:25 +000010934 // If LCSSA is around, don't mess with Phi nodes
Chris Lattner8258b442007-03-04 04:27:24 +000010935 if (MustPreserveLCSSA) return 0;
Owen Andersona6968f82006-07-10 19:03:49 +000010936
Owen Andersonae8aa642006-07-10 22:03:18 +000010937 if (Value *V = PN.hasConstantValue())
10938 return ReplaceInstUsesWith(PN, V);
10939
Owen Andersonae8aa642006-07-10 22:03:18 +000010940 // If all PHI operands are the same operation, pull them through the PHI,
10941 // reducing code size.
10942 if (isa<Instruction>(PN.getIncomingValue(0)) &&
Chris Lattner9d02a702008-12-01 02:34:36 +000010943 isa<Instruction>(PN.getIncomingValue(1)) &&
10944 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10945 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10946 // FIXME: The hasOneUse check will fail for PHIs that use the value more
10947 // than themselves more than once.
Owen Andersonae8aa642006-07-10 22:03:18 +000010948 PN.getIncomingValue(0)->hasOneUse())
10949 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10950 return Result;
10951
10952 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
10953 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10954 // PHI)... break the cycle.
Chris Lattnerc8dcede2007-01-15 07:30:06 +000010955 if (PN.hasOneUse()) {
10956 Instruction *PHIUser = cast<Instruction>(PN.use_back());
10957 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattnerd2602d52007-03-26 20:40:50 +000010958 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Andersonae8aa642006-07-10 22:03:18 +000010959 PotentiallyDeadPHIs.insert(&PN);
10960 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
Owen Andersonb5618da2009-07-03 00:17:18 +000010961 return ReplaceInstUsesWith(PN, Context->getUndef(PN.getType()));
Owen Andersonae8aa642006-07-10 22:03:18 +000010962 }
Chris Lattnerc8dcede2007-01-15 07:30:06 +000010963
10964 // If this phi has a single use, and if that use just computes a value for
10965 // the next iteration of a loop, delete the phi. This occurs with unused
10966 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
10967 // common case here is good because the only other things that catch this
10968 // are induction variable analysis (sometimes) and ADCE, which is only run
10969 // late.
10970 if (PHIUser->hasOneUse() &&
10971 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10972 PHIUser->use_back() == &PN) {
Owen Andersonb5618da2009-07-03 00:17:18 +000010973 return ReplaceInstUsesWith(PN, Context->getUndef(PN.getType()));
Chris Lattnerc8dcede2007-01-15 07:30:06 +000010974 }
10975 }
Owen Andersonae8aa642006-07-10 22:03:18 +000010976
Chris Lattnerd8515f82007-11-06 21:52:06 +000010977 // We sometimes end up with phi cycles that non-obviously end up being the
10978 // same value, for example:
10979 // z = some value; x = phi (y, z); y = phi (x, z)
10980 // where the phi nodes don't necessarily need to be in the same block. Do a
10981 // quick check to see if the PHI node only contains a single non-phi value, if
10982 // so, scan to see if the phi cycle is actually equal to that value.
10983 {
10984 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10985 // Scan for the first non-phi operand.
10986 while (InValNo != NumOperandVals &&
10987 isa<PHINode>(PN.getIncomingValue(InValNo)))
10988 ++InValNo;
10989
10990 if (InValNo != NumOperandVals) {
10991 Value *NonPhiInVal = PN.getOperand(InValNo);
10992
10993 // Scan the rest of the operands to see if there are any conflicts, if so
10994 // there is no need to recursively scan other phis.
10995 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10996 Value *OpVal = PN.getIncomingValue(InValNo);
10997 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10998 break;
10999 }
11000
11001 // If we scanned over all operands, then we have one unique value plus
11002 // phi values. Scan PHI nodes to see if they all merge in each other or
11003 // the value.
11004 if (InValNo == NumOperandVals) {
11005 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
11006 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
11007 return ReplaceInstUsesWith(PN, NonPhiInVal);
11008 }
11009 }
11010 }
Chris Lattner91daeb52003-12-19 05:58:40 +000011011 return 0;
Chris Lattnerbbbdd852002-05-06 18:06:38 +000011012}
11013
Reid Spencer13bc5d72006-12-12 09:18:51 +000011014static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
11015 Instruction *InsertPoint,
11016 InstCombiner *IC) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +000011017 unsigned PtrSize = DTy->getScalarSizeInBits();
11018 unsigned VTySize = V->getType()->getScalarSizeInBits();
Reid Spencer13bc5d72006-12-12 09:18:51 +000011019 // We must cast correctly to the pointer type. Ensure that we
11020 // sign extend the integer value if it is smaller as this is
11021 // used for address computation.
11022 Instruction::CastOps opcode =
11023 (VTySize < PtrSize ? Instruction::SExt :
11024 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
11025 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
Chris Lattner69193f92004-04-05 01:30:19 +000011026}
11027
Chris Lattner48a44f72002-05-02 17:06:02 +000011028
Chris Lattner113f4f42002-06-25 16:13:24 +000011029Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner5f667a62004-05-07 22:09:22 +000011030 Value *PtrOp = GEP.getOperand(0);
Chris Lattneracbf6a42007-04-28 00:57:34 +000011031 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
Chris Lattner113f4f42002-06-25 16:13:24 +000011032 // If so, eliminate the noop.
Chris Lattner8d0bacb2004-02-22 05:25:17 +000011033 if (GEP.getNumOperands() == 1)
Chris Lattner5f667a62004-05-07 22:09:22 +000011034 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner8d0bacb2004-02-22 05:25:17 +000011035
Chris Lattner81a7a232004-10-16 18:11:37 +000011036 if (isa<UndefValue>(GEP.getOperand(0)))
Owen Andersonb5618da2009-07-03 00:17:18 +000011037 return ReplaceInstUsesWith(GEP, Context->getUndef(GEP.getType()));
Chris Lattner81a7a232004-10-16 18:11:37 +000011038
Chris Lattner8d0bacb2004-02-22 05:25:17 +000011039 bool HasZeroPointerIndex = false;
11040 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
11041 HasZeroPointerIndex = C->isNullValue();
11042
11043 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner5f667a62004-05-07 22:09:22 +000011044 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner48a44f72002-05-02 17:06:02 +000011045
Chris Lattner69193f92004-04-05 01:30:19 +000011046 // Eliminate unneeded casts for indices.
11047 bool MadeChange = false;
Chris Lattner9bf53ff2007-03-25 20:43:09 +000011048
Chris Lattner2b2412d2004-04-07 18:38:20 +000011049 gep_type_iterator GTI = gep_type_begin(GEP);
Gabor Greiff6d8e772008-06-12 21:37:33 +000011050 for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end();
11051 i != e; ++i, ++GTI) {
Sanjiv Gupta46c97e62009-04-24 02:37:54 +000011052 if (isa<SequentialType>(*GTI)) {
Gabor Greiff6d8e772008-06-12 21:37:33 +000011053 if (CastInst *CI = dyn_cast<CastInst>(*i)) {
Chris Lattner27df1db2007-01-15 07:02:54 +000011054 if (CI->getOpcode() == Instruction::ZExt ||
11055 CI->getOpcode() == Instruction::SExt) {
11056 const Type *SrcTy = CI->getOperand(0)->getType();
11057 // We can eliminate a cast from i32 to i64 iff the target
11058 // is a 32-bit pointer target.
Dan Gohman7ccc52f2009-06-15 22:12:54 +000011059 if (SrcTy->getScalarSizeInBits() >= TD->getPointerSizeInBits()) {
Chris Lattner27df1db2007-01-15 07:02:54 +000011060 MadeChange = true;
Gabor Greiff6d8e772008-06-12 21:37:33 +000011061 *i = CI->getOperand(0);
Chris Lattner69193f92004-04-05 01:30:19 +000011062 }
11063 }
11064 }
Chris Lattner2b2412d2004-04-07 18:38:20 +000011065 // If we are using a wider index than needed for this platform, shrink it
Dan Gohmaneff71f22008-09-11 23:06:38 +000011066 // to what we need. If narrower, sign-extend it to what we need.
11067 // If the incoming value needs a cast instruction,
Chris Lattner2b2412d2004-04-07 18:38:20 +000011068 // insert it. This explicit cast can make subsequent optimizations more
11069 // obvious.
Gabor Greiff6d8e772008-06-12 21:37:33 +000011070 Value *Op = *i;
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +000011071 if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
Chris Lattner1e9ac1a2004-04-17 18:16:10 +000011072 if (Constant *C = dyn_cast<Constant>(Op)) {
Owen Andersonb5618da2009-07-03 00:17:18 +000011073 *i = Context->getConstantExprTrunc(C, TD->getIntPtrType());
Chris Lattner1e9ac1a2004-04-17 18:16:10 +000011074 MadeChange = true;
11075 } else {
Reid Spencer13bc5d72006-12-12 09:18:51 +000011076 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
11077 GEP);
Gabor Greiff6d8e772008-06-12 21:37:33 +000011078 *i = Op;
Chris Lattner2b2412d2004-04-07 18:38:20 +000011079 MadeChange = true;
11080 }
Dan Gohmaneff71f22008-09-11 23:06:38 +000011081 } else if (TD->getTypeSizeInBits(Op->getType()) < TD->getPointerSizeInBits()) {
11082 if (Constant *C = dyn_cast<Constant>(Op)) {
Owen Andersonb5618da2009-07-03 00:17:18 +000011083 *i = Context->getConstantExprSExt(C, TD->getIntPtrType());
Dan Gohmaneff71f22008-09-11 23:06:38 +000011084 MadeChange = true;
11085 } else {
11086 Op = InsertCastBefore(Instruction::SExt, Op, TD->getIntPtrType(),
11087 GEP);
11088 *i = Op;
11089 MadeChange = true;
11090 }
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +000011091 }
Chris Lattner69193f92004-04-05 01:30:19 +000011092 }
Chris Lattner9bf53ff2007-03-25 20:43:09 +000011093 }
Chris Lattner69193f92004-04-05 01:30:19 +000011094 if (MadeChange) return &GEP;
11095
Chris Lattnerae7a0d32002-08-02 19:29:35 +000011096 // Combine Indices - If the source pointer to this getelementptr instruction
11097 // is a getelementptr instruction, combine the indices of the two
11098 // getelementptr instructions into a single instruction.
11099 //
Chris Lattneraf6094f2007-02-15 22:48:32 +000011100 SmallVector<Value*, 8> SrcGEPOperands;
Chris Lattner0798af32005-01-13 20:14:25 +000011101 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattneraf6094f2007-02-15 22:48:32 +000011102 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
Chris Lattner57c67b02004-03-25 22:59:29 +000011103
11104 if (!SrcGEPOperands.empty()) {
Chris Lattner5f667a62004-05-07 22:09:22 +000011105 // Note that if our source is a gep chain itself that we wait for that
11106 // chain to be resolved before we perform this transformation. This
11107 // avoids us creating a TON of code in some cases.
11108 //
11109 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
11110 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
11111 return 0; // Wait until our source is folded to completion.
11112
Chris Lattneraf6094f2007-02-15 22:48:32 +000011113 SmallVector<Value*, 8> Indices;
Chris Lattner5f667a62004-05-07 22:09:22 +000011114
11115 // Find out whether the last index in the source GEP is a sequential idx.
11116 bool EndsWithSequential = false;
11117 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
11118 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattner8ec5f882004-05-08 22:41:42 +000011119 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanb1c93172005-04-21 23:48:37 +000011120
Chris Lattnerae7a0d32002-08-02 19:29:35 +000011121 // Can we combine the two pointer arithmetics offsets?
Chris Lattner5f667a62004-05-07 22:09:22 +000011122 if (EndsWithSequential) {
Chris Lattner235af562003-03-05 22:33:14 +000011123 // Replace: gep (gep %P, long B), long A, ...
11124 // With: T = long A+B; gep %P, T, ...
11125 //
Chris Lattner5f667a62004-05-07 22:09:22 +000011126 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Owen Andersonb5618da2009-07-03 00:17:18 +000011127 if (SO1 == Context->getNullValue(SO1->getType())) {
Chris Lattner69193f92004-04-05 01:30:19 +000011128 Sum = GO1;
Owen Andersonb5618da2009-07-03 00:17:18 +000011129 } else if (GO1 == Context->getNullValue(GO1->getType())) {
Chris Lattner69193f92004-04-05 01:30:19 +000011130 Sum = SO1;
11131 } else {
11132 // If they aren't the same type, convert both to an integer of the
11133 // target's pointer size.
11134 if (SO1->getType() != GO1->getType()) {
11135 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Owen Andersonb5618da2009-07-03 00:17:18 +000011136 SO1 =
11137 Context->getConstantExprIntegerCast(SO1C, GO1->getType(), true);
Chris Lattner69193f92004-04-05 01:30:19 +000011138 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Owen Andersonb5618da2009-07-03 00:17:18 +000011139 GO1 =
11140 Context->getConstantExprIntegerCast(GO1C, SO1->getType(), true);
Chris Lattner69193f92004-04-05 01:30:19 +000011141 } else {
Duncan Sands44b87212007-11-01 20:53:16 +000011142 unsigned PS = TD->getPointerSizeInBits();
11143 if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
Chris Lattner69193f92004-04-05 01:30:19 +000011144 // Convert GO1 to SO1's type.
Reid Spencer13bc5d72006-12-12 09:18:51 +000011145 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
Chris Lattner69193f92004-04-05 01:30:19 +000011146
Duncan Sands44b87212007-11-01 20:53:16 +000011147 } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
Chris Lattner69193f92004-04-05 01:30:19 +000011148 // Convert SO1 to GO1's type.
Reid Spencer13bc5d72006-12-12 09:18:51 +000011149 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
Chris Lattner69193f92004-04-05 01:30:19 +000011150 } else {
11151 const Type *PT = TD->getIntPtrType();
Reid Spencer13bc5d72006-12-12 09:18:51 +000011152 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
11153 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
Chris Lattner69193f92004-04-05 01:30:19 +000011154 }
11155 }
11156 }
Chris Lattner5f667a62004-05-07 22:09:22 +000011157 if (isa<Constant>(SO1) && isa<Constant>(GO1))
Owen Andersonb5618da2009-07-03 00:17:18 +000011158 Sum = Context->getConstantExprAdd(cast<Constant>(SO1),
11159 cast<Constant>(GO1));
Chris Lattner5f667a62004-05-07 22:09:22 +000011160 else {
Gabor Greife1f6e4b2008-05-16 19:29:10 +000011161 Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +000011162 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner5f667a62004-05-07 22:09:22 +000011163 }
Chris Lattner69193f92004-04-05 01:30:19 +000011164 }
Chris Lattner5f667a62004-05-07 22:09:22 +000011165
11166 // Recycle the GEP we already have if possible.
11167 if (SrcGEPOperands.size() == 2) {
11168 GEP.setOperand(0, SrcGEPOperands[0]);
11169 GEP.setOperand(1, Sum);
11170 return &GEP;
11171 } else {
11172 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
11173 SrcGEPOperands.end()-1);
11174 Indices.push_back(Sum);
11175 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
11176 }
Misha Brukmanb1c93172005-04-21 23:48:37 +000011177 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner69193f92004-04-05 01:30:19 +000011178 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanb1c93172005-04-21 23:48:37 +000011179 SrcGEPOperands.size() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +000011180 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattner57c67b02004-03-25 22:59:29 +000011181 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
11182 SrcGEPOperands.end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +000011183 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
11184 }
11185
11186 if (!Indices.empty())
Gabor Greife9ecc682008-04-06 20:25:17 +000011187 return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
11188 Indices.end(), GEP.getName());
Chris Lattnerc59af1d2002-08-17 22:21:59 +000011189
Chris Lattner5f667a62004-05-07 22:09:22 +000011190 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattnerc59af1d2002-08-17 22:21:59 +000011191 // GEP of global variable. If all of the indices for this GEP are
11192 // constants, we can promote this to a constexpr instead of an instruction.
11193
11194 // Scan for nonconstants...
Chris Lattnerf96f4a82007-01-31 04:40:53 +000011195 SmallVector<Constant*, 8> Indices;
Chris Lattnerc59af1d2002-08-17 22:21:59 +000011196 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
11197 for (; I != E && isa<Constant>(*I); ++I)
11198 Indices.push_back(cast<Constant>(*I));
11199
11200 if (I == E) { // If they are all constants...
Owen Andersonb5618da2009-07-03 00:17:18 +000011201 Constant *CE = Context->getConstantExprGetElementPtr(GV,
Chris Lattnerf96f4a82007-01-31 04:40:53 +000011202 &Indices[0],Indices.size());
Chris Lattnerc59af1d2002-08-17 22:21:59 +000011203
11204 // Replace all uses of the GEP with the new constexpr...
11205 return ReplaceInstUsesWith(GEP, CE);
11206 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +000011207 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
Chris Lattner567b81f2005-09-13 00:40:14 +000011208 if (!isa<PointerType>(X->getType())) {
11209 // Not interesting. Source pointer must be a cast from pointer.
11210 } else if (HasZeroPointerIndex) {
Wojciech Matyjewicz309e5a72007-12-12 15:21:32 +000011211 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
11212 // into : GEP [10 x i8]* X, i32 0, ...
Chris Lattner567b81f2005-09-13 00:40:14 +000011213 //
Duncan Sands5795a602009-03-02 09:18:21 +000011214 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
11215 // into : GEP i8* X, ...
11216 //
Chris Lattner567b81f2005-09-13 00:40:14 +000011217 // This occurs when the program declares an array extern like "int X[];"
Chris Lattner567b81f2005-09-13 00:40:14 +000011218 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
11219 const PointerType *XTy = cast<PointerType>(X->getType());
Duncan Sands5795a602009-03-02 09:18:21 +000011220 if (const ArrayType *CATy =
11221 dyn_cast<ArrayType>(CPTy->getElementType())) {
11222 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
11223 if (CATy->getElementType() == XTy->getElementType()) {
11224 // -> GEP i8* X, ...
11225 SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
11226 return GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
11227 GEP.getName());
11228 } else if (const ArrayType *XATy =
11229 dyn_cast<ArrayType>(XTy->getElementType())) {
11230 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
Chris Lattner567b81f2005-09-13 00:40:14 +000011231 if (CATy->getElementType() == XATy->getElementType()) {
Duncan Sands5795a602009-03-02 09:18:21 +000011232 // -> GEP [10 x i8]* X, i32 0, ...
Chris Lattner567b81f2005-09-13 00:40:14 +000011233 // At this point, we know that the cast source type is a pointer
11234 // to an array of the same type as the destination pointer
11235 // array. Because the array type is never stepped over (there
11236 // is a leading zero) we can fold the cast into this GEP.
11237 GEP.setOperand(0, X);
11238 return &GEP;
11239 }
Duncan Sands5795a602009-03-02 09:18:21 +000011240 }
11241 }
Chris Lattner567b81f2005-09-13 00:40:14 +000011242 } else if (GEP.getNumOperands() == 2) {
11243 // Transform things like:
Wojciech Matyjewicz309e5a72007-12-12 15:21:32 +000011244 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
11245 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattner567b81f2005-09-13 00:40:14 +000011246 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
11247 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
11248 if (isa<ArrayType>(SrcElTy) &&
Duncan Sandsaf9eaa82009-05-09 07:06:46 +000011249 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
11250 TD->getTypeAllocSize(ResElTy)) {
David Greenec656cbb2007-09-04 15:46:09 +000011251 Value *Idx[2];
Owen Andersonb5618da2009-07-03 00:17:18 +000011252 Idx[0] = Context->getNullValue(Type::Int32Ty);
David Greenec656cbb2007-09-04 15:46:09 +000011253 Idx[1] = GEP.getOperand(1);
Chris Lattner567b81f2005-09-13 00:40:14 +000011254 Value *V = InsertNewInstBefore(
Gabor Greife9ecc682008-04-06 20:25:17 +000011255 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
Reid Spencer6c38f0b2006-11-27 01:05:10 +000011256 // V and GEP are both pointer types --> BitCast
11257 return new BitCastInst(V, GEP.getType());
Chris Lattner8d0bacb2004-02-22 05:25:17 +000011258 }
Chris Lattner2a893292005-09-13 18:36:04 +000011259
11260 // Transform things like:
Wojciech Matyjewicz309e5a72007-12-12 15:21:32 +000011261 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner2a893292005-09-13 18:36:04 +000011262 // (where tmp = 8*tmp2) into:
Wojciech Matyjewicz309e5a72007-12-12 15:21:32 +000011263 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner2a893292005-09-13 18:36:04 +000011264
Wojciech Matyjewicz309e5a72007-12-12 15:21:32 +000011265 if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
Chris Lattner2a893292005-09-13 18:36:04 +000011266 uint64_t ArrayEltSize =
Duncan Sandsaf9eaa82009-05-09 07:06:46 +000011267 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner2a893292005-09-13 18:36:04 +000011268
11269 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
11270 // allow either a mul, shift, or constant here.
11271 Value *NewIdx = 0;
11272 ConstantInt *Scale = 0;
11273 if (ArrayEltSize == 1) {
11274 NewIdx = GEP.getOperand(1);
Owen Andersonb5618da2009-07-03 00:17:18 +000011275 Scale =
11276 Context->getConstantInt(cast<IntegerType>(NewIdx->getType()), 1);
Chris Lattner2a893292005-09-13 18:36:04 +000011277 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Owen Andersonb5618da2009-07-03 00:17:18 +000011278 NewIdx = Context->getConstantInt(CI->getType(), 1);
Chris Lattner2a893292005-09-13 18:36:04 +000011279 Scale = CI;
11280 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11281 if (Inst->getOpcode() == Instruction::Shl &&
11282 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Shengb25806f2007-03-30 09:29:48 +000011283 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11284 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
Owen Andersonb5618da2009-07-03 00:17:18 +000011285 Scale = Context->getConstantInt(cast<IntegerType>(Inst->getType()),
Dan Gohman7ccc52f2009-06-15 22:12:54 +000011286 1ULL << ShAmtVal);
Chris Lattner2a893292005-09-13 18:36:04 +000011287 NewIdx = Inst->getOperand(0);
11288 } else if (Inst->getOpcode() == Instruction::Mul &&
11289 isa<ConstantInt>(Inst->getOperand(1))) {
11290 Scale = cast<ConstantInt>(Inst->getOperand(1));
11291 NewIdx = Inst->getOperand(0);
11292 }
11293 }
Wojciech Matyjewicz309e5a72007-12-12 15:21:32 +000011294
Chris Lattner2a893292005-09-13 18:36:04 +000011295 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewicz309e5a72007-12-12 15:21:32 +000011296 // out, perform the transformation. Note, we don't know whether Scale is
11297 // signed or not. We'll use unsigned version of division/modulo
11298 // operation after making sure Scale doesn't have the sign bit set.
Chris Lattneraf618172009-02-25 18:20:01 +000011299 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
Wojciech Matyjewicz309e5a72007-12-12 15:21:32 +000011300 Scale->getZExtValue() % ArrayEltSize == 0) {
Owen Andersonb5618da2009-07-03 00:17:18 +000011301 Scale = Context->getConstantInt(Scale->getType(),
Wojciech Matyjewicz309e5a72007-12-12 15:21:32 +000011302 Scale->getZExtValue() / ArrayEltSize);
Reid Spencere0fc4df2006-10-20 07:07:24 +000011303 if (Scale->getZExtValue() != 1) {
Owen Andersonb5618da2009-07-03 00:17:18 +000011304 Constant *C =
11305 Context->getConstantExprIntegerCast(Scale, NewIdx->getType(),
Wojciech Matyjewicz309e5a72007-12-12 15:21:32 +000011306 false /*ZExt*/);
Gabor Greife1f6e4b2008-05-16 19:29:10 +000011307 Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
Chris Lattner2a893292005-09-13 18:36:04 +000011308 NewIdx = InsertNewInstBefore(Sc, GEP);
11309 }
11310
11311 // Insert the new GEP instruction.
David Greenec656cbb2007-09-04 15:46:09 +000011312 Value *Idx[2];
Owen Andersonb5618da2009-07-03 00:17:18 +000011313 Idx[0] = Context->getNullValue(Type::Int32Ty);
David Greenec656cbb2007-09-04 15:46:09 +000011314 Idx[1] = NewIdx;
Reid Spencer6c38f0b2006-11-27 01:05:10 +000011315 Instruction *NewGEP =
Gabor Greife9ecc682008-04-06 20:25:17 +000011316 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
Reid Spencer6c38f0b2006-11-27 01:05:10 +000011317 NewGEP = InsertNewInstBefore(NewGEP, GEP);
11318 // The NewGEP must be pointer typed, so must the old one -> BitCast
11319 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner2a893292005-09-13 18:36:04 +000011320 }
11321 }
Chris Lattner8d0bacb2004-02-22 05:25:17 +000011322 }
Chris Lattnerca081252001-12-14 16:52:21 +000011323 }
Chris Lattnera784a2c2009-01-09 04:53:57 +000011324
Chris Lattnerfef138b2009-01-09 05:44:56 +000011325 /// See if we can simplify:
11326 /// X = bitcast A to B*
11327 /// Y = gep X, <...constant indices...>
11328 /// into a gep of the original struct. This is important for SROA and alias
11329 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattnera784a2c2009-01-09 04:53:57 +000011330 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Chris Lattnerfef138b2009-01-09 05:44:56 +000011331 if (!isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
11332 // Determine how much the GEP moves the pointer. We are guaranteed to get
11333 // a constant back from EmitGEPOffset.
Owen Andersonb5618da2009-07-03 00:17:18 +000011334 ConstantInt *OffsetV =
11335 cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
Chris Lattnerfef138b2009-01-09 05:44:56 +000011336 int64_t Offset = OffsetV->getSExtValue();
11337
11338 // If this GEP instruction doesn't move the pointer, just replace the GEP
11339 // with a bitcast of the real input to the dest type.
11340 if (Offset == 0) {
11341 // If the bitcast is of an allocation, and the allocation will be
11342 // converted to match the type of the cast, don't touch this.
11343 if (isa<AllocationInst>(BCI->getOperand(0))) {
11344 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11345 if (Instruction *I = visitBitCast(*BCI)) {
11346 if (I != BCI) {
11347 I->takeName(BCI);
11348 BCI->getParent()->getInstList().insert(BCI, I);
11349 ReplaceInstUsesWith(*BCI, I);
11350 }
11351 return &GEP;
Chris Lattnera784a2c2009-01-09 04:53:57 +000011352 }
Chris Lattnera784a2c2009-01-09 04:53:57 +000011353 }
Chris Lattnerfef138b2009-01-09 05:44:56 +000011354 return new BitCastInst(BCI->getOperand(0), GEP.getType());
Chris Lattnera784a2c2009-01-09 04:53:57 +000011355 }
Chris Lattnerfef138b2009-01-09 05:44:56 +000011356
11357 // Otherwise, if the offset is non-zero, we need to find out if there is a
11358 // field at Offset in 'A's type. If so, we can pull the cast through the
11359 // GEP.
11360 SmallVector<Value*, 8> NewIndices;
11361 const Type *InTy =
11362 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
Owen Andersonb5618da2009-07-03 00:17:18 +000011363 if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
Chris Lattnerfef138b2009-01-09 05:44:56 +000011364 Instruction *NGEP =
11365 GetElementPtrInst::Create(BCI->getOperand(0), NewIndices.begin(),
11366 NewIndices.end());
11367 if (NGEP->getType() == GEP.getType()) return NGEP;
11368 InsertNewInstBefore(NGEP, GEP);
11369 NGEP->takeName(&GEP);
11370 return new BitCastInst(NGEP, GEP.getType());
11371 }
Chris Lattnera784a2c2009-01-09 04:53:57 +000011372 }
11373 }
11374
Chris Lattnerca081252001-12-14 16:52:21 +000011375 return 0;
11376}
11377
Chris Lattner1085bdf2002-11-04 16:18:53 +000011378Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
11379 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +000011380 if (AI.isArrayAllocation()) { // Check C != 1
Reid Spencere0fc4df2006-10-20 07:07:24 +000011381 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11382 const Type *NewTy =
Owen Andersonb5618da2009-07-03 00:17:18 +000011383 Context->getArrayType(AI.getAllocatedType(), C->getZExtValue());
Chris Lattnera2620ac2002-11-09 00:49:43 +000011384 AllocationInst *New = 0;
Chris Lattner1085bdf2002-11-04 16:18:53 +000011385
11386 // Create and insert the replacement instruction...
11387 if (isa<MallocInst>(AI))
Nate Begeman848622f2005-11-05 09:21:28 +000011388 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +000011389 else {
11390 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman848622f2005-11-05 09:21:28 +000011391 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +000011392 }
Chris Lattnerabb77c92004-03-19 06:08:10 +000011393
11394 InsertNewInstBefore(New, AI);
Misha Brukmanb1c93172005-04-21 23:48:37 +000011395
Chris Lattner1085bdf2002-11-04 16:18:53 +000011396 // Scan to the end of the allocation instructions, to skip over a block of
Dale Johannesen08ccba72009-03-11 22:19:43 +000011397 // allocas if possible...also skip interleaved debug info
Chris Lattner1085bdf2002-11-04 16:18:53 +000011398 //
11399 BasicBlock::iterator It = New;
Dale Johannesen08ccba72009-03-11 22:19:43 +000011400 while (isa<AllocationInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
Chris Lattner1085bdf2002-11-04 16:18:53 +000011401
11402 // Now that I is pointing to the first non-allocation-inst in the block,
11403 // insert our getelementptr instruction...
11404 //
Owen Andersonb5618da2009-07-03 00:17:18 +000011405 Value *NullIdx = Context->getNullValue(Type::Int32Ty);
David Greenec656cbb2007-09-04 15:46:09 +000011406 Value *Idx[2];
11407 Idx[0] = NullIdx;
11408 Idx[1] = NullIdx;
Gabor Greife9ecc682008-04-06 20:25:17 +000011409 Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
11410 New->getName()+".sub", It);
Chris Lattner1085bdf2002-11-04 16:18:53 +000011411
11412 // Now make everything use the getelementptr instead of the original
11413 // allocation.
Chris Lattnerabb77c92004-03-19 06:08:10 +000011414 return ReplaceInstUsesWith(AI, V);
Chris Lattner81a7a232004-10-16 18:11:37 +000011415 } else if (isa<UndefValue>(AI.getArraySize())) {
Owen Andersonb5618da2009-07-03 00:17:18 +000011416 return ReplaceInstUsesWith(AI, Context->getNullValue(AI.getType()));
Chris Lattner1085bdf2002-11-04 16:18:53 +000011417 }
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +000011418 }
Chris Lattnerabb77c92004-03-19 06:08:10 +000011419
Dan Gohman59af7732009-01-13 20:18:38 +000011420 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
11421 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
Chris Lattnere5494932009-03-17 17:55:15 +000011422 // Note that we only do this for alloca's, because malloc should allocate
11423 // and return a unique pointer, even for a zero byte allocation.
Duncan Sandsaf9eaa82009-05-09 07:06:46 +000011424 if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
Owen Andersonb5618da2009-07-03 00:17:18 +000011425 return ReplaceInstUsesWith(AI, Context->getNullValue(AI.getType()));
Dan Gohman59af7732009-01-13 20:18:38 +000011426
11427 // If the alignment is 0 (unspecified), assign it the preferred alignment.
11428 if (AI.getAlignment() == 0)
11429 AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11430 }
Chris Lattnerabb77c92004-03-19 06:08:10 +000011431
Chris Lattner1085bdf2002-11-04 16:18:53 +000011432 return 0;
11433}
11434
Chris Lattner8427bff2003-12-07 01:24:23 +000011435Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
11436 Value *Op = FI.getOperand(0);
11437
Chris Lattner8ba9ec92004-10-18 02:59:09 +000011438 // free undef -> unreachable.
11439 if (isa<UndefValue>(Op)) {
11440 // Insert a new store to null because we cannot modify the CFG here.
Owen Andersonb5618da2009-07-03 00:17:18 +000011441 new StoreInst(Context->getConstantIntTrue(),
11442 Context->getUndef(Context->getPointerTypeUnqual(Type::Int1Ty)), &FI);
Chris Lattner8ba9ec92004-10-18 02:59:09 +000011443 return EraseInstFromFunction(FI);
11444 }
Chris Lattnerefb33d22007-04-14 00:20:02 +000011445
Chris Lattnerf3a36602004-02-28 04:57:37 +000011446 // If we have 'free null' delete the instruction. This can happen in stl code
11447 // when lots of inlining happens.
Chris Lattner8ba9ec92004-10-18 02:59:09 +000011448 if (isa<ConstantPointerNull>(Op))
Chris Lattner51ea1272004-02-28 05:22:00 +000011449 return EraseInstFromFunction(FI);
Chris Lattnerefb33d22007-04-14 00:20:02 +000011450
11451 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
11452 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
11453 FI.setOperand(0, CI->getOperand(0));
11454 return &FI;
11455 }
11456
11457 // Change free (gep X, 0,0,0,0) into free(X)
11458 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11459 if (GEPI->hasAllZeroIndices()) {
11460 AddToWorkList(GEPI);
11461 FI.setOperand(0, GEPI->getOperand(0));
11462 return &FI;
11463 }
11464 }
11465
11466 // Change free(malloc) into nothing, if the malloc has a single use.
11467 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
11468 if (MI->hasOneUse()) {
11469 EraseInstFromFunction(FI);
11470 return EraseInstFromFunction(*MI);
11471 }
Chris Lattnerf3a36602004-02-28 04:57:37 +000011472
Chris Lattner8427bff2003-12-07 01:24:23 +000011473 return 0;
11474}
11475
11476
Chris Lattner72684fe2005-01-31 05:51:45 +000011477/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Pateldf49cf52007-10-18 19:52:32 +000011478static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendlingd188e032008-02-26 10:53:30 +000011479 const TargetData *TD) {
Chris Lattner35e24772004-07-13 01:49:43 +000011480 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerfe1b0b82005-01-31 04:50:46 +000011481 Value *CastOp = CI->getOperand(0);
Owen Anderson38264b12009-07-06 23:00:19 +000011482 LLVMContext *Context = IC.getContext();
Chris Lattner35e24772004-07-13 01:49:43 +000011483
Nick Lewycky702fbf92009-05-08 06:47:37 +000011484 if (TD) {
11485 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
11486 // Instead of loading constant c string, use corresponding integer value
11487 // directly if string length is small enough.
11488 std::string Str;
11489 if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
11490 unsigned len = Str.length();
11491 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
11492 unsigned numBits = Ty->getPrimitiveSizeInBits();
11493 // Replace LI with immediate integer store.
11494 if ((numBits >> 3) == len + 1) {
11495 APInt StrVal(numBits, 0);
11496 APInt SingleChar(numBits, 0);
11497 if (TD->isLittleEndian()) {
11498 for (signed i = len-1; i >= 0; i--) {
11499 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11500 StrVal = (StrVal << 8) | SingleChar;
11501 }
11502 } else {
11503 for (unsigned i = 0; i < len; i++) {
11504 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11505 StrVal = (StrVal << 8) | SingleChar;
11506 }
11507 // Append NULL at the end.
11508 SingleChar = 0;
Bill Wendlingd188e032008-02-26 10:53:30 +000011509 StrVal = (StrVal << 8) | SingleChar;
11510 }
Owen Andersonb5618da2009-07-03 00:17:18 +000011511 Value *NL = Context->getConstantInt(StrVal);
Nick Lewycky702fbf92009-05-08 06:47:37 +000011512 return IC.ReplaceInstUsesWith(LI, NL);
Bill Wendlingd188e032008-02-26 10:53:30 +000011513 }
Devang Pateldf49cf52007-10-18 19:52:32 +000011514 }
11515 }
11516 }
11517
Mon P Wang21eb52a2009-02-07 22:19:29 +000011518 const PointerType *DestTy = cast<PointerType>(CI->getType());
11519 const Type *DestPTy = DestTy->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +000011520 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Mon P Wang21eb52a2009-02-07 22:19:29 +000011521
11522 // If the address spaces don't match, don't eliminate the cast.
11523 if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11524 return 0;
11525
Chris Lattner35e24772004-07-13 01:49:43 +000011526 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +000011527
Reid Spencer31a4ef42007-01-22 05:51:25 +000011528 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencerd84d35b2007-02-15 02:26:10 +000011529 isa<VectorType>(DestPTy)) {
Chris Lattnerfe1b0b82005-01-31 04:50:46 +000011530 // If the source is an array, the code below will not succeed. Check to
11531 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11532 // constants.
11533 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11534 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11535 if (ASrcTy->getNumElements() != 0) {
Chris Lattnerf96f4a82007-01-31 04:40:53 +000011536 Value *Idxs[2];
Owen Andersonb5618da2009-07-03 00:17:18 +000011537 Idxs[0] = Idxs[1] = Context->getNullValue(Type::Int32Ty);
11538 CastOp = Context->getConstantExprGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerfe1b0b82005-01-31 04:50:46 +000011539 SrcTy = cast<PointerType>(CastOp->getType());
11540 SrcPTy = SrcTy->getElementType();
11541 }
11542
Reid Spencer31a4ef42007-01-22 05:51:25 +000011543 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencerd84d35b2007-02-15 02:26:10 +000011544 isa<VectorType>(SrcPTy)) &&
Chris Lattnerecfa9b52005-03-29 06:37:47 +000011545 // Do not allow turning this into a load of an integer, which is then
11546 // casted to a pointer, this pessimizes pointer analysis a lot.
11547 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Reid Spencer31a4ef42007-01-22 05:51:25 +000011548 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
11549 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Misha Brukmanb1c93172005-04-21 23:48:37 +000011550
Chris Lattnerfe1b0b82005-01-31 04:50:46 +000011551 // Okay, we are casting from one integer or pointer type to another of
11552 // the same size. Instead of casting the pointer before the load, cast
11553 // the result of the loaded value.
11554 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
11555 CI->getName(),
11556 LI.isVolatile()),LI);
11557 // Now cast the result of the load.
Reid Spencerbb65ebf2006-12-12 23:36:14 +000011558 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerfe1b0b82005-01-31 04:50:46 +000011559 }
Chris Lattner35e24772004-07-13 01:49:43 +000011560 }
11561 }
11562 return 0;
11563}
11564
Chris Lattner0f1d8a32003-06-26 05:06:25 +000011565Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11566 Value *Op = LI.getOperand(0);
Chris Lattner7e8af382004-01-12 04:13:56 +000011567
Dan Gohmane31a61e2007-07-20 16:34:21 +000011568 // Attempt to improve the alignment.
Dan Gohman9cdfd442009-02-16 00:44:23 +000011569 unsigned KnownAlign =
11570 GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
Dan Gohman99b7b3f2008-04-10 18:43:06 +000011571 if (KnownAlign >
11572 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11573 LI.getAlignment()))
Dan Gohmane31a61e2007-07-20 16:34:21 +000011574 LI.setAlignment(KnownAlign);
11575
Chris Lattnera9d84e32005-05-01 04:24:53 +000011576 // load (cast X) --> cast (load X) iff safe
Reid Spencerde46e482006-11-02 20:25:50 +000011577 if (isa<CastInst>(Op))
Devang Pateldf49cf52007-10-18 19:52:32 +000011578 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattnera9d84e32005-05-01 04:24:53 +000011579 return Res;
11580
11581 // None of the following transforms are legal for volatile loads.
11582 if (LI.isVolatile()) return 0;
Chris Lattnerb990f7d2005-09-12 22:00:15 +000011583
Dan Gohmanbc027842008-10-15 23:19:35 +000011584 // Do really simple store-to-load forwarding and load CSE, to catch cases
11585 // where there are several consequtive memory accesses to the same location,
11586 // separated by a few arithmetic operations.
11587 BasicBlock::iterator BBI = &LI;
Chris Lattnere0d019d2008-11-27 08:56:30 +000011588 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11589 return ReplaceInstUsesWith(LI, AvailableVal);
Chris Lattnera9d84e32005-05-01 04:24:53 +000011590
Christopher Lambb053b802007-12-29 07:56:53 +000011591 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11592 const Value *GEPI0 = GEPI->getOperand(0);
11593 // TODO: Consider a target hook for valid address spaces for this xform.
11594 if (isa<ConstantPointerNull>(GEPI0) &&
11595 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
Chris Lattnera9d84e32005-05-01 04:24:53 +000011596 // Insert a new store to null instruction before the load to indicate
11597 // that this code is not reachable. We do this instead of inserting
11598 // an unreachable instruction directly because we cannot modify the
11599 // CFG.
Owen Andersonb5618da2009-07-03 00:17:18 +000011600 new StoreInst(Context->getUndef(LI.getType()),
11601 Context->getNullValue(Op->getType()), &LI);
11602 return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
Chris Lattnera9d84e32005-05-01 04:24:53 +000011603 }
Christopher Lambb053b802007-12-29 07:56:53 +000011604 }
Chris Lattnera9d84e32005-05-01 04:24:53 +000011605
Chris Lattner81a7a232004-10-16 18:11:37 +000011606 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattnera9d84e32005-05-01 04:24:53 +000011607 // load null/undef -> undef
Christopher Lambb053b802007-12-29 07:56:53 +000011608 // TODO: Consider a target hook for valid address spaces for this xform.
11609 if (isa<UndefValue>(C) || (C->isNullValue() &&
11610 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
Chris Lattner8ba9ec92004-10-18 02:59:09 +000011611 // Insert a new store to null instruction before the load to indicate that
11612 // this code is not reachable. We do this instead of inserting an
11613 // unreachable instruction directly because we cannot modify the CFG.
Owen Andersonb5618da2009-07-03 00:17:18 +000011614 new StoreInst(Context->getUndef(LI.getType()),
11615 Context->getNullValue(Op->getType()), &LI);
11616 return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
Chris Lattner8ba9ec92004-10-18 02:59:09 +000011617 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +000011618
Chris Lattner81a7a232004-10-16 18:11:37 +000011619 // Instcombine load (constant global) into the value loaded.
11620 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Duncan Sands1f15ca72009-03-21 21:27:31 +000011621 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Chris Lattner81a7a232004-10-16 18:11:37 +000011622 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanb1c93172005-04-21 23:48:37 +000011623
Chris Lattner81a7a232004-10-16 18:11:37 +000011624 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +000011625 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
Chris Lattner81a7a232004-10-16 18:11:37 +000011626 if (CE->getOpcode() == Instruction::GetElementPtr) {
11627 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Duncan Sands1f15ca72009-03-21 21:27:31 +000011628 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Chris Lattner0b011ec2005-09-26 05:28:06 +000011629 if (Constant *V =
Owen Anderson39f00cc2009-07-06 18:42:36 +000011630 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE,
11631 Context))
Chris Lattner81a7a232004-10-16 18:11:37 +000011632 return ReplaceInstUsesWith(LI, V);
Chris Lattnera9d84e32005-05-01 04:24:53 +000011633 if (CE->getOperand(0)->isNullValue()) {
11634 // Insert a new store to null instruction before the load to indicate
11635 // that this code is not reachable. We do this instead of inserting
11636 // an unreachable instruction directly because we cannot modify the
11637 // CFG.
Owen Andersonb5618da2009-07-03 00:17:18 +000011638 new StoreInst(Context->getUndef(LI.getType()),
11639 Context->getNullValue(Op->getType()), &LI);
11640 return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
Chris Lattnera9d84e32005-05-01 04:24:53 +000011641 }
11642
Reid Spencer6c38f0b2006-11-27 01:05:10 +000011643 } else if (CE->isCast()) {
Devang Pateldf49cf52007-10-18 19:52:32 +000011644 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattner81a7a232004-10-16 18:11:37 +000011645 return Res;
11646 }
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +000011647 }
Chris Lattner81a7a232004-10-16 18:11:37 +000011648 }
Chris Lattner99c8ee22007-08-11 18:48:48 +000011649
11650 // If this load comes from anywhere in a constant global, and if the global
11651 // is all undef or zero, we know what it loads.
Duncan Sandsd65a4da2008-10-01 15:25:41 +000011652 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
Duncan Sands1f15ca72009-03-21 21:27:31 +000011653 if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
Chris Lattner99c8ee22007-08-11 18:48:48 +000011654 if (GV->getInitializer()->isNullValue())
Owen Andersonb5618da2009-07-03 00:17:18 +000011655 return ReplaceInstUsesWith(LI, Context->getNullValue(LI.getType()));
Chris Lattner99c8ee22007-08-11 18:48:48 +000011656 else if (isa<UndefValue>(GV->getInitializer()))
Owen Andersonb5618da2009-07-03 00:17:18 +000011657 return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
Chris Lattner99c8ee22007-08-11 18:48:48 +000011658 }
11659 }
Chris Lattnere228ee52004-04-08 20:39:49 +000011660
Chris Lattnera9d84e32005-05-01 04:24:53 +000011661 if (Op->hasOneUse()) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +000011662 // Change select and PHI nodes to select values instead of addresses: this
11663 // helps alias analysis out a lot, allows many others simplifications, and
11664 // exposes redundancy in the code.
11665 //
11666 // Note that we cannot do the transformation unless we know that the
11667 // introduced loads cannot trap! Something like this is valid as long as
11668 // the condition is always false: load (select bool %C, int* null, int* %G),
11669 // but it would not be valid if we transformed it to load from null
11670 // unconditionally.
11671 //
11672 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11673 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattnere6f13092004-09-19 19:18:10 +000011674 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11675 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +000011676 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner42618552004-09-20 10:15:10 +000011677 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +000011678 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner42618552004-09-20 10:15:10 +000011679 SI->getOperand(2)->getName()+".val"), LI);
Gabor Greife9ecc682008-04-06 20:25:17 +000011680 return SelectInst::Create(SI->getCondition(), V1, V2);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +000011681 }
11682
Chris Lattnerbdcf41a2004-09-23 15:46:00 +000011683 // load (select (cond, null, P)) -> load P
11684 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11685 if (C->isNullValue()) {
11686 LI.setOperand(0, SI->getOperand(2));
11687 return &LI;
11688 }
11689
11690 // load (select (cond, P, null)) -> load P
11691 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11692 if (C->isNullValue()) {
11693 LI.setOperand(0, SI->getOperand(1));
11694 return &LI;
11695 }
Chris Lattnerf62ea8e2004-09-19 18:43:46 +000011696 }
11697 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +000011698 return 0;
11699}
11700
Reid Spencere928a152007-01-19 21:20:31 +000011701/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattner72cd68f2009-01-24 01:00:13 +000011702/// when possible. This makes it generally easy to do alias analysis and/or
11703/// SROA/mem2reg of the memory object.
Chris Lattner72684fe2005-01-31 05:51:45 +000011704static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11705 User *CI = cast<User>(SI.getOperand(1));
11706 Value *CastOp = CI->getOperand(0);
Owen Anderson38264b12009-07-06 23:00:19 +000011707 LLVMContext *Context = IC.getContext();
Chris Lattner72684fe2005-01-31 05:51:45 +000011708
11709 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattner733256f2009-01-16 20:08:59 +000011710 const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11711 if (SrcTy == 0) return 0;
11712
11713 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattner72684fe2005-01-31 05:51:45 +000011714
Chris Lattner733256f2009-01-16 20:08:59 +000011715 if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11716 return 0;
11717
Chris Lattner72cd68f2009-01-24 01:00:13 +000011718 /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11719 /// to its first element. This allows us to handle things like:
11720 /// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11721 /// on 32-bit hosts.
11722 SmallVector<Value*, 4> NewGEPIndices;
11723
Chris Lattner733256f2009-01-16 20:08:59 +000011724 // If the source is an array, the code below will not succeed. Check to
11725 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11726 // constants.
Chris Lattner72cd68f2009-01-24 01:00:13 +000011727 if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11728 // Index through pointer.
Owen Andersonb5618da2009-07-03 00:17:18 +000011729 Constant *Zero = Context->getNullValue(Type::Int32Ty);
Chris Lattner72cd68f2009-01-24 01:00:13 +000011730 NewGEPIndices.push_back(Zero);
11731
11732 while (1) {
11733 if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
Torok Edwinf4395ea2009-01-24 17:16:04 +000011734 if (!STy->getNumElements()) /* Struct can be empty {} */
Torok Edwin73ff9222009-01-24 11:30:49 +000011735 break;
Chris Lattner72cd68f2009-01-24 01:00:13 +000011736 NewGEPIndices.push_back(Zero);
11737 SrcPTy = STy->getElementType(0);
11738 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11739 NewGEPIndices.push_back(Zero);
11740 SrcPTy = ATy->getElementType();
11741 } else {
11742 break;
Chris Lattner72684fe2005-01-31 05:51:45 +000011743 }
Chris Lattner72cd68f2009-01-24 01:00:13 +000011744 }
11745
Owen Andersonb5618da2009-07-03 00:17:18 +000011746 SrcTy = Context->getPointerType(SrcPTy, SrcTy->getAddressSpace());
Chris Lattner72cd68f2009-01-24 01:00:13 +000011747 }
Chris Lattner733256f2009-01-16 20:08:59 +000011748
11749 if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11750 return 0;
11751
Chris Lattnerdb2d9612009-01-16 20:12:52 +000011752 // If the pointers point into different address spaces or if they point to
11753 // values with different sizes, we can't do the transformation.
11754 if (SrcTy->getAddressSpace() !=
11755 cast<PointerType>(CI->getType())->getAddressSpace() ||
11756 IC.getTargetData().getTypeSizeInBits(SrcPTy) !=
Chris Lattner733256f2009-01-16 20:08:59 +000011757 IC.getTargetData().getTypeSizeInBits(DestPTy))
11758 return 0;
11759
11760 // Okay, we are casting from one integer or pointer type to another of
11761 // the same size. Instead of casting the pointer before
11762 // the store, cast the value to be stored.
11763 Value *NewCast;
11764 Value *SIOp0 = SI.getOperand(0);
11765 Instruction::CastOps opcode = Instruction::BitCast;
11766 const Type* CastSrcTy = SIOp0->getType();
11767 const Type* CastDstTy = SrcPTy;
11768 if (isa<PointerType>(CastDstTy)) {
11769 if (CastSrcTy->isInteger())
11770 opcode = Instruction::IntToPtr;
11771 } else if (isa<IntegerType>(CastDstTy)) {
11772 if (isa<PointerType>(SIOp0->getType()))
11773 opcode = Instruction::PtrToInt;
Chris Lattner72684fe2005-01-31 05:51:45 +000011774 }
Chris Lattner72cd68f2009-01-24 01:00:13 +000011775
11776 // SIOp0 is a pointer to aggregate and this is a store to the first field,
11777 // emit a GEP to index into its first field.
11778 if (!NewGEPIndices.empty()) {
11779 if (Constant *C = dyn_cast<Constant>(CastOp))
Owen Andersonb5618da2009-07-03 00:17:18 +000011780 CastOp = Context->getConstantExprGetElementPtr(C, &NewGEPIndices[0],
Chris Lattner72cd68f2009-01-24 01:00:13 +000011781 NewGEPIndices.size());
11782 else
11783 CastOp = IC.InsertNewInstBefore(
11784 GetElementPtrInst::Create(CastOp, NewGEPIndices.begin(),
11785 NewGEPIndices.end()), SI);
11786 }
11787
Chris Lattner733256f2009-01-16 20:08:59 +000011788 if (Constant *C = dyn_cast<Constant>(SIOp0))
Owen Andersonb5618da2009-07-03 00:17:18 +000011789 NewCast = Context->getConstantExprCast(opcode, C, CastDstTy);
Chris Lattner733256f2009-01-16 20:08:59 +000011790 else
11791 NewCast = IC.InsertNewInstBefore(
11792 CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
11793 SI);
11794 return new StoreInst(NewCast, CastOp);
Chris Lattner72684fe2005-01-31 05:51:45 +000011795}
11796
Chris Lattnere0d019d2008-11-27 08:56:30 +000011797/// equivalentAddressValues - Test if A and B will obviously have the same
11798/// value. This includes recognizing that %t0 and %t1 will have the same
11799/// value in code like this:
Dan Gohman92b551b2009-03-03 02:55:14 +000011800/// %t0 = getelementptr \@a, 0, 3
Chris Lattnere0d019d2008-11-27 08:56:30 +000011801/// store i32 0, i32* %t0
Dan Gohman92b551b2009-03-03 02:55:14 +000011802/// %t1 = getelementptr \@a, 0, 3
Chris Lattnere0d019d2008-11-27 08:56:30 +000011803/// %t2 = load i32* %t1
11804///
11805static bool equivalentAddressValues(Value *A, Value *B) {
11806 // Test if the values are trivially equivalent.
11807 if (A == B) return true;
11808
11809 // Test if the values come form identical arithmetic instructions.
11810 if (isa<BinaryOperator>(A) ||
11811 isa<CastInst>(A) ||
11812 isa<PHINode>(A) ||
11813 isa<GetElementPtrInst>(A))
11814 if (Instruction *BI = dyn_cast<Instruction>(B))
11815 if (cast<Instruction>(A)->isIdenticalTo(BI))
11816 return true;
11817
11818 // Otherwise they may not be equivalent.
11819 return false;
11820}
11821
Dale Johannesen77456b72009-03-03 21:26:39 +000011822// If this instruction has two uses, one of which is a llvm.dbg.declare,
11823// return the llvm.dbg.declare.
11824DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11825 if (!V->hasNUses(2))
11826 return 0;
11827 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11828 UI != E; ++UI) {
11829 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11830 return DI;
11831 if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11832 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11833 return DI;
11834 }
11835 }
11836 return 0;
11837}
11838
Chris Lattner31f486c2005-01-31 05:36:43 +000011839Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11840 Value *Val = SI.getOperand(0);
11841 Value *Ptr = SI.getOperand(1);
11842
11843 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner5997cf92006-02-08 03:25:32 +000011844 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +000011845 ++NumCombined;
11846 return 0;
11847 }
Chris Lattnera4beeef2007-01-15 06:51:56 +000011848
11849 // If the RHS is an alloca with a single use, zapify the store, making the
11850 // alloca dead.
Dale Johannesen77456b72009-03-03 21:26:39 +000011851 // If the RHS is an alloca with a two uses, the other one being a
11852 // llvm.dbg.declare, zapify the store and the declare, making the
11853 // alloca dead. We must do this to prevent declare's from affecting
11854 // codegen.
11855 if (!SI.isVolatile()) {
11856 if (Ptr->hasOneUse()) {
11857 if (isa<AllocaInst>(Ptr)) {
Chris Lattnera4beeef2007-01-15 06:51:56 +000011858 EraseInstFromFunction(SI);
11859 ++NumCombined;
11860 return 0;
11861 }
Dale Johannesen77456b72009-03-03 21:26:39 +000011862 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11863 if (isa<AllocaInst>(GEP->getOperand(0))) {
11864 if (GEP->getOperand(0)->hasOneUse()) {
11865 EraseInstFromFunction(SI);
11866 ++NumCombined;
11867 return 0;
11868 }
11869 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11870 EraseInstFromFunction(*DI);
11871 EraseInstFromFunction(SI);
11872 ++NumCombined;
11873 return 0;
11874 }
11875 }
11876 }
11877 }
11878 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11879 EraseInstFromFunction(*DI);
11880 EraseInstFromFunction(SI);
11881 ++NumCombined;
11882 return 0;
11883 }
Chris Lattnera4beeef2007-01-15 06:51:56 +000011884 }
Chris Lattner31f486c2005-01-31 05:36:43 +000011885
Dan Gohmane31a61e2007-07-20 16:34:21 +000011886 // Attempt to improve the alignment.
Dan Gohman9cdfd442009-02-16 00:44:23 +000011887 unsigned KnownAlign =
11888 GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
Dan Gohman99b7b3f2008-04-10 18:43:06 +000011889 if (KnownAlign >
11890 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11891 SI.getAlignment()))
Dan Gohmane31a61e2007-07-20 16:34:21 +000011892 SI.setAlignment(KnownAlign);
11893
Dale Johannesen01925522009-03-03 01:43:03 +000011894 // Do really simple DSE, to catch cases where there are several consecutive
Chris Lattner5997cf92006-02-08 03:25:32 +000011895 // stores to the same location, separated by a few arithmetic operations. This
11896 // situation often occurs with bitfield accesses.
11897 BasicBlock::iterator BBI = &SI;
11898 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11899 --ScanInsts) {
Dale Johannesen0365d3b2009-03-04 01:20:34 +000011900 --BBI;
Dale Johannesenc8b5a6e2009-03-04 01:53:05 +000011901 // Don't count debug info directives, lest they affect codegen,
11902 // and we skip pointer-to-pointer bitcasts, which are NOPs.
11903 // It is necessary for correctness to skip those that feed into a
11904 // llvm.dbg.declare, as these are not present when debugging is off.
Dale Johannesen09c3e8e2009-03-03 22:36:47 +000011905 if (isa<DbgInfoIntrinsic>(BBI) ||
Dale Johannesenc8b5a6e2009-03-04 01:53:05 +000011906 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
Dale Johannesen01925522009-03-03 01:43:03 +000011907 ScanInsts++;
Dale Johannesen01925522009-03-03 01:43:03 +000011908 continue;
11909 }
Chris Lattner5997cf92006-02-08 03:25:32 +000011910
11911 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11912 // Prev store isn't volatile, and stores to the same location?
Chris Lattnere0d019d2008-11-27 08:56:30 +000011913 if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11914 SI.getOperand(1))) {
Chris Lattner5997cf92006-02-08 03:25:32 +000011915 ++NumDeadStore;
11916 ++BBI;
11917 EraseInstFromFunction(*PrevSI);
11918 continue;
11919 }
11920 break;
11921 }
11922
Chris Lattnerdab43b22006-05-26 19:19:20 +000011923 // If this is a load, we have to stop. However, if the loaded value is from
11924 // the pointer we're loading and is producing the pointer we're storing,
11925 // then *this* store is dead (X = load P; store X -> P).
11926 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Dan Gohmanbc027842008-10-15 23:19:35 +000011927 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11928 !SI.isVolatile()) {
Chris Lattnerdab43b22006-05-26 19:19:20 +000011929 EraseInstFromFunction(SI);
11930 ++NumCombined;
11931 return 0;
11932 }
11933 // Otherwise, this is a load from some other location. Stores before it
11934 // may not be dead.
11935 break;
11936 }
11937
Chris Lattner5997cf92006-02-08 03:25:32 +000011938 // Don't skip over loads or things that can modify memory.
Chris Lattner4fa09662008-05-08 17:20:30 +000011939 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Chris Lattner5997cf92006-02-08 03:25:32 +000011940 break;
11941 }
11942
11943
11944 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner31f486c2005-01-31 05:36:43 +000011945
11946 // store X, null -> turns into 'unreachable' in SimplifyCFG
Chris Lattner61797e32009-06-11 17:54:56 +000011947 if (isa<ConstantPointerNull>(Ptr) &&
11948 cast<PointerType>(Ptr->getType())->getAddressSpace() == 0) {
Chris Lattner31f486c2005-01-31 05:36:43 +000011949 if (!isa<UndefValue>(Val)) {
Owen Andersonb5618da2009-07-03 00:17:18 +000011950 SI.setOperand(0, Context->getUndef(Val->getType()));
Chris Lattner31f486c2005-01-31 05:36:43 +000011951 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattnerb15e2b12007-03-02 21:28:56 +000011952 AddToWorkList(U); // Dropped a use.
Chris Lattner31f486c2005-01-31 05:36:43 +000011953 ++NumCombined;
11954 }
11955 return 0; // Do not modify these!
11956 }
11957
11958 // store undef, Ptr -> noop
11959 if (isa<UndefValue>(Val)) {
Chris Lattner5997cf92006-02-08 03:25:32 +000011960 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +000011961 ++NumCombined;
11962 return 0;
11963 }
11964
Chris Lattner72684fe2005-01-31 05:51:45 +000011965 // If the pointer destination is a cast, see if we can fold the cast into the
11966 // source instead.
Reid Spencerde46e482006-11-02 20:25:50 +000011967 if (isa<CastInst>(Ptr))
Chris Lattner72684fe2005-01-31 05:51:45 +000011968 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11969 return Res;
11970 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer6c38f0b2006-11-27 01:05:10 +000011971 if (CE->isCast())
Chris Lattner72684fe2005-01-31 05:51:45 +000011972 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11973 return Res;
11974
Chris Lattner219175c2005-09-12 23:23:25 +000011975
Dale Johannesen78ab3382009-03-05 02:06:48 +000011976 // If this store is the last instruction in the basic block (possibly
11977 // excepting debug info instructions and the pointer bitcasts that feed
11978 // into them), and if the block ends with an unconditional branch, try
11979 // to move it to the successor block.
11980 BBI = &SI;
11981 do {
11982 ++BBI;
11983 } while (isa<DbgInfoIntrinsic>(BBI) ||
11984 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
Chris Lattner219175c2005-09-12 23:23:25 +000011985 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
Chris Lattner14a251b2007-04-15 00:07:55 +000011986 if (BI->isUnconditional())
11987 if (SimplifyStoreAtEndOfBlock(SI))
11988 return 0; // xform done!
Chris Lattner219175c2005-09-12 23:23:25 +000011989
Chris Lattner31f486c2005-01-31 05:36:43 +000011990 return 0;
11991}
11992
Chris Lattner14a251b2007-04-15 00:07:55 +000011993/// SimplifyStoreAtEndOfBlock - Turn things like:
11994/// if () { *P = v1; } else { *P = v2 }
11995/// into a phi node with a store in the successor.
11996///
Chris Lattner4a6e0cb2007-04-15 01:02:18 +000011997/// Simplify things like:
11998/// *P = v1; if () { *P = v2; }
11999/// into a phi node with a store in the successor.
12000///
Chris Lattner14a251b2007-04-15 00:07:55 +000012001bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
12002 BasicBlock *StoreBB = SI.getParent();
12003
12004 // Check to see if the successor block has exactly two incoming edges. If
12005 // so, see if the other predecessor contains a store to the same location.
12006 // if so, insert a PHI node (if needed) and move the stores down.
Chris Lattner4a6e0cb2007-04-15 01:02:18 +000012007 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Chris Lattner14a251b2007-04-15 00:07:55 +000012008
12009 // Determine whether Dest has exactly two predecessors and, if so, compute
12010 // the other predecessor.
Chris Lattner4a6e0cb2007-04-15 01:02:18 +000012011 pred_iterator PI = pred_begin(DestBB);
12012 BasicBlock *OtherBB = 0;
Chris Lattner14a251b2007-04-15 00:07:55 +000012013 if (*PI != StoreBB)
Chris Lattner4a6e0cb2007-04-15 01:02:18 +000012014 OtherBB = *PI;
Chris Lattner14a251b2007-04-15 00:07:55 +000012015 ++PI;
Chris Lattner4a6e0cb2007-04-15 01:02:18 +000012016 if (PI == pred_end(DestBB))
Chris Lattner14a251b2007-04-15 00:07:55 +000012017 return false;
12018
12019 if (*PI != StoreBB) {
Chris Lattner4a6e0cb2007-04-15 01:02:18 +000012020 if (OtherBB)
Chris Lattner14a251b2007-04-15 00:07:55 +000012021 return false;
Chris Lattner4a6e0cb2007-04-15 01:02:18 +000012022 OtherBB = *PI;
Chris Lattner14a251b2007-04-15 00:07:55 +000012023 }
Chris Lattner4a6e0cb2007-04-15 01:02:18 +000012024 if (++PI != pred_end(DestBB))
Chris Lattner14a251b2007-04-15 00:07:55 +000012025 return false;
Eli Friedman9833a1b2008-06-13 21:17:49 +000012026
12027 // Bail out if all the relevant blocks aren't distinct (this can happen,
12028 // for example, if SI is in an infinite loop)
12029 if (StoreBB == DestBB || OtherBB == DestBB)
12030 return false;
12031
Chris Lattner4a6e0cb2007-04-15 01:02:18 +000012032 // Verify that the other block ends in a branch and is not otherwise empty.
12033 BasicBlock::iterator BBI = OtherBB->getTerminator();
Chris Lattner14a251b2007-04-15 00:07:55 +000012034 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
Chris Lattner4a6e0cb2007-04-15 01:02:18 +000012035 if (!OtherBr || BBI == OtherBB->begin())
Chris Lattner14a251b2007-04-15 00:07:55 +000012036 return false;
12037
Chris Lattner4a6e0cb2007-04-15 01:02:18 +000012038 // If the other block ends in an unconditional branch, check for the 'if then
12039 // else' case. there is an instruction before the branch.
12040 StoreInst *OtherStore = 0;
12041 if (OtherBr->isUnconditional()) {
Chris Lattner4a6e0cb2007-04-15 01:02:18 +000012042 --BBI;
Dale Johannesen78ab3382009-03-05 02:06:48 +000012043 // Skip over debugging info.
12044 while (isa<DbgInfoIntrinsic>(BBI) ||
12045 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
12046 if (BBI==OtherBB->begin())
12047 return false;
12048 --BBI;
12049 }
12050 // If this isn't a store, or isn't a store to the same location, bail out.
Chris Lattner4a6e0cb2007-04-15 01:02:18 +000012051 OtherStore = dyn_cast<StoreInst>(BBI);
12052 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
12053 return false;
12054 } else {
Chris Lattner361e9812007-05-05 22:32:24 +000012055 // Otherwise, the other block ended with a conditional branch. If one of the
Chris Lattner4a6e0cb2007-04-15 01:02:18 +000012056 // destinations is StoreBB, then we have the if/then case.
12057 if (OtherBr->getSuccessor(0) != StoreBB &&
12058 OtherBr->getSuccessor(1) != StoreBB)
12059 return false;
12060
12061 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
Chris Lattner361e9812007-05-05 22:32:24 +000012062 // if/then triangle. See if there is a store to the same ptr as SI that
12063 // lives in OtherBB.
Chris Lattner4a6e0cb2007-04-15 01:02:18 +000012064 for (;; --BBI) {
12065 // Check to see if we find the matching store.
12066 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
12067 if (OtherStore->getOperand(1) != SI.getOperand(1))
12068 return false;
12069 break;
12070 }
Eli Friedman5de0a772008-06-13 22:02:12 +000012071 // If we find something that may be using or overwriting the stored
12072 // value, or if we run out of instructions, we can't do the xform.
12073 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
Chris Lattner4a6e0cb2007-04-15 01:02:18 +000012074 BBI == OtherBB->begin())
12075 return false;
12076 }
12077
12078 // In order to eliminate the store in OtherBr, we have to
Eli Friedman5de0a772008-06-13 22:02:12 +000012079 // make sure nothing reads or overwrites the stored value in
12080 // StoreBB.
Chris Lattner4a6e0cb2007-04-15 01:02:18 +000012081 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
12082 // FIXME: This should really be AA driven.
Eli Friedman5de0a772008-06-13 22:02:12 +000012083 if (I->mayReadFromMemory() || I->mayWriteToMemory())
Chris Lattner4a6e0cb2007-04-15 01:02:18 +000012084 return false;
12085 }
12086 }
Chris Lattner14a251b2007-04-15 00:07:55 +000012087
Chris Lattner4a6e0cb2007-04-15 01:02:18 +000012088 // Insert a PHI node now if we need it.
Chris Lattner14a251b2007-04-15 00:07:55 +000012089 Value *MergedVal = OtherStore->getOperand(0);
12090 if (MergedVal != SI.getOperand(0)) {
Gabor Greife9ecc682008-04-06 20:25:17 +000012091 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Chris Lattner14a251b2007-04-15 00:07:55 +000012092 PN->reserveOperandSpace(2);
12093 PN->addIncoming(SI.getOperand(0), SI.getParent());
Chris Lattner4a6e0cb2007-04-15 01:02:18 +000012094 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
12095 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Chris Lattner14a251b2007-04-15 00:07:55 +000012096 }
12097
12098 // Advance to a place where it is safe to insert the new store and
12099 // insert it.
Dan Gohmanf96e1372008-05-23 21:05:58 +000012100 BBI = DestBB->getFirstNonPHI();
Chris Lattner14a251b2007-04-15 00:07:55 +000012101 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
12102 OtherStore->isVolatile()), *BBI);
12103
12104 // Nuke the old stores.
12105 EraseInstFromFunction(SI);
12106 EraseInstFromFunction(*OtherStore);
12107 ++NumCombined;
12108 return true;
12109}
12110
Chris Lattner31f486c2005-01-31 05:36:43 +000012111
Chris Lattner9eef8a72003-06-04 04:46:00 +000012112Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
12113 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4fdd96c2005-06-18 17:37:34 +000012114 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +000012115 BasicBlock *TrueDest;
12116 BasicBlock *FalseDest;
Owen Anderson16e76742009-07-10 17:35:01 +000012117 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest), *Context) &&
Chris Lattnerd4252a72004-07-30 07:50:03 +000012118 !isa<Constant>(X)) {
12119 // Swap Destinations and condition...
12120 BI.setCondition(X);
12121 BI.setSuccessor(0, FalseDest);
12122 BI.setSuccessor(1, TrueDest);
12123 return &BI;
12124 }
12125
Reid Spencer266e42b2006-12-23 06:05:41 +000012126 // Cannonicalize fcmp_one -> fcmp_oeq
12127 FCmpInst::Predicate FPred; Value *Y;
12128 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
Owen Anderson16e76742009-07-10 17:35:01 +000012129 TrueDest, FalseDest), *Context))
Reid Spencer266e42b2006-12-23 06:05:41 +000012130 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
12131 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
12132 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
Reid Spencer266e42b2006-12-23 06:05:41 +000012133 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
Owen Anderson1e5f00e2009-07-09 23:48:35 +000012134 Instruction *NewSCC = new FCmpInst(I, NewPred, X, Y, "");
Chris Lattner6e0123b2007-02-11 01:23:03 +000012135 NewSCC->takeName(I);
Reid Spencer266e42b2006-12-23 06:05:41 +000012136 // Swap Destinations and condition...
12137 BI.setCondition(NewSCC);
12138 BI.setSuccessor(0, FalseDest);
12139 BI.setSuccessor(1, TrueDest);
Chris Lattnerb15e2b12007-03-02 21:28:56 +000012140 RemoveFromWorkList(I);
Chris Lattner6e0123b2007-02-11 01:23:03 +000012141 I->eraseFromParent();
Chris Lattnerb15e2b12007-03-02 21:28:56 +000012142 AddToWorkList(NewSCC);
Reid Spencer266e42b2006-12-23 06:05:41 +000012143 return &BI;
12144 }
12145
12146 // Cannonicalize icmp_ne -> icmp_eq
12147 ICmpInst::Predicate IPred;
12148 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
Owen Anderson16e76742009-07-10 17:35:01 +000012149 TrueDest, FalseDest), *Context))
Reid Spencer266e42b2006-12-23 06:05:41 +000012150 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
12151 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
12152 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
12153 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
Reid Spencer266e42b2006-12-23 06:05:41 +000012154 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
Owen Anderson1e5f00e2009-07-09 23:48:35 +000012155 Instruction *NewSCC = new ICmpInst(I, NewPred, X, Y, "");
Chris Lattner6e0123b2007-02-11 01:23:03 +000012156 NewSCC->takeName(I);
Chris Lattnere967b342003-06-04 05:10:11 +000012157 // Swap Destinations and condition...
Chris Lattnerd4252a72004-07-30 07:50:03 +000012158 BI.setCondition(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +000012159 BI.setSuccessor(0, FalseDest);
12160 BI.setSuccessor(1, TrueDest);
Chris Lattnerb15e2b12007-03-02 21:28:56 +000012161 RemoveFromWorkList(I);
Chris Lattner6e0123b2007-02-11 01:23:03 +000012162 I->eraseFromParent();;
Chris Lattnerb15e2b12007-03-02 21:28:56 +000012163 AddToWorkList(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +000012164 return &BI;
12165 }
Misha Brukmanb1c93172005-04-21 23:48:37 +000012166
Chris Lattner9eef8a72003-06-04 04:46:00 +000012167 return 0;
12168}
Chris Lattner1085bdf2002-11-04 16:18:53 +000012169
Chris Lattner4c9c20a2004-07-03 00:26:11 +000012170Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
12171 Value *Cond = SI.getCondition();
12172 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
12173 if (I->getOpcode() == Instruction::Add)
12174 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
12175 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
12176 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Owen Andersonb5618da2009-07-03 00:17:18 +000012177 SI.setOperand(i,
12178 Context->getConstantExprSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner4c9c20a2004-07-03 00:26:11 +000012179 AddRHS));
12180 SI.setOperand(0, I->getOperand(0));
Chris Lattnerb15e2b12007-03-02 21:28:56 +000012181 AddToWorkList(I);
Chris Lattner4c9c20a2004-07-03 00:26:11 +000012182 return &SI;
12183 }
12184 }
12185 return 0;
12186}
12187
Matthijs Kooijmanb2fc72b2008-06-11 14:05:05 +000012188Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijmanc1d74772008-07-16 12:55:45 +000012189 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmanb2fc72b2008-06-11 14:05:05 +000012190
Matthijs Kooijmanc1d74772008-07-16 12:55:45 +000012191 if (!EV.hasIndices())
12192 return ReplaceInstUsesWith(EV, Agg);
12193
12194 if (Constant *C = dyn_cast<Constant>(Agg)) {
12195 if (isa<UndefValue>(C))
Owen Andersonb5618da2009-07-03 00:17:18 +000012196 return ReplaceInstUsesWith(EV, Context->getUndef(EV.getType()));
Matthijs Kooijmanc1d74772008-07-16 12:55:45 +000012197
12198 if (isa<ConstantAggregateZero>(C))
Owen Andersonb5618da2009-07-03 00:17:18 +000012199 return ReplaceInstUsesWith(EV, Context->getNullValue(EV.getType()));
Matthijs Kooijmanc1d74772008-07-16 12:55:45 +000012200
12201 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
12202 // Extract the element indexed by the first index out of the constant
12203 Value *V = C->getOperand(*EV.idx_begin());
12204 if (EV.getNumIndices() > 1)
12205 // Extract the remaining indices out of the constant indexed by the
12206 // first index
12207 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
12208 else
12209 return ReplaceInstUsesWith(EV, V);
12210 }
12211 return 0; // Can't handle other constants
12212 }
12213 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
12214 // We're extracting from an insertvalue instruction, compare the indices
12215 const unsigned *exti, *exte, *insi, *inse;
12216 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
12217 exte = EV.idx_end(), inse = IV->idx_end();
12218 exti != exte && insi != inse;
12219 ++exti, ++insi) {
12220 if (*insi != *exti)
12221 // The insert and extract both reference distinctly different elements.
12222 // This means the extract is not influenced by the insert, and we can
12223 // replace the aggregate operand of the extract with the aggregate
12224 // operand of the insert. i.e., replace
12225 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12226 // %E = extractvalue { i32, { i32 } } %I, 0
12227 // with
12228 // %E = extractvalue { i32, { i32 } } %A, 0
12229 return ExtractValueInst::Create(IV->getAggregateOperand(),
12230 EV.idx_begin(), EV.idx_end());
12231 }
12232 if (exti == exte && insi == inse)
12233 // Both iterators are at the end: Index lists are identical. Replace
12234 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12235 // %C = extractvalue { i32, { i32 } } %B, 1, 0
12236 // with "i32 42"
12237 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12238 if (exti == exte) {
12239 // The extract list is a prefix of the insert list. i.e. replace
12240 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12241 // %E = extractvalue { i32, { i32 } } %I, 1
12242 // with
12243 // %X = extractvalue { i32, { i32 } } %A, 1
12244 // %E = insertvalue { i32 } %X, i32 42, 0
12245 // by switching the order of the insert and extract (though the
12246 // insertvalue should be left in, since it may have other uses).
12247 Value *NewEV = InsertNewInstBefore(
12248 ExtractValueInst::Create(IV->getAggregateOperand(),
12249 EV.idx_begin(), EV.idx_end()),
12250 EV);
12251 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12252 insi, inse);
12253 }
12254 if (insi == inse)
12255 // The insert list is a prefix of the extract list
12256 // We can simply remove the common indices from the extract and make it
12257 // operate on the inserted value instead of the insertvalue result.
12258 // i.e., replace
12259 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12260 // %E = extractvalue { i32, { i32 } } %I, 1, 0
12261 // with
12262 // %E extractvalue { i32 } { i32 42 }, 0
12263 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
12264 exti, exte);
12265 }
12266 // Can't simplify extracts from other values. Note that nested extracts are
12267 // already simplified implicitely by the above (extract ( extract (insert) )
12268 // will be translated into extract ( insert ( extract ) ) first and then just
12269 // the value inserted, if appropriate).
Matthijs Kooijmanb2fc72b2008-06-11 14:05:05 +000012270 return 0;
12271}
12272
Chris Lattner6bc98652006-03-05 00:22:33 +000012273/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12274/// is to leave as a vector operation.
12275static bool CheapToScalarize(Value *V, bool isConstant) {
12276 if (isa<ConstantAggregateZero>(V))
12277 return true;
Reid Spencerd84d35b2007-02-15 02:26:10 +000012278 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner6bc98652006-03-05 00:22:33 +000012279 if (isConstant) return true;
12280 // If all elts are the same, we can extract.
12281 Constant *Op0 = C->getOperand(0);
12282 for (unsigned i = 1; i < C->getNumOperands(); ++i)
12283 if (C->getOperand(i) != Op0)
12284 return false;
12285 return true;
12286 }
12287 Instruction *I = dyn_cast<Instruction>(V);
12288 if (!I) return false;
12289
12290 // Insert element gets simplified to the inserted element or is deleted if
12291 // this is constant idx extract element and its a constant idx insertelt.
12292 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12293 isa<ConstantInt>(I->getOperand(2)))
12294 return true;
12295 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12296 return true;
12297 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12298 if (BO->hasOneUse() &&
12299 (CheapToScalarize(BO->getOperand(0), isConstant) ||
12300 CheapToScalarize(BO->getOperand(1), isConstant)))
12301 return true;
Reid Spencer266e42b2006-12-23 06:05:41 +000012302 if (CmpInst *CI = dyn_cast<CmpInst>(I))
12303 if (CI->hasOneUse() &&
12304 (CheapToScalarize(CI->getOperand(0), isConstant) ||
12305 CheapToScalarize(CI->getOperand(1), isConstant)))
12306 return true;
Chris Lattner6bc98652006-03-05 00:22:33 +000012307
12308 return false;
12309}
12310
Chris Lattner945e4372007-02-14 05:52:17 +000012311/// Read and decode a shufflevector mask.
12312///
12313/// It turns undef elements into values that are larger than the number of
12314/// elements in the input.
Chris Lattner12249be2006-05-25 23:48:38 +000012315static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12316 unsigned NElts = SVI->getType()->getNumElements();
12317 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12318 return std::vector<unsigned>(NElts, 0);
12319 if (isa<UndefValue>(SVI->getOperand(2)))
12320 return std::vector<unsigned>(NElts, 2*NElts);
12321
12322 std::vector<unsigned> Result;
Reid Spencerd84d35b2007-02-15 02:26:10 +000012323 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Gabor Greiff6d8e772008-06-12 21:37:33 +000012324 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12325 if (isa<UndefValue>(*i))
Chris Lattner12249be2006-05-25 23:48:38 +000012326 Result.push_back(NElts*2); // undef -> 8
12327 else
Gabor Greiff6d8e772008-06-12 21:37:33 +000012328 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
Chris Lattner12249be2006-05-25 23:48:38 +000012329 return Result;
12330}
12331
Chris Lattner8d1d8d32006-03-31 23:01:56 +000012332/// FindScalarElement - Given a vector and an element number, see if the scalar
12333/// value is already around as a register, for example if it were inserted then
12334/// extracted from the vector.
Owen Andersonb5618da2009-07-03 00:17:18 +000012335static Value *FindScalarElement(Value *V, unsigned EltNo,
Owen Anderson38264b12009-07-06 23:00:19 +000012336 LLVMContext *Context) {
Reid Spencerd84d35b2007-02-15 02:26:10 +000012337 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12338 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner2d37f922006-04-10 23:06:36 +000012339 unsigned Width = PTy->getNumElements();
12340 if (EltNo >= Width) // Out of range access.
Owen Andersonb5618da2009-07-03 00:17:18 +000012341 return Context->getUndef(PTy->getElementType());
Chris Lattner8d1d8d32006-03-31 23:01:56 +000012342
12343 if (isa<UndefValue>(V))
Owen Andersonb5618da2009-07-03 00:17:18 +000012344 return Context->getUndef(PTy->getElementType());
Chris Lattner8d1d8d32006-03-31 23:01:56 +000012345 else if (isa<ConstantAggregateZero>(V))
Owen Andersonb5618da2009-07-03 00:17:18 +000012346 return Context->getNullValue(PTy->getElementType());
Reid Spencerd84d35b2007-02-15 02:26:10 +000012347 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner8d1d8d32006-03-31 23:01:56 +000012348 return CP->getOperand(EltNo);
12349 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12350 // If this is an insert to a variable element, we don't know what it is.
Reid Spencere0fc4df2006-10-20 07:07:24 +000012351 if (!isa<ConstantInt>(III->getOperand(2)))
12352 return 0;
12353 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner8d1d8d32006-03-31 23:01:56 +000012354
12355 // If this is an insert to the element we are looking for, return the
12356 // inserted value.
Reid Spencere0fc4df2006-10-20 07:07:24 +000012357 if (EltNo == IIElt)
12358 return III->getOperand(1);
Chris Lattner8d1d8d32006-03-31 23:01:56 +000012359
12360 // Otherwise, the insertelement doesn't modify the value, recurse on its
12361 // vector input.
Owen Andersonb5618da2009-07-03 00:17:18 +000012362 return FindScalarElement(III->getOperand(0), EltNo, Context);
Chris Lattner2d37f922006-04-10 23:06:36 +000012363 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Mon P Wang25f01062008-11-10 04:46:22 +000012364 unsigned LHSWidth =
12365 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
Chris Lattner12249be2006-05-25 23:48:38 +000012366 unsigned InEl = getShuffleMask(SVI)[EltNo];
Mon P Wang25f01062008-11-10 04:46:22 +000012367 if (InEl < LHSWidth)
Owen Andersonb5618da2009-07-03 00:17:18 +000012368 return FindScalarElement(SVI->getOperand(0), InEl, Context);
Mon P Wang25f01062008-11-10 04:46:22 +000012369 else if (InEl < LHSWidth*2)
Owen Andersonb5618da2009-07-03 00:17:18 +000012370 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
Chris Lattner12249be2006-05-25 23:48:38 +000012371 else
Owen Andersonb5618da2009-07-03 00:17:18 +000012372 return Context->getUndef(PTy->getElementType());
Chris Lattner8d1d8d32006-03-31 23:01:56 +000012373 }
12374
12375 // Otherwise, we don't know.
12376 return 0;
12377}
12378
Robert Bocchinoa8352962006-01-13 22:48:06 +000012379Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Dan Gohman06c60b62007-07-16 14:29:03 +000012380 // If vector val is undef, replace extract with scalar undef.
Chris Lattner92346c32006-03-31 18:25:14 +000012381 if (isa<UndefValue>(EI.getOperand(0)))
Owen Andersonb5618da2009-07-03 00:17:18 +000012382 return ReplaceInstUsesWith(EI, Context->getUndef(EI.getType()));
Chris Lattner92346c32006-03-31 18:25:14 +000012383
Dan Gohman06c60b62007-07-16 14:29:03 +000012384 // If vector val is constant 0, replace extract with scalar 0.
Chris Lattner92346c32006-03-31 18:25:14 +000012385 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
Owen Andersonb5618da2009-07-03 00:17:18 +000012386 return ReplaceInstUsesWith(EI, Context->getNullValue(EI.getType()));
Chris Lattner92346c32006-03-31 18:25:14 +000012387
Reid Spencerd84d35b2007-02-15 02:26:10 +000012388 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Matthijs Kooijman3453c7b2008-06-11 09:00:12 +000012389 // If vector val is constant with all elements the same, replace EI with
12390 // that element. When the elements are not identical, we cannot replace yet
12391 // (we do that below, but only when the index is constant).
Chris Lattner6bc98652006-03-05 00:22:33 +000012392 Constant *op0 = C->getOperand(0);
Robert Bocchinoa8352962006-01-13 22:48:06 +000012393 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner6bc98652006-03-05 00:22:33 +000012394 if (C->getOperand(i) != op0) {
12395 op0 = 0;
12396 break;
12397 }
12398 if (op0)
12399 return ReplaceInstUsesWith(EI, op0);
Robert Bocchinoa8352962006-01-13 22:48:06 +000012400 }
Chris Lattner6bc98652006-03-05 00:22:33 +000012401
Chris Lattner8d1d8d32006-03-31 23:01:56 +000012402 // If extracting a specified index from the vector, see if we can recursively
12403 // find a previously computed scalar that was inserted into the vector.
Reid Spencere0fc4df2006-10-20 07:07:24 +000012404 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattnera87c9f62007-04-09 01:37:55 +000012405 unsigned IndexVal = IdxC->getZExtValue();
12406 unsigned VectorWidth =
12407 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
12408
12409 // If this is extracting an invalid index, turn this into undef, to avoid
12410 // crashing the code below.
12411 if (IndexVal >= VectorWidth)
Owen Andersonb5618da2009-07-03 00:17:18 +000012412 return ReplaceInstUsesWith(EI, Context->getUndef(EI.getType()));
Chris Lattnera87c9f62007-04-09 01:37:55 +000012413
Chris Lattner2deeaea2006-10-05 06:55:50 +000012414 // This instruction only demands the single element from the input vector.
12415 // If the input vector has a single use, simplify it based on this use
12416 // property.
Chris Lattnera87c9f62007-04-09 01:37:55 +000012417 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Evan Cheng8542caa2009-02-03 10:05:09 +000012418 APInt UndefElts(VectorWidth, 0);
12419 APInt DemandedMask(VectorWidth, 1 << IndexVal);
Chris Lattner2deeaea2006-10-05 06:55:50 +000012420 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Evan Cheng8542caa2009-02-03 10:05:09 +000012421 DemandedMask, UndefElts)) {
Chris Lattner2deeaea2006-10-05 06:55:50 +000012422 EI.setOperand(0, V);
12423 return &EI;
12424 }
12425 }
12426
Owen Andersonb5618da2009-07-03 00:17:18 +000012427 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
Chris Lattner8d1d8d32006-03-31 23:01:56 +000012428 return ReplaceInstUsesWith(EI, Elt);
Chris Lattner7bfdd0a2007-04-14 23:02:14 +000012429
12430 // If the this extractelement is directly using a bitcast from a vector of
12431 // the same number of elements, see if we can find the source element from
12432 // it. In this case, we will end up needing to bitcast the scalars.
12433 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12434 if (const VectorType *VT =
12435 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12436 if (VT->getNumElements() == VectorWidth)
Owen Andersonb5618da2009-07-03 00:17:18 +000012437 if (Value *Elt = FindScalarElement(BCI->getOperand(0),
12438 IndexVal, Context))
Chris Lattner7bfdd0a2007-04-14 23:02:14 +000012439 return new BitCastInst(Elt, EI.getType());
12440 }
Chris Lattner2d37f922006-04-10 23:06:36 +000012441 }
Chris Lattner8d1d8d32006-03-31 23:01:56 +000012442
Chris Lattner83f65782006-05-25 22:53:38 +000012443 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchinoa8352962006-01-13 22:48:06 +000012444 if (I->hasOneUse()) {
12445 // Push extractelement into predecessor operation if legal and
12446 // profitable to do so
12447 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner6bc98652006-03-05 00:22:33 +000012448 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
12449 if (CheapToScalarize(BO, isConstantElt)) {
12450 ExtractElementInst *newEI0 =
12451 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
12452 EI.getName()+".lhs");
12453 ExtractElementInst *newEI1 =
12454 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
12455 EI.getName()+".rhs");
12456 InsertNewInstBefore(newEI0, EI);
12457 InsertNewInstBefore(newEI1, EI);
Gabor Greife1f6e4b2008-05-16 19:29:10 +000012458 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Chris Lattner6bc98652006-03-05 00:22:33 +000012459 }
Reid Spencerde46e482006-11-02 20:25:50 +000012460 } else if (isa<LoadInst>(I)) {
Christopher Lambedf07882007-12-17 01:12:55 +000012461 unsigned AS =
12462 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
Chris Lattner5a866122008-01-13 22:23:22 +000012463 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
Owen Andersonb5618da2009-07-03 00:17:18 +000012464 Context->getPointerType(EI.getType(), AS),EI);
Gabor Greif697e94c2008-05-15 10:04:30 +000012465 GetElementPtrInst *GEP =
12466 GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
Robert Bocchinoa8352962006-01-13 22:48:06 +000012467 InsertNewInstBefore(GEP, EI);
12468 return new LoadInst(GEP);
Chris Lattner83f65782006-05-25 22:53:38 +000012469 }
12470 }
12471 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
12472 // Extracting the inserted element?
12473 if (IE->getOperand(2) == EI.getOperand(1))
12474 return ReplaceInstUsesWith(EI, IE->getOperand(1));
12475 // If the inserted and extracted elements are constants, they must not
12476 // be the same value, extract from the pre-inserted value instead.
12477 if (isa<Constant>(IE->getOperand(2)) &&
12478 isa<Constant>(EI.getOperand(1))) {
12479 AddUsesToWorkList(EI);
12480 EI.setOperand(0, IE->getOperand(0));
12481 return &EI;
12482 }
12483 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12484 // If this is extracting an element from a shufflevector, figure out where
12485 // it came from and extract from the appropriate input element instead.
Reid Spencere0fc4df2006-10-20 07:07:24 +000012486 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12487 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner12249be2006-05-25 23:48:38 +000012488 Value *Src;
Mon P Wang25f01062008-11-10 04:46:22 +000012489 unsigned LHSWidth =
12490 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12491
12492 if (SrcIdx < LHSWidth)
Chris Lattner12249be2006-05-25 23:48:38 +000012493 Src = SVI->getOperand(0);
Mon P Wang25f01062008-11-10 04:46:22 +000012494 else if (SrcIdx < LHSWidth*2) {
12495 SrcIdx -= LHSWidth;
Chris Lattner12249be2006-05-25 23:48:38 +000012496 Src = SVI->getOperand(1);
12497 } else {
Owen Andersonb5618da2009-07-03 00:17:18 +000012498 return ReplaceInstUsesWith(EI, Context->getUndef(EI.getType()));
Chris Lattner612fa8e2006-03-30 22:02:40 +000012499 }
Chris Lattner2deeaea2006-10-05 06:55:50 +000012500 return new ExtractElementInst(Src, SrcIdx);
Robert Bocchinoa8352962006-01-13 22:48:06 +000012501 }
12502 }
Chris Lattner83f65782006-05-25 22:53:38 +000012503 }
Robert Bocchinoa8352962006-01-13 22:48:06 +000012504 return 0;
12505}
12506
Chris Lattner90951862006-04-16 00:51:47 +000012507/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12508/// elements from either LHS or RHS, return the shuffle mask and true.
12509/// Otherwise, return false.
12510static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
Owen Andersonb5618da2009-07-03 00:17:18 +000012511 std::vector<Constant*> &Mask,
Owen Anderson38264b12009-07-06 23:00:19 +000012512 LLVMContext *Context) {
Chris Lattner90951862006-04-16 00:51:47 +000012513 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12514 "Invalid CollectSingleShuffleElements");
Reid Spencerd84d35b2007-02-15 02:26:10 +000012515 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner90951862006-04-16 00:51:47 +000012516
12517 if (isa<UndefValue>(V)) {
Owen Andersonb5618da2009-07-03 00:17:18 +000012518 Mask.assign(NumElts, Context->getUndef(Type::Int32Ty));
Chris Lattner90951862006-04-16 00:51:47 +000012519 return true;
12520 } else if (V == LHS) {
12521 for (unsigned i = 0; i != NumElts; ++i)
Owen Andersonb5618da2009-07-03 00:17:18 +000012522 Mask.push_back(Context->getConstantInt(Type::Int32Ty, i));
Chris Lattner90951862006-04-16 00:51:47 +000012523 return true;
12524 } else if (V == RHS) {
12525 for (unsigned i = 0; i != NumElts; ++i)
Owen Andersonb5618da2009-07-03 00:17:18 +000012526 Mask.push_back(Context->getConstantInt(Type::Int32Ty, i+NumElts));
Chris Lattner90951862006-04-16 00:51:47 +000012527 return true;
12528 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12529 // If this is an insert of an extract from some other vector, include it.
12530 Value *VecOp = IEI->getOperand(0);
12531 Value *ScalarOp = IEI->getOperand(1);
12532 Value *IdxOp = IEI->getOperand(2);
12533
Chris Lattnerb6cb64b2006-04-27 21:14:21 +000012534 if (!isa<ConstantInt>(IdxOp))
12535 return false;
Reid Spencere0fc4df2006-10-20 07:07:24 +000012536 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerb6cb64b2006-04-27 21:14:21 +000012537
12538 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
12539 // Okay, we can handle this if the vector we are insertinting into is
12540 // transitively ok.
Owen Andersonb5618da2009-07-03 00:17:18 +000012541 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Chris Lattnerb6cb64b2006-04-27 21:14:21 +000012542 // If so, update the mask to reflect the inserted undef.
Owen Andersonb5618da2009-07-03 00:17:18 +000012543 Mask[InsertedIdx] = Context->getUndef(Type::Int32Ty);
Chris Lattnerb6cb64b2006-04-27 21:14:21 +000012544 return true;
12545 }
12546 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12547 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner90951862006-04-16 00:51:47 +000012548 EI->getOperand(0)->getType() == V->getType()) {
12549 unsigned ExtractedIdx =
Reid Spencere0fc4df2006-10-20 07:07:24 +000012550 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner90951862006-04-16 00:51:47 +000012551
12552 // This must be extracting from either LHS or RHS.
12553 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12554 // Okay, we can handle this if the vector we are insertinting into is
12555 // transitively ok.
Owen Andersonb5618da2009-07-03 00:17:18 +000012556 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Chris Lattner90951862006-04-16 00:51:47 +000012557 // If so, update the mask to reflect the inserted value.
12558 if (EI->getOperand(0) == LHS) {
Mon P Wang1b2c0612008-08-20 02:23:25 +000012559 Mask[InsertedIdx % NumElts] =
Owen Andersonb5618da2009-07-03 00:17:18 +000012560 Context->getConstantInt(Type::Int32Ty, ExtractedIdx);
Chris Lattner90951862006-04-16 00:51:47 +000012561 } else {
12562 assert(EI->getOperand(0) == RHS);
Mon P Wang1b2c0612008-08-20 02:23:25 +000012563 Mask[InsertedIdx % NumElts] =
Owen Andersonb5618da2009-07-03 00:17:18 +000012564 Context->getConstantInt(Type::Int32Ty, ExtractedIdx+NumElts);
Chris Lattner90951862006-04-16 00:51:47 +000012565
12566 }
12567 return true;
12568 }
12569 }
12570 }
12571 }
12572 }
12573 // TODO: Handle shufflevector here!
12574
12575 return false;
12576}
12577
12578/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12579/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
12580/// that computes V and the LHS value of the shuffle.
Chris Lattner39fac442006-04-15 01:39:45 +000012581static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Owen Anderson38264b12009-07-06 23:00:19 +000012582 Value *&RHS, LLVMContext *Context) {
Reid Spencerd84d35b2007-02-15 02:26:10 +000012583 assert(isa<VectorType>(V->getType()) &&
Chris Lattner90951862006-04-16 00:51:47 +000012584 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattner39fac442006-04-15 01:39:45 +000012585 "Invalid shuffle!");
Reid Spencerd84d35b2007-02-15 02:26:10 +000012586 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner39fac442006-04-15 01:39:45 +000012587
12588 if (isa<UndefValue>(V)) {
Owen Andersonb5618da2009-07-03 00:17:18 +000012589 Mask.assign(NumElts, Context->getUndef(Type::Int32Ty));
Chris Lattner39fac442006-04-15 01:39:45 +000012590 return V;
12591 } else if (isa<ConstantAggregateZero>(V)) {
Owen Andersonb5618da2009-07-03 00:17:18 +000012592 Mask.assign(NumElts, Context->getConstantInt(Type::Int32Ty, 0));
Chris Lattner39fac442006-04-15 01:39:45 +000012593 return V;
12594 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12595 // If this is an insert of an extract from some other vector, include it.
12596 Value *VecOp = IEI->getOperand(0);
12597 Value *ScalarOp = IEI->getOperand(1);
12598 Value *IdxOp = IEI->getOperand(2);
12599
12600 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12601 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12602 EI->getOperand(0)->getType() == V->getType()) {
12603 unsigned ExtractedIdx =
Reid Spencere0fc4df2006-10-20 07:07:24 +000012604 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12605 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattner39fac442006-04-15 01:39:45 +000012606
12607 // Either the extracted from or inserted into vector must be RHSVec,
12608 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner90951862006-04-16 00:51:47 +000012609 if (EI->getOperand(0) == RHS || RHS == 0) {
12610 RHS = EI->getOperand(0);
Owen Andersonb5618da2009-07-03 00:17:18 +000012611 Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
Mon P Wang1b2c0612008-08-20 02:23:25 +000012612 Mask[InsertedIdx % NumElts] =
Owen Andersonb5618da2009-07-03 00:17:18 +000012613 Context->getConstantInt(Type::Int32Ty, NumElts+ExtractedIdx);
Chris Lattner39fac442006-04-15 01:39:45 +000012614 return V;
12615 }
12616
Chris Lattner90951862006-04-16 00:51:47 +000012617 if (VecOp == RHS) {
Owen Andersonb5618da2009-07-03 00:17:18 +000012618 Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
12619 RHS, Context);
Chris Lattner39fac442006-04-15 01:39:45 +000012620 // Everything but the extracted element is replaced with the RHS.
12621 for (unsigned i = 0; i != NumElts; ++i) {
12622 if (i != InsertedIdx)
Owen Andersonb5618da2009-07-03 00:17:18 +000012623 Mask[i] = Context->getConstantInt(Type::Int32Ty, NumElts+i);
Chris Lattner39fac442006-04-15 01:39:45 +000012624 }
12625 return V;
12626 }
Chris Lattner90951862006-04-16 00:51:47 +000012627
12628 // If this insertelement is a chain that comes from exactly these two
12629 // vectors, return the vector and the effective shuffle.
Owen Andersonb5618da2009-07-03 00:17:18 +000012630 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
12631 Context))
Chris Lattner90951862006-04-16 00:51:47 +000012632 return EI->getOperand(0);
12633
Chris Lattner39fac442006-04-15 01:39:45 +000012634 }
12635 }
12636 }
Chris Lattner90951862006-04-16 00:51:47 +000012637 // TODO: Handle shufflevector here!
Chris Lattner39fac442006-04-15 01:39:45 +000012638
12639 // Otherwise, can't do anything fancy. Return an identity vector.
12640 for (unsigned i = 0; i != NumElts; ++i)
Owen Andersonb5618da2009-07-03 00:17:18 +000012641 Mask.push_back(Context->getConstantInt(Type::Int32Ty, i));
Chris Lattner39fac442006-04-15 01:39:45 +000012642 return V;
12643}
12644
12645Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12646 Value *VecOp = IE.getOperand(0);
12647 Value *ScalarOp = IE.getOperand(1);
12648 Value *IdxOp = IE.getOperand(2);
12649
Chris Lattner4ca9cbb2007-04-09 01:11:16 +000012650 // Inserting an undef or into an undefined place, remove this.
12651 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12652 ReplaceInstUsesWith(IE, VecOp);
12653
Chris Lattner39fac442006-04-15 01:39:45 +000012654 // If the inserted element was extracted from some other vector, and if the
12655 // indexes are constant, try to turn this into a shufflevector operation.
12656 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12657 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12658 EI->getOperand(0)->getType() == IE.getType()) {
12659 unsigned NumVectorElts = IE.getType()->getNumElements();
Chris Lattner28d921d2007-04-14 23:32:02 +000012660 unsigned ExtractedIdx =
12661 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Reid Spencere0fc4df2006-10-20 07:07:24 +000012662 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattner39fac442006-04-15 01:39:45 +000012663
12664 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12665 return ReplaceInstUsesWith(IE, VecOp);
12666
12667 if (InsertedIdx >= NumVectorElts) // Out of range insert.
Owen Andersonb5618da2009-07-03 00:17:18 +000012668 return ReplaceInstUsesWith(IE, Context->getUndef(IE.getType()));
Chris Lattner39fac442006-04-15 01:39:45 +000012669
12670 // If we are extracting a value from a vector, then inserting it right
12671 // back into the same place, just use the input vector.
12672 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12673 return ReplaceInstUsesWith(IE, VecOp);
12674
12675 // We could theoretically do this for ANY input. However, doing so could
12676 // turn chains of insertelement instructions into a chain of shufflevector
12677 // instructions, and right now we do not merge shufflevectors. As such,
12678 // only do this in a situation where it is clear that there is benefit.
12679 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
12680 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
12681 // the values of VecOp, except then one read from EIOp0.
12682 // Build a new shuffle mask.
12683 std::vector<Constant*> Mask;
12684 if (isa<UndefValue>(VecOp))
Owen Andersonb5618da2009-07-03 00:17:18 +000012685 Mask.assign(NumVectorElts, Context->getUndef(Type::Int32Ty));
Chris Lattner39fac442006-04-15 01:39:45 +000012686 else {
12687 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Owen Andersonb5618da2009-07-03 00:17:18 +000012688 Mask.assign(NumVectorElts, Context->getConstantInt(Type::Int32Ty,
Chris Lattner39fac442006-04-15 01:39:45 +000012689 NumVectorElts));
12690 }
Owen Andersonb5618da2009-07-03 00:17:18 +000012691 Mask[InsertedIdx] =
12692 Context->getConstantInt(Type::Int32Ty, ExtractedIdx);
Chris Lattner39fac442006-04-15 01:39:45 +000012693 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Owen Andersonb5618da2009-07-03 00:17:18 +000012694 Context->getConstantVector(Mask));
Chris Lattner39fac442006-04-15 01:39:45 +000012695 }
12696
12697 // If this insertelement isn't used by some other insertelement, turn it
12698 // (and any insertelements it points to), into one big shuffle.
12699 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12700 std::vector<Constant*> Mask;
Chris Lattner90951862006-04-16 00:51:47 +000012701 Value *RHS = 0;
Owen Andersonb5618da2009-07-03 00:17:18 +000012702 Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
12703 if (RHS == 0) RHS = Context->getUndef(LHS->getType());
Chris Lattner90951862006-04-16 00:51:47 +000012704 // We now have a shuffle of LHS, RHS, Mask.
Owen Andersonb5618da2009-07-03 00:17:18 +000012705 return new ShuffleVectorInst(LHS, RHS,
12706 Context->getConstantVector(Mask));
Chris Lattner39fac442006-04-15 01:39:45 +000012707 }
12708 }
12709 }
12710
Eli Friedman73a83062009-06-06 20:08:03 +000012711 unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
12712 APInt UndefElts(VWidth, 0);
12713 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12714 if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
12715 return &IE;
12716
Chris Lattner39fac442006-04-15 01:39:45 +000012717 return 0;
12718}
12719
12720
Chris Lattnerfbb77a42006-04-10 22:45:52 +000012721Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12722 Value *LHS = SVI.getOperand(0);
12723 Value *RHS = SVI.getOperand(1);
Chris Lattner12249be2006-05-25 23:48:38 +000012724 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnerfbb77a42006-04-10 22:45:52 +000012725
12726 bool MadeChange = false;
Mon P Wang25f01062008-11-10 04:46:22 +000012727
Chris Lattner2deeaea2006-10-05 06:55:50 +000012728 // Undefined shuffle mask -> undefined value.
Chris Lattner12249be2006-05-25 23:48:38 +000012729 if (isa<UndefValue>(SVI.getOperand(2)))
Owen Andersonb5618da2009-07-03 00:17:18 +000012730 return ReplaceInstUsesWith(SVI, Context->getUndef(SVI.getType()));
Dan Gohman86fb5b42008-09-09 18:11:14 +000012731
Dan Gohman86fb5b42008-09-09 18:11:14 +000012732 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
Mon P Wang25f01062008-11-10 04:46:22 +000012733
12734 if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12735 return 0;
12736
Evan Cheng8542caa2009-02-03 10:05:09 +000012737 APInt UndefElts(VWidth, 0);
12738 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12739 if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
Dan Gohman7d01c062008-09-11 22:47:57 +000012740 LHS = SVI.getOperand(0);
12741 RHS = SVI.getOperand(1);
Dan Gohman86fb5b42008-09-09 18:11:14 +000012742 MadeChange = true;
Dan Gohman7d01c062008-09-11 22:47:57 +000012743 }
Chris Lattner39fac442006-04-15 01:39:45 +000012744
Chris Lattner12249be2006-05-25 23:48:38 +000012745 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
12746 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12747 if (LHS == RHS || isa<UndefValue>(LHS)) {
12748 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnerfbb77a42006-04-10 22:45:52 +000012749 // shuffle(undef,undef,mask) -> undef.
12750 return ReplaceInstUsesWith(SVI, LHS);
12751 }
12752
Chris Lattner12249be2006-05-25 23:48:38 +000012753 // Remap any references to RHS to use LHS.
12754 std::vector<Constant*> Elts;
12755 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner0e477162006-05-26 00:29:06 +000012756 if (Mask[i] >= 2*e)
Owen Andersonb5618da2009-07-03 00:17:18 +000012757 Elts.push_back(Context->getUndef(Type::Int32Ty));
Chris Lattner0e477162006-05-26 00:29:06 +000012758 else {
12759 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
Dan Gohmanac22cfc2008-08-06 18:17:32 +000012760 (Mask[i] < e && isa<UndefValue>(LHS))) {
Chris Lattner0e477162006-05-26 00:29:06 +000012761 Mask[i] = 2*e; // Turn into undef.
Owen Andersonb5618da2009-07-03 00:17:18 +000012762 Elts.push_back(Context->getUndef(Type::Int32Ty));
Dan Gohmanac22cfc2008-08-06 18:17:32 +000012763 } else {
Mon P Wang1b2c0612008-08-20 02:23:25 +000012764 Mask[i] = Mask[i] % e; // Force to LHS.
Owen Andersonb5618da2009-07-03 00:17:18 +000012765 Elts.push_back(Context->getConstantInt(Type::Int32Ty, Mask[i]));
Dan Gohmanac22cfc2008-08-06 18:17:32 +000012766 }
Chris Lattner0e477162006-05-26 00:29:06 +000012767 }
Chris Lattnerfbb77a42006-04-10 22:45:52 +000012768 }
Chris Lattner12249be2006-05-25 23:48:38 +000012769 SVI.setOperand(0, SVI.getOperand(1));
Owen Andersonb5618da2009-07-03 00:17:18 +000012770 SVI.setOperand(1, Context->getUndef(RHS->getType()));
12771 SVI.setOperand(2, Context->getConstantVector(Elts));
Chris Lattner0e477162006-05-26 00:29:06 +000012772 LHS = SVI.getOperand(0);
12773 RHS = SVI.getOperand(1);
Chris Lattnerfbb77a42006-04-10 22:45:52 +000012774 MadeChange = true;
12775 }
12776
Chris Lattner0e477162006-05-26 00:29:06 +000012777 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner12249be2006-05-25 23:48:38 +000012778 bool isLHSID = true, isRHSID = true;
Chris Lattner34cebe72006-04-16 00:03:56 +000012779
Chris Lattner12249be2006-05-25 23:48:38 +000012780 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12781 if (Mask[i] >= e*2) continue; // Ignore undef values.
12782 // Is this an identity shuffle of the LHS value?
12783 isLHSID &= (Mask[i] == i);
12784
12785 // Is this an identity shuffle of the RHS value?
12786 isRHSID &= (Mask[i]-e == i);
Chris Lattner34cebe72006-04-16 00:03:56 +000012787 }
Chris Lattnerfbb77a42006-04-10 22:45:52 +000012788
Chris Lattner12249be2006-05-25 23:48:38 +000012789 // Eliminate identity shuffles.
12790 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12791 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnerfbb77a42006-04-10 22:45:52 +000012792
Chris Lattner0e477162006-05-26 00:29:06 +000012793 // If the LHS is a shufflevector itself, see if we can combine it with this
12794 // one without producing an unusual shuffle. Here we are really conservative:
12795 // we are absolutely afraid of producing a shuffle mask not in the input
12796 // program, because the code gen may not be smart enough to turn a merged
12797 // shuffle into two specific shuffles: it may produce worse code. As such,
12798 // we only merge two shuffles if the result is one of the two input shuffle
12799 // masks. In this case, merging the shuffles just removes one instruction,
12800 // which we know is safe. This is good for things like turning:
12801 // (splat(splat)) -> splat.
12802 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12803 if (isa<UndefValue>(RHS)) {
12804 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12805
12806 std::vector<unsigned> NewMask;
12807 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12808 if (Mask[i] >= 2*e)
12809 NewMask.push_back(2*e);
12810 else
12811 NewMask.push_back(LHSMask[Mask[i]]);
12812
12813 // If the result mask is equal to the src shuffle or this shuffle mask, do
12814 // the replacement.
12815 if (NewMask == LHSMask || NewMask == Mask) {
Mon P Wang3537a622009-01-26 04:39:00 +000012816 unsigned LHSInNElts =
12817 cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
Chris Lattner0e477162006-05-26 00:29:06 +000012818 std::vector<Constant*> Elts;
12819 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
Mon P Wang3537a622009-01-26 04:39:00 +000012820 if (NewMask[i] >= LHSInNElts*2) {
Owen Andersonb5618da2009-07-03 00:17:18 +000012821 Elts.push_back(Context->getUndef(Type::Int32Ty));
Chris Lattner0e477162006-05-26 00:29:06 +000012822 } else {
Owen Andersonb5618da2009-07-03 00:17:18 +000012823 Elts.push_back(Context->getConstantInt(Type::Int32Ty, NewMask[i]));
Chris Lattner0e477162006-05-26 00:29:06 +000012824 }
12825 }
12826 return new ShuffleVectorInst(LHSSVI->getOperand(0),
12827 LHSSVI->getOperand(1),
Owen Andersonb5618da2009-07-03 00:17:18 +000012828 Context->getConstantVector(Elts));
Chris Lattner0e477162006-05-26 00:29:06 +000012829 }
12830 }
12831 }
Chris Lattner4284f642007-01-30 22:32:46 +000012832
Chris Lattnerfbb77a42006-04-10 22:45:52 +000012833 return MadeChange ? &SVI : 0;
12834}
12835
12836
Robert Bocchinoa8352962006-01-13 22:48:06 +000012837
Chris Lattner39c98bb2004-12-08 23:43:58 +000012838
12839/// TryToSinkInstruction - Try to move the specified instruction from its
12840/// current block into the beginning of DestBlock, which can only happen if it's
12841/// safe to move the instruction past all of the instructions between it and the
12842/// end of its block.
12843static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12844 assert(I->hasOneUse() && "Invariants didn't hold!");
12845
Chris Lattnerc4f67e62005-10-27 17:13:11 +000012846 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Duncan Sands1efabaa2009-05-06 06:49:50 +000012847 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
Chris Lattnera4ee1f52008-05-09 15:07:33 +000012848 return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +000012849
Chris Lattner39c98bb2004-12-08 23:43:58 +000012850 // Do not sink alloca instructions out of the entry block.
Dan Gohmandcb291f2007-03-22 16:38:57 +000012851 if (isa<AllocaInst>(I) && I->getParent() ==
12852 &DestBlock->getParent()->getEntryBlock())
Chris Lattner39c98bb2004-12-08 23:43:58 +000012853 return false;
12854
Chris Lattnerf17a2fb2004-12-09 07:14:34 +000012855 // We can only sink load instructions if there is nothing between the load and
12856 // the end of block that could change the value.
Chris Lattner49a594e2008-05-08 17:37:37 +000012857 if (I->mayReadFromMemory()) {
12858 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Chris Lattnerf17a2fb2004-12-09 07:14:34 +000012859 Scan != E; ++Scan)
12860 if (Scan->mayWriteToMemory())
12861 return false;
Chris Lattnerf17a2fb2004-12-09 07:14:34 +000012862 }
Chris Lattner39c98bb2004-12-08 23:43:58 +000012863
Dan Gohmanf96e1372008-05-23 21:05:58 +000012864 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Chris Lattner39c98bb2004-12-08 23:43:58 +000012865
Dale Johannesene1bb2f82009-03-03 01:09:07 +000012866 CopyPrecedingStopPoint(I, InsertPos);
Chris Lattner9f269e42005-08-08 19:11:57 +000012867 I->moveBefore(InsertPos);
Chris Lattner39c98bb2004-12-08 23:43:58 +000012868 ++NumSunkInst;
12869 return true;
12870}
12871
Chris Lattnera36ee4e2006-05-10 19:00:36 +000012872
12873/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12874/// all reachable code to the worklist.
12875///
12876/// This has a couple of tricks to make the code faster and more powerful. In
12877/// particular, we constant fold and DCE instructions as we go, to avoid adding
12878/// them to the worklist (this significantly speeds up instcombine on code where
12879/// many instructions are dead or constant). Additionally, if we find a branch
12880/// whose condition is a known constant, we only visit the reachable successors.
12881///
12882static void AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner7907e5f2007-02-15 19:41:52 +000012883 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerb15e2b12007-03-02 21:28:56 +000012884 InstCombiner &IC,
Chris Lattner1443bc52006-05-11 17:11:52 +000012885 const TargetData *TD) {
Chris Lattner1d239152008-08-15 04:03:01 +000012886 SmallVector<BasicBlock*, 256> Worklist;
Chris Lattner12b89cc2007-03-23 19:17:18 +000012887 Worklist.push_back(BB);
Chris Lattnera36ee4e2006-05-10 19:00:36 +000012888
Chris Lattner12b89cc2007-03-23 19:17:18 +000012889 while (!Worklist.empty()) {
12890 BB = Worklist.back();
12891 Worklist.pop_back();
12892
12893 // We have now visited this block! If we've already been here, ignore it.
12894 if (!Visited.insert(BB)) continue;
Devang Patel7ed6c532008-11-19 18:56:50 +000012895
12896 DbgInfoIntrinsic *DBI_Prev = NULL;
Chris Lattner12b89cc2007-03-23 19:17:18 +000012897 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12898 Instruction *Inst = BBI++;
Chris Lattnera36ee4e2006-05-10 19:00:36 +000012899
Chris Lattner12b89cc2007-03-23 19:17:18 +000012900 // DCE instruction if trivially dead.
12901 if (isInstructionTriviallyDead(Inst)) {
12902 ++NumDeadInst;
12903 DOUT << "IC: DCE: " << *Inst;
12904 Inst->eraseFromParent();
12905 continue;
12906 }
12907
12908 // ConstantProp instruction if trivially constant.
Owen Anderson39f00cc2009-07-06 18:42:36 +000012909 if (Constant *C = ConstantFoldInstruction(Inst, BB->getContext(), TD)) {
Chris Lattner12b89cc2007-03-23 19:17:18 +000012910 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
12911 Inst->replaceAllUsesWith(C);
12912 ++NumConstProp;
12913 Inst->eraseFromParent();
12914 continue;
12915 }
Chris Lattnerd82e4a12007-07-20 22:06:41 +000012916
Devang Patel7ed6c532008-11-19 18:56:50 +000012917 // If there are two consecutive llvm.dbg.stoppoint calls then
12918 // it is likely that the optimizer deleted code in between these
12919 // two intrinsics.
12920 DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12921 if (DBI_Next) {
12922 if (DBI_Prev
12923 && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12924 && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
12925 IC.RemoveFromWorkList(DBI_Prev);
12926 DBI_Prev->eraseFromParent();
12927 }
12928 DBI_Prev = DBI_Next;
Zhou Sheng3a86bcf2009-02-23 10:14:11 +000012929 } else {
12930 DBI_Prev = 0;
Devang Patel7ed6c532008-11-19 18:56:50 +000012931 }
12932
Chris Lattner12b89cc2007-03-23 19:17:18 +000012933 IC.AddToWorkList(Inst);
Chris Lattnera36ee4e2006-05-10 19:00:36 +000012934 }
Chris Lattner12b89cc2007-03-23 19:17:18 +000012935
12936 // Recursively visit successors. If this is a branch or switch on a
12937 // constant, only visit the reachable successor.
12938 TerminatorInst *TI = BB->getTerminator();
12939 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12940 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12941 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky271506f2008-03-09 08:50:23 +000012942 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewycky4d43d3c2008-04-25 16:53:59 +000012943 Worklist.push_back(ReachableBB);
Chris Lattner12b89cc2007-03-23 19:17:18 +000012944 continue;
12945 }
12946 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12947 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12948 // See if this is an explicit destination.
12949 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12950 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky271506f2008-03-09 08:50:23 +000012951 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewycky4d43d3c2008-04-25 16:53:59 +000012952 Worklist.push_back(ReachableBB);
Chris Lattner12b89cc2007-03-23 19:17:18 +000012953 continue;
12954 }
12955
12956 // Otherwise it is the default destination.
12957 Worklist.push_back(SI->getSuccessor(0));
12958 continue;
12959 }
12960 }
12961
12962 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12963 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnera36ee4e2006-05-10 19:00:36 +000012964 }
Chris Lattnera36ee4e2006-05-10 19:00:36 +000012965}
12966
Chris Lattner960a5432007-03-03 02:04:50 +000012967bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattner260ab202002-04-18 17:39:14 +000012968 bool Changed = false;
Chris Lattnerf4ad1652003-11-02 05:57:39 +000012969 TD = &getAnalysis<TargetData>();
Chris Lattner960a5432007-03-03 02:04:50 +000012970
12971 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12972 << F.getNameStr() << "\n");
Chris Lattnerca081252001-12-14 16:52:21 +000012973
Chris Lattner4ed40f72005-07-07 20:40:38 +000012974 {
Chris Lattnera36ee4e2006-05-10 19:00:36 +000012975 // Do a depth-first traversal of the function, populate the worklist with
12976 // the reachable instructions. Ignore blocks that are not reachable. Keep
12977 // track of which blocks we visit.
Chris Lattner7907e5f2007-02-15 19:41:52 +000012978 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerb15e2b12007-03-02 21:28:56 +000012979 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +000012980
Chris Lattner4ed40f72005-07-07 20:40:38 +000012981 // Do a quick scan over the function. If we find any blocks that are
12982 // unreachable, remove any instructions inside of them. This prevents
12983 // the instcombine code from having to deal with some bad special cases.
12984 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12985 if (!Visited.count(BB)) {
12986 Instruction *Term = BB->getTerminator();
12987 while (Term != BB->begin()) { // Remove instrs bottom-up
12988 BasicBlock::iterator I = Term; --I;
Chris Lattner2d3a7a62004-04-27 15:13:33 +000012989
Bill Wendling5dbf43c2006-11-26 09:46:52 +000012990 DOUT << "IC: DCE: " << *I;
Dale Johannesen703703a2009-03-10 21:19:49 +000012991 // A debug intrinsic shouldn't force another iteration if we weren't
12992 // going to do one without it.
12993 if (!isa<DbgInfoIntrinsic>(I)) {
12994 ++NumDeadInst;
12995 Changed = true;
12996 }
Chris Lattner4ed40f72005-07-07 20:40:38 +000012997 if (!I->use_empty())
Owen Andersonb5618da2009-07-03 00:17:18 +000012998 I->replaceAllUsesWith(Context->getUndef(I->getType()));
Chris Lattner4ed40f72005-07-07 20:40:38 +000012999 I->eraseFromParent();
13000 }
13001 }
13002 }
Chris Lattnerca081252001-12-14 16:52:21 +000013003
Chris Lattnerb15e2b12007-03-02 21:28:56 +000013004 while (!Worklist.empty()) {
13005 Instruction *I = RemoveOneFromWorkList();
13006 if (I == 0) continue; // skip null values.
Chris Lattnerca081252001-12-14 16:52:21 +000013007
Chris Lattner1443bc52006-05-11 17:11:52 +000013008 // Check to see if we can DCE the instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +000013009 if (isInstructionTriviallyDead(I)) {
Chris Lattner1443bc52006-05-11 17:11:52 +000013010 // Add operands to the worklist.
Chris Lattnere8ed4ef2003-10-06 17:11:01 +000013011 if (I->getNumOperands() < 4)
Chris Lattner51ea1272004-02-28 05:22:00 +000013012 AddUsesToWorkList(*I);
Chris Lattner99f48c62002-09-02 04:59:56 +000013013 ++NumDeadInst;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +000013014
Bill Wendling5dbf43c2006-11-26 09:46:52 +000013015 DOUT << "IC: DCE: " << *I;
Chris Lattnercd517ff2005-01-28 19:32:01 +000013016
13017 I->eraseFromParent();
Chris Lattnerb15e2b12007-03-02 21:28:56 +000013018 RemoveFromWorkList(I);
Chris Lattner94cfb2812009-01-31 07:04:22 +000013019 Changed = true;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +000013020 continue;
13021 }
Chris Lattner99f48c62002-09-02 04:59:56 +000013022
Chris Lattner1443bc52006-05-11 17:11:52 +000013023 // Instruction isn't dead, see if we can constant propagate it.
Owen Anderson39f00cc2009-07-06 18:42:36 +000013024 if (Constant *C = ConstantFoldInstruction(I, F.getContext(), TD)) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +000013025 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
Chris Lattnercd517ff2005-01-28 19:32:01 +000013026
Chris Lattner1443bc52006-05-11 17:11:52 +000013027 // Add operands to the worklist.
Chris Lattner51ea1272004-02-28 05:22:00 +000013028 AddUsesToWorkList(*I);
Chris Lattnerc6509f42002-12-05 22:41:53 +000013029 ReplaceInstUsesWith(*I, C);
13030
Chris Lattner99f48c62002-09-02 04:59:56 +000013031 ++NumConstProp;
Chris Lattnera36ee4e2006-05-10 19:00:36 +000013032 I->eraseFromParent();
Chris Lattnerb15e2b12007-03-02 21:28:56 +000013033 RemoveFromWorkList(I);
Chris Lattner94cfb2812009-01-31 07:04:22 +000013034 Changed = true;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +000013035 continue;
Chris Lattner99f48c62002-09-02 04:59:56 +000013036 }
Chris Lattnere8ed4ef2003-10-06 17:11:01 +000013037
Dan Gohman140a6f242009-05-07 19:43:39 +000013038 if (TD &&
13039 (I->getType()->getTypeID() == Type::VoidTyID ||
13040 I->isTrapping())) {
Nick Lewyckyf6ccd252008-05-25 20:56:15 +000013041 // See if we can constant fold its operands.
Chris Lattner94cfb2812009-01-31 07:04:22 +000013042 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
13043 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i))
Owen Anderson39f00cc2009-07-06 18:42:36 +000013044 if (Constant *NewC = ConstantFoldConstantExpression(CE,
13045 F.getContext(), TD))
Chris Lattner94cfb2812009-01-31 07:04:22 +000013046 if (NewC != CE) {
13047 i->set(NewC);
13048 Changed = true;
13049 }
Nick Lewyckyf6ccd252008-05-25 20:56:15 +000013050 }
13051
Chris Lattner39c98bb2004-12-08 23:43:58 +000013052 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohmanfa1211f2008-07-23 00:34:11 +000013053 if (I->hasOneUse()) {
Chris Lattner39c98bb2004-12-08 23:43:58 +000013054 BasicBlock *BB = I->getParent();
13055 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
13056 if (UserParent != BB) {
13057 bool UserIsSuccessor = false;
13058 // See if the user is one of our successors.
13059 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
13060 if (*SI == UserParent) {
13061 UserIsSuccessor = true;
13062 break;
13063 }
13064
13065 // If the user is one of our immediate successors, and if that successor
13066 // only has us as a predecessors (we'd have to split the critical edge
13067 // otherwise), we can keep going.
13068 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
13069 next(pred_begin(UserParent)) == pred_end(UserParent))
13070 // Okay, the CFG is simple enough, try to sink this instruction.
13071 Changed |= TryToSinkInstruction(I, UserParent);
13072 }
13073 }
13074
Chris Lattnerca081252001-12-14 16:52:21 +000013075 // Now that we have an instruction, try combining it to simplify it...
Reid Spencer755d0e72007-03-26 17:44:01 +000013076#ifndef NDEBUG
13077 std::string OrigI;
13078#endif
13079 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
Chris Lattnerae7a0d32002-08-02 19:29:35 +000013080 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +000013081 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +000013082 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +000013083 if (Result != I) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +000013084 DOUT << "IC: Old = " << *I
13085 << " New = " << *Result;
Chris Lattner7d2a5392004-03-13 23:54:27 +000013086
Chris Lattner396dbfe2004-06-09 05:08:07 +000013087 // Everything uses the new instruction now.
13088 I->replaceAllUsesWith(Result);
13089
13090 // Push the new instruction and any users onto the worklist.
Chris Lattnerb15e2b12007-03-02 21:28:56 +000013091 AddToWorkList(Result);
Chris Lattner396dbfe2004-06-09 05:08:07 +000013092 AddUsersToWorkList(*Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +000013093
Chris Lattner6e0123b2007-02-11 01:23:03 +000013094 // Move the name to the new instruction first.
13095 Result->takeName(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +000013096
13097 // Insert the new instruction into the basic block...
13098 BasicBlock *InstParent = I->getParent();
Chris Lattner7515cab2004-11-14 19:13:23 +000013099 BasicBlock::iterator InsertPos = I;
13100
13101 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
13102 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
13103 ++InsertPos;
13104
13105 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +000013106
Chris Lattner63d75af2004-05-01 23:27:23 +000013107 // Make sure that we reprocess all operands now that we reduced their
13108 // use counts.
Chris Lattnerb15e2b12007-03-02 21:28:56 +000013109 AddUsesToWorkList(*I);
Chris Lattnerb643a9e2004-05-01 23:19:52 +000013110
Chris Lattner396dbfe2004-06-09 05:08:07 +000013111 // Instructions can end up on the worklist more than once. Make sure
13112 // we do not process an instruction that has been deleted.
Chris Lattnerb15e2b12007-03-02 21:28:56 +000013113 RemoveFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +000013114
13115 // Erase the old instruction.
13116 InstParent->getInstList().erase(I);
Chris Lattner113f4f42002-06-25 16:13:24 +000013117 } else {
Evan Chenga4ed8a52007-03-27 16:44:48 +000013118#ifndef NDEBUG
Reid Spencer755d0e72007-03-26 17:44:01 +000013119 DOUT << "IC: Mod = " << OrigI
13120 << " New = " << *I;
Evan Chenga4ed8a52007-03-27 16:44:48 +000013121#endif
Chris Lattner7d2a5392004-03-13 23:54:27 +000013122
Chris Lattnerae7a0d32002-08-02 19:29:35 +000013123 // If the instruction was modified, it's possible that it is now dead.
13124 // if so, remove it.
Chris Lattner63d75af2004-05-01 23:27:23 +000013125 if (isInstructionTriviallyDead(I)) {
13126 // Make sure we process all operands now that we are reducing their
13127 // use counts.
Chris Lattner960a5432007-03-03 02:04:50 +000013128 AddUsesToWorkList(*I);
Misha Brukmanb1c93172005-04-21 23:48:37 +000013129
Chris Lattner63d75af2004-05-01 23:27:23 +000013130 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchinoa8352962006-01-13 22:48:06 +000013131 // occurrences of this instruction.
Chris Lattnerb15e2b12007-03-02 21:28:56 +000013132 RemoveFromWorkList(I);
Chris Lattner31f486c2005-01-31 05:36:43 +000013133 I->eraseFromParent();
Chris Lattner396dbfe2004-06-09 05:08:07 +000013134 } else {
Chris Lattner960a5432007-03-03 02:04:50 +000013135 AddToWorkList(I);
13136 AddUsersToWorkList(*I);
Chris Lattnerae7a0d32002-08-02 19:29:35 +000013137 }
Chris Lattner053c0932002-05-14 15:24:07 +000013138 }
Chris Lattner260ab202002-04-18 17:39:14 +000013139 Changed = true;
Chris Lattnerca081252001-12-14 16:52:21 +000013140 }
13141 }
13142
Chris Lattner960a5432007-03-03 02:04:50 +000013143 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattnerf0da7972007-08-05 08:47:58 +000013144
13145 // Do an explicit clear, this shrinks the map if needed.
13146 WorklistMap.clear();
Chris Lattner260ab202002-04-18 17:39:14 +000013147 return Changed;
Chris Lattner04805fa2002-02-26 21:46:54 +000013148}
13149
Chris Lattner960a5432007-03-03 02:04:50 +000013150
13151bool InstCombiner::runOnFunction(Function &F) {
Chris Lattner8258b442007-03-04 04:27:24 +000013152 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
13153
Chris Lattner960a5432007-03-03 02:04:50 +000013154 bool EverMadeChange = false;
13155
13156 // Iterate while there is work to do.
13157 unsigned Iteration = 0;
Bill Wendling37169522008-05-14 22:45:20 +000013158 while (DoOneIteration(F, Iteration++))
Chris Lattner960a5432007-03-03 02:04:50 +000013159 EverMadeChange = true;
13160 return EverMadeChange;
13161}
13162
Brian Gaeke38b79e82004-07-27 17:43:21 +000013163FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +000013164 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +000013165}