blob: bab6616deda58d775af603dfac58b6f1ca40aeed [file] [log] [blame]
Chris Lattner233f7dc2002-08-12 21:17:25 +00001//===- InstructionCombining.cpp - Combine multiple instructions -----------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner8a2a3112001-12-14 16:52:21 +00009//
10// InstructionCombining - Combine instructions to form fewer, simple
Chris Lattner62b14df2002-09-02 04:59:56 +000011// instructions. This pass does not modify the CFG This pass is where algebraic
12// simplification happens.
Chris Lattner8a2a3112001-12-14 16:52:21 +000013//
14// This pass combines things like:
Chris Lattner318bf792007-03-18 22:51:34 +000015// %Y = add i32 %X, 1
16// %Z = add i32 %Y, 1
Chris Lattner8a2a3112001-12-14 16:52:21 +000017// into:
Chris Lattner318bf792007-03-18 22:51:34 +000018// %Z = add i32 %X, 2
Chris Lattner8a2a3112001-12-14 16:52:21 +000019//
20// This is a simple worklist driven algorithm.
21//
Chris Lattner065a6162003-09-10 05:29:43 +000022// This pass guarantees that the following canonicalizations are performed on
Chris Lattner2cd91962003-07-23 21:41:57 +000023// the program:
24// 1. If a binary operator has a constant operand, it is moved to the RHS
Chris Lattnerdf17af12003-08-12 21:53:41 +000025// 2. Bitwise operators with constant operands are always grouped so that
26// shifts are performed first, then or's, then and's, then xor's.
Reid Spencere4d87aa2006-12-23 06:05:41 +000027// 3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
28// 4. All cmp instructions on boolean values are replaced with logical ops
Chris Lattnere92d2f42003-08-13 04:18:28 +000029// 5. add X, X is represented as (X*2) => (X << 1)
30// 6. Multiplies with a power-of-two constant argument are transformed into
31// shifts.
Chris Lattnerbac32862004-11-14 19:13:23 +000032// ... etc.
Chris Lattner2cd91962003-07-23 21:41:57 +000033//
Chris Lattner8a2a3112001-12-14 16:52:21 +000034//===----------------------------------------------------------------------===//
35
Chris Lattner0cea42a2004-03-13 23:54:27 +000036#define DEBUG_TYPE "instcombine"
Chris Lattner022103b2002-05-07 20:03:00 +000037#include "llvm/Transforms/Scalar.h"
Chris Lattner35b9e482004-10-12 04:52:52 +000038#include "llvm/IntrinsicInst.h"
Chris Lattnerbd0ef772002-02-26 21:46:54 +000039#include "llvm/Pass.h"
Chris Lattner0864acf2002-11-04 16:18:53 +000040#include "llvm/DerivedTypes.h"
Chris Lattner833b8a42003-06-26 05:06:25 +000041#include "llvm/GlobalVariable.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000042#include "llvm/Analysis/ConstantFolding.h"
Chris Lattnerbc61e662003-11-02 05:57:39 +000043#include "llvm/Target/TargetData.h"
44#include "llvm/Transforms/Utils/BasicBlockUtils.h"
45#include "llvm/Transforms/Utils/Local.h"
Chris Lattner28977af2004-04-05 01:30:19 +000046#include "llvm/Support/CallSite.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000047#include "llvm/Support/Debug.h"
Chris Lattner28977af2004-04-05 01:30:19 +000048#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattnerdd841ae2002-04-18 17:39:14 +000049#include "llvm/Support/InstVisitor.h"
Chris Lattnerbcd7db52005-08-02 19:16:58 +000050#include "llvm/Support/MathExtras.h"
Chris Lattneracd1f0f2004-07-30 07:50:03 +000051#include "llvm/Support/PatternMatch.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000052#include "llvm/Support/Compiler.h"
Chris Lattnerdbab3862007-03-02 21:28:56 +000053#include "llvm/ADT/DenseMap.h"
Chris Lattner55eb1c42007-01-31 04:40:53 +000054#include "llvm/ADT/SmallVector.h"
Chris Lattner1f87a582007-02-15 19:41:52 +000055#include "llvm/ADT/SmallPtrSet.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000056#include "llvm/ADT/Statistic.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000057#include "llvm/ADT/STLExtras.h"
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000058#include <algorithm>
Reid Spencera9b81012007-03-26 17:44:01 +000059#include <sstream>
Chris Lattner67b1e1b2003-12-07 01:24:23 +000060using namespace llvm;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000061using namespace llvm::PatternMatch;
Brian Gaeked0fde302003-11-11 22:41:34 +000062
Chris Lattner0e5f4992006-12-19 21:40:18 +000063STATISTIC(NumCombined , "Number of insts combined");
64STATISTIC(NumConstProp, "Number of constant folds");
65STATISTIC(NumDeadInst , "Number of dead inst eliminated");
66STATISTIC(NumDeadStore, "Number of dead stores eliminated");
67STATISTIC(NumSunkInst , "Number of instructions sunk");
Chris Lattnera92f6962002-10-01 22:38:41 +000068
Chris Lattner0e5f4992006-12-19 21:40:18 +000069namespace {
Chris Lattnerf4b54612006-06-28 22:08:15 +000070 class VISIBILITY_HIDDEN InstCombiner
71 : public FunctionPass,
72 public InstVisitor<InstCombiner, Instruction*> {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000073 // Worklist of all of the instructions that need to be simplified.
Chris Lattnerdbab3862007-03-02 21:28:56 +000074 std::vector<Instruction*> Worklist;
75 DenseMap<Instruction*, unsigned> WorklistMap;
Chris Lattnerbc61e662003-11-02 05:57:39 +000076 TargetData *TD;
Chris Lattnerf964f322007-03-04 04:27:24 +000077 bool MustPreserveLCSSA;
Chris Lattnerdbab3862007-03-02 21:28:56 +000078 public:
Nick Lewyckyecd94c82007-05-06 13:37:16 +000079 static char ID; // Pass identification, replacement for typeid
Devang Patel794fd752007-05-01 21:15:47 +000080 InstCombiner() : FunctionPass((intptr_t)&ID) {}
81
Chris Lattnerdbab3862007-03-02 21:28:56 +000082 /// AddToWorkList - Add the specified instruction to the worklist if it
83 /// isn't already in it.
84 void AddToWorkList(Instruction *I) {
85 if (WorklistMap.insert(std::make_pair(I, Worklist.size())))
86 Worklist.push_back(I);
87 }
88
89 // RemoveFromWorkList - remove I from the worklist if it exists.
90 void RemoveFromWorkList(Instruction *I) {
91 DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
92 if (It == WorklistMap.end()) return; // Not in worklist.
93
94 // Don't bother moving everything down, just null out the slot.
95 Worklist[It->second] = 0;
96
97 WorklistMap.erase(It);
98 }
99
100 Instruction *RemoveOneFromWorkList() {
101 Instruction *I = Worklist.back();
102 Worklist.pop_back();
103 WorklistMap.erase(I);
104 return I;
105 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000106
Chris Lattnerdbab3862007-03-02 21:28:56 +0000107
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000108 /// AddUsersToWorkList - When an instruction is simplified, add all users of
109 /// the instruction to the work lists because they might get more simplified
110 /// now.
111 ///
Chris Lattner6dce1a72006-02-07 06:56:34 +0000112 void AddUsersToWorkList(Value &I) {
Chris Lattner7e708292002-06-25 16:13:24 +0000113 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000114 UI != UE; ++UI)
Chris Lattnerdbab3862007-03-02 21:28:56 +0000115 AddToWorkList(cast<Instruction>(*UI));
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000116 }
117
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000118 /// AddUsesToWorkList - When an instruction is simplified, add operands to
119 /// the work lists because they might get more simplified now.
120 ///
121 void AddUsesToWorkList(Instruction &I) {
122 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
123 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
Chris Lattnerdbab3862007-03-02 21:28:56 +0000124 AddToWorkList(Op);
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000125 }
Chris Lattner867b99f2006-10-05 06:55:50 +0000126
127 /// AddSoonDeadInstToWorklist - The specified instruction is about to become
128 /// dead. Add all of its operands to the worklist, turning them into
129 /// undef's to reduce the number of uses of those instructions.
130 ///
131 /// Return the specified operand before it is turned into an undef.
132 ///
133 Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
134 Value *R = I.getOperand(op);
135
136 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
137 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i))) {
Chris Lattnerdbab3862007-03-02 21:28:56 +0000138 AddToWorkList(Op);
Chris Lattner867b99f2006-10-05 06:55:50 +0000139 // Set the operand to undef to drop the use.
140 I.setOperand(i, UndefValue::get(Op->getType()));
141 }
142
143 return R;
144 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000145
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000146 public:
Chris Lattner7e708292002-06-25 16:13:24 +0000147 virtual bool runOnFunction(Function &F);
Chris Lattnerec9c3582007-03-03 02:04:50 +0000148
149 bool DoOneIteration(Function &F, unsigned ItNum);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000150
Chris Lattner97e52e42002-04-28 21:27:06 +0000151 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerbc61e662003-11-02 05:57:39 +0000152 AU.addRequired<TargetData>();
Owen Andersond1b78a12006-07-10 19:03:49 +0000153 AU.addPreservedID(LCSSAID);
Chris Lattnercb2610e2002-10-21 20:00:28 +0000154 AU.setPreservesCFG();
Chris Lattner97e52e42002-04-28 21:27:06 +0000155 }
156
Chris Lattner28977af2004-04-05 01:30:19 +0000157 TargetData &getTargetData() const { return *TD; }
158
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000159 // Visitation implementation - Implement instruction combining for different
160 // instruction types. The semantics are as follows:
161 // Return Value:
162 // null - No change was made
Chris Lattner233f7dc2002-08-12 21:17:25 +0000163 // I - Change was made, I is still valid, I may be dead though
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000164 // otherwise - Change was made, replace I with returned instruction
Misha Brukmanfd939082005-04-21 23:48:37 +0000165 //
Chris Lattner7e708292002-06-25 16:13:24 +0000166 Instruction *visitAdd(BinaryOperator &I);
167 Instruction *visitSub(BinaryOperator &I);
168 Instruction *visitMul(BinaryOperator &I);
Reid Spencer0a783f72006-11-02 01:53:59 +0000169 Instruction *visitURem(BinaryOperator &I);
170 Instruction *visitSRem(BinaryOperator &I);
171 Instruction *visitFRem(BinaryOperator &I);
172 Instruction *commonRemTransforms(BinaryOperator &I);
173 Instruction *commonIRemTransforms(BinaryOperator &I);
Reid Spencer1628cec2006-10-26 06:15:43 +0000174 Instruction *commonDivTransforms(BinaryOperator &I);
175 Instruction *commonIDivTransforms(BinaryOperator &I);
176 Instruction *visitUDiv(BinaryOperator &I);
177 Instruction *visitSDiv(BinaryOperator &I);
178 Instruction *visitFDiv(BinaryOperator &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000179 Instruction *visitAnd(BinaryOperator &I);
180 Instruction *visitOr (BinaryOperator &I);
181 Instruction *visitXor(BinaryOperator &I);
Reid Spencer832254e2007-02-02 02:16:23 +0000182 Instruction *visitShl(BinaryOperator &I);
183 Instruction *visitAShr(BinaryOperator &I);
184 Instruction *visitLShr(BinaryOperator &I);
185 Instruction *commonShiftTransforms(BinaryOperator &I);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000186 Instruction *visitFCmpInst(FCmpInst &I);
187 Instruction *visitICmpInst(ICmpInst &I);
188 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
Chris Lattner01deb9d2007-04-03 17:43:25 +0000189 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
190 Instruction *LHS,
191 ConstantInt *RHS);
Chris Lattner484d3cf2005-04-24 06:59:08 +0000192
Reid Spencere4d87aa2006-12-23 06:05:41 +0000193 Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
194 ICmpInst::Predicate Cond, Instruction &I);
Reid Spencerb83eb642006-10-20 07:07:24 +0000195 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +0000196 BinaryOperator &I);
Reid Spencer3da59db2006-11-27 01:05:10 +0000197 Instruction *commonCastTransforms(CastInst &CI);
198 Instruction *commonIntCastTransforms(CastInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000199 Instruction *commonPointerCastTransforms(CastInst &CI);
Chris Lattner8a9f5712007-04-11 06:57:46 +0000200 Instruction *visitTrunc(TruncInst &CI);
201 Instruction *visitZExt(ZExtInst &CI);
202 Instruction *visitSExt(SExtInst &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000203 Instruction *visitFPTrunc(CastInst &CI);
204 Instruction *visitFPExt(CastInst &CI);
205 Instruction *visitFPToUI(CastInst &CI);
206 Instruction *visitFPToSI(CastInst &CI);
207 Instruction *visitUIToFP(CastInst &CI);
208 Instruction *visitSIToFP(CastInst &CI);
209 Instruction *visitPtrToInt(CastInst &CI);
210 Instruction *visitIntToPtr(CastInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000211 Instruction *visitBitCast(BitCastInst &CI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +0000212 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
213 Instruction *FI);
Chris Lattner3d69f462004-03-12 05:52:32 +0000214 Instruction *visitSelectInst(SelectInst &CI);
Chris Lattner9fe38862003-06-19 17:00:31 +0000215 Instruction *visitCallInst(CallInst &CI);
216 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner7e708292002-06-25 16:13:24 +0000217 Instruction *visitPHINode(PHINode &PN);
218 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner0864acf2002-11-04 16:18:53 +0000219 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner67b1e1b2003-12-07 01:24:23 +0000220 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner833b8a42003-06-26 05:06:25 +0000221 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner2f503e62005-01-31 05:36:43 +0000222 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattnerc4d10eb2003-06-04 04:46:00 +0000223 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner46238a62004-07-03 00:26:11 +0000224 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattnerefb47352006-04-15 01:39:45 +0000225 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchino1d7456d2006-01-13 22:48:06 +0000226 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +0000227 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000228
229 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner7e708292002-06-25 16:13:24 +0000230 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner8b170942002-08-09 23:47:40 +0000231
Chris Lattner9fe38862003-06-19 17:00:31 +0000232 private:
Chris Lattnera44d8a22003-10-07 22:32:43 +0000233 Instruction *visitCallSite(CallSite CS);
Chris Lattner9fe38862003-06-19 17:00:31 +0000234 bool transformConstExprCastCall(CallSite CS);
235
Chris Lattner28977af2004-04-05 01:30:19 +0000236 public:
Chris Lattner8b170942002-08-09 23:47:40 +0000237 // InsertNewInstBefore - insert an instruction New before instruction Old
238 // in the program. Add the new instruction to the worklist.
239 //
Chris Lattner955f3312004-09-28 21:48:02 +0000240 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattnere6f9a912002-08-23 18:32:43 +0000241 assert(New && New->getParent() == 0 &&
242 "New instruction already inserted into a basic block!");
Chris Lattner8b170942002-08-09 23:47:40 +0000243 BasicBlock *BB = Old.getParent();
244 BB->getInstList().insert(&Old, New); // Insert inst
Chris Lattnerdbab3862007-03-02 21:28:56 +0000245 AddToWorkList(New);
Chris Lattner4cb170c2004-02-23 06:38:22 +0000246 return New;
Chris Lattner8b170942002-08-09 23:47:40 +0000247 }
248
Chris Lattner0c967662004-09-24 15:21:34 +0000249 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
250 /// This also adds the cast to the worklist. Finally, this returns the
251 /// cast.
Reid Spencer17212df2006-12-12 09:18:51 +0000252 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
253 Instruction &Pos) {
Chris Lattner0c967662004-09-24 15:21:34 +0000254 if (V->getType() == Ty) return V;
Misha Brukmanfd939082005-04-21 23:48:37 +0000255
Chris Lattnere2ed0572006-04-06 19:19:17 +0000256 if (Constant *CV = dyn_cast<Constant>(V))
Reid Spencer17212df2006-12-12 09:18:51 +0000257 return ConstantExpr::getCast(opc, CV, Ty);
Chris Lattnere2ed0572006-04-06 19:19:17 +0000258
Reid Spencer17212df2006-12-12 09:18:51 +0000259 Instruction *C = CastInst::create(opc, V, Ty, V->getName(), &Pos);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000260 AddToWorkList(C);
Chris Lattner0c967662004-09-24 15:21:34 +0000261 return C;
262 }
263
Chris Lattner8b170942002-08-09 23:47:40 +0000264 // ReplaceInstUsesWith - This method is to be used when an instruction is
265 // found to be dead, replacable with another preexisting expression. Here
266 // we add all uses of I to the worklist, replace all uses of I with the new
267 // value, then return I, so that the inst combiner will know that I was
268 // modified.
269 //
270 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000271 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner15a76c02004-04-05 02:10:19 +0000272 if (&I != V) {
273 I.replaceAllUsesWith(V);
274 return &I;
275 } else {
276 // If we are replacing the instruction with itself, this must be in a
277 // segment of unreachable code, so just clobber the instruction.
Chris Lattner17be6352004-10-18 02:59:09 +0000278 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +0000279 return &I;
280 }
Chris Lattner8b170942002-08-09 23:47:40 +0000281 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000282
Chris Lattner6dce1a72006-02-07 06:56:34 +0000283 // UpdateValueUsesWith - This method is to be used when an value is
284 // found to be replacable with another preexisting expression or was
285 // updated. Here we add all uses of I to the worklist, replace all uses of
286 // I with the new value (unless the instruction was just updated), then
287 // return true, so that the inst combiner will know that I was modified.
288 //
289 bool UpdateValueUsesWith(Value *Old, Value *New) {
290 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
291 if (Old != New)
292 Old->replaceAllUsesWith(New);
293 if (Instruction *I = dyn_cast<Instruction>(Old))
Chris Lattnerdbab3862007-03-02 21:28:56 +0000294 AddToWorkList(I);
Chris Lattnerf8c36f52006-02-12 08:02:11 +0000295 if (Instruction *I = dyn_cast<Instruction>(New))
Chris Lattnerdbab3862007-03-02 21:28:56 +0000296 AddToWorkList(I);
Chris Lattner6dce1a72006-02-07 06:56:34 +0000297 return true;
298 }
299
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000300 // EraseInstFromFunction - When dealing with an instruction that has side
301 // effects or produces a void value, we can't rely on DCE to delete the
302 // instruction. Instead, visit methods should return the value returned by
303 // this function.
304 Instruction *EraseInstFromFunction(Instruction &I) {
305 assert(I.use_empty() && "Cannot erase instruction that is used!");
306 AddUsesToWorkList(I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000307 RemoveFromWorkList(&I);
Chris Lattner954f66a2004-11-18 21:41:39 +0000308 I.eraseFromParent();
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000309 return 0; // Don't do anything with FI
310 }
311
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000312 private:
Chris Lattner24c8e382003-07-24 17:35:25 +0000313 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
314 /// InsertBefore instruction. This is specialized a bit to avoid inserting
315 /// casts that are known to not do anything...
316 ///
Reid Spencer17212df2006-12-12 09:18:51 +0000317 Value *InsertOperandCastBefore(Instruction::CastOps opcode,
318 Value *V, const Type *DestTy,
Chris Lattner24c8e382003-07-24 17:35:25 +0000319 Instruction *InsertBefore);
320
Reid Spencere4d87aa2006-12-23 06:05:41 +0000321 /// SimplifyCommutative - This performs a few simplifications for
322 /// commutative operators.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000323 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000324
Reid Spencere4d87aa2006-12-23 06:05:41 +0000325 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
326 /// most-complex to least-complex order.
327 bool SimplifyCompare(CmpInst &I);
328
Reid Spencer2ec619a2007-03-23 21:24:59 +0000329 /// SimplifyDemandedBits - Attempts to replace V with a simpler value based
330 /// on the demanded bits.
Reid Spencer8cb68342007-03-12 17:25:59 +0000331 bool SimplifyDemandedBits(Value *V, APInt DemandedMask,
332 APInt& KnownZero, APInt& KnownOne,
333 unsigned Depth = 0);
334
Chris Lattner867b99f2006-10-05 06:55:50 +0000335 Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
336 uint64_t &UndefElts, unsigned Depth = 0);
337
Chris Lattner4e998b22004-09-29 05:07:12 +0000338 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
339 // PHI node as operand #0, see if we can fold the instruction into the PHI
340 // (which is only possible if all operands to the PHI are constants).
341 Instruction *FoldOpIntoPhi(Instruction &I);
342
Chris Lattnerbac32862004-11-14 19:13:23 +0000343 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
344 // operator and they all are only used by the PHI, PHI together their
345 // inputs, and do the operation once, to the result of the PHI.
346 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
Chris Lattner7da52b22006-11-01 04:51:18 +0000347 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
348
349
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000350 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
351 ConstantInt *AndRHS, BinaryOperator &TheAnd);
Chris Lattnerc8e77562005-09-18 04:24:45 +0000352
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000353 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
Chris Lattnerc8e77562005-09-18 04:24:45 +0000354 bool isSub, Instruction &I);
Chris Lattnera96879a2004-09-29 17:40:11 +0000355 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000356 bool isSigned, bool Inside, Instruction &IB);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000357 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
Chris Lattnerafe91a52006-06-15 19:07:26 +0000358 Instruction *MatchBSwap(BinaryOperator &I);
Chris Lattner3284d1f2007-04-15 00:07:55 +0000359 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattnerafe91a52006-06-15 19:07:26 +0000360
Reid Spencerc55b2432006-12-13 18:21:21 +0000361 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000362 };
Chris Lattnerf6293092002-07-23 18:06:35 +0000363
Devang Patel19974732007-05-03 01:11:54 +0000364 char InstCombiner::ID = 0;
Chris Lattner7f8897f2006-08-27 22:42:52 +0000365 RegisterPass<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000366}
367
Chris Lattner4f98c562003-03-10 21:43:22 +0000368// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattnere87597f2004-10-16 18:11:37 +0000369// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattner4f98c562003-03-10 21:43:22 +0000370static unsigned getComplexity(Value *V) {
371 if (isa<Instruction>(V)) {
372 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattnere87597f2004-10-16 18:11:37 +0000373 return 3;
374 return 4;
Chris Lattner4f98c562003-03-10 21:43:22 +0000375 }
Chris Lattnere87597f2004-10-16 18:11:37 +0000376 if (isa<Argument>(V)) return 3;
377 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattner4f98c562003-03-10 21:43:22 +0000378}
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000379
Chris Lattnerc8802d22003-03-11 00:12:48 +0000380// isOnlyUse - Return true if this instruction will be deleted if we stop using
381// it.
382static bool isOnlyUse(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000383 return V->hasOneUse() || isa<Constant>(V);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000384}
385
Chris Lattner4cb170c2004-02-23 06:38:22 +0000386// getPromotedType - Return the specified type promoted as it would be to pass
387// though a va_arg area...
388static const Type *getPromotedType(const Type *Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000389 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
390 if (ITy->getBitWidth() < 32)
391 return Type::Int32Ty;
Chris Lattner2b7e0ad2007-05-23 01:17:04 +0000392 }
Reid Spencera54b7cb2007-01-12 07:05:14 +0000393 return Ty;
Chris Lattner4cb170c2004-02-23 06:38:22 +0000394}
395
Reid Spencer3da59db2006-11-27 01:05:10 +0000396/// getBitCastOperand - If the specified operand is a CastInst or a constant
397/// expression bitcast, return the operand value, otherwise return null.
398static Value *getBitCastOperand(Value *V) {
399 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
Chris Lattnereed48272005-09-13 00:40:14 +0000400 return I->getOperand(0);
401 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Reid Spencer3da59db2006-11-27 01:05:10 +0000402 if (CE->getOpcode() == Instruction::BitCast)
Chris Lattnereed48272005-09-13 00:40:14 +0000403 return CE->getOperand(0);
404 return 0;
405}
406
Reid Spencer3da59db2006-11-27 01:05:10 +0000407/// This function is a wrapper around CastInst::isEliminableCastPair. It
408/// simply extracts arguments and returns what that function returns.
Reid Spencer3da59db2006-11-27 01:05:10 +0000409static Instruction::CastOps
410isEliminableCastPair(
411 const CastInst *CI, ///< The first cast instruction
412 unsigned opcode, ///< The opcode of the second cast instruction
413 const Type *DstTy, ///< The target type for the second cast instruction
414 TargetData *TD ///< The target data for pointer size
415) {
416
417 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
418 const Type *MidTy = CI->getType(); // B from above
Chris Lattner33a61132006-05-06 09:00:16 +0000419
Reid Spencer3da59db2006-11-27 01:05:10 +0000420 // Get the opcodes of the two Cast instructions
421 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
422 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner33a61132006-05-06 09:00:16 +0000423
Reid Spencer3da59db2006-11-27 01:05:10 +0000424 return Instruction::CastOps(
425 CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
426 DstTy, TD->getIntPtrType()));
Chris Lattner33a61132006-05-06 09:00:16 +0000427}
428
429/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
430/// in any code being generated. It does not require codegen if V is simple
431/// enough or if the cast can be folded into other casts.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000432static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
433 const Type *Ty, TargetData *TD) {
Chris Lattner33a61132006-05-06 09:00:16 +0000434 if (V->getType() == Ty || isa<Constant>(V)) return false;
435
Chris Lattner01575b72006-05-25 23:24:33 +0000436 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner33a61132006-05-06 09:00:16 +0000437 if (const CastInst *CI = dyn_cast<CastInst>(V))
Reid Spencere4d87aa2006-12-23 06:05:41 +0000438 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner33a61132006-05-06 09:00:16 +0000439 return false;
440 return true;
441}
442
443/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
444/// InsertBefore instruction. This is specialized a bit to avoid inserting
445/// casts that are known to not do anything...
446///
Reid Spencer17212df2006-12-12 09:18:51 +0000447Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
448 Value *V, const Type *DestTy,
Chris Lattner33a61132006-05-06 09:00:16 +0000449 Instruction *InsertBefore) {
450 if (V->getType() == DestTy) return V;
451 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencer17212df2006-12-12 09:18:51 +0000452 return ConstantExpr::getCast(opcode, C, DestTy);
Chris Lattner33a61132006-05-06 09:00:16 +0000453
Reid Spencer17212df2006-12-12 09:18:51 +0000454 return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
Chris Lattner33a61132006-05-06 09:00:16 +0000455}
456
Chris Lattner4f98c562003-03-10 21:43:22 +0000457// SimplifyCommutative - This performs a few simplifications for commutative
458// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000459//
Chris Lattner4f98c562003-03-10 21:43:22 +0000460// 1. Order operands such that they are listed from right (least complex) to
461// left (most complex). This puts constants before unary operators before
462// binary operators.
463//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000464// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
465// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000466//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000467bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000468 bool Changed = false;
469 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
470 Changed = !I.swapOperands();
Misha Brukmanfd939082005-04-21 23:48:37 +0000471
Chris Lattner4f98c562003-03-10 21:43:22 +0000472 if (!I.isAssociative()) return Changed;
473 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000474 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
475 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
476 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner2a9c8472003-05-27 16:40:51 +0000477 Constant *Folded = ConstantExpr::get(I.getOpcode(),
478 cast<Constant>(I.getOperand(1)),
479 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000480 I.setOperand(0, Op->getOperand(0));
481 I.setOperand(1, Folded);
482 return true;
483 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
484 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
485 isOnlyUse(Op) && isOnlyUse(Op1)) {
486 Constant *C1 = cast<Constant>(Op->getOperand(1));
487 Constant *C2 = cast<Constant>(Op1->getOperand(1));
488
489 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner2a9c8472003-05-27 16:40:51 +0000490 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000491 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
492 Op1->getOperand(0),
493 Op1->getName(), &I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000494 AddToWorkList(New);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000495 I.setOperand(0, New);
496 I.setOperand(1, Folded);
497 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000498 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000499 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000500 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000501}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000502
Reid Spencere4d87aa2006-12-23 06:05:41 +0000503/// SimplifyCompare - For a CmpInst this function just orders the operands
504/// so that theyare listed from right (least complex) to left (most complex).
505/// This puts constants before unary operators before binary operators.
506bool InstCombiner::SimplifyCompare(CmpInst &I) {
507 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
508 return false;
509 I.swapOperands();
510 // Compare instructions are not associative so there's nothing else we can do.
511 return true;
512}
513
Chris Lattner8d969642003-03-10 23:06:50 +0000514// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
515// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000516//
Chris Lattner8d969642003-03-10 23:06:50 +0000517static inline Value *dyn_castNegVal(Value *V) {
518 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000519 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000520
Chris Lattner0ce85802004-12-14 20:08:06 +0000521 // Constants can be considered to be negated values if they can be folded.
522 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
523 return ConstantExpr::getNeg(C);
Chris Lattner8d969642003-03-10 23:06:50 +0000524 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000525}
526
Chris Lattner8d969642003-03-10 23:06:50 +0000527static inline Value *dyn_castNotVal(Value *V) {
528 if (BinaryOperator::isNot(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000529 return BinaryOperator::getNotArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000530
531 // Constants can be considered to be not'ed values...
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000532 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Zhou Sheng4a1822a2007-04-02 13:45:30 +0000533 return ConstantInt::get(~C->getValue());
Chris Lattner8d969642003-03-10 23:06:50 +0000534 return 0;
535}
536
Chris Lattnerc8802d22003-03-11 00:12:48 +0000537// dyn_castFoldableMul - If this value is a multiply that can be folded into
538// other computations (because it has a constant operand), return the
Chris Lattner50af16a2004-11-13 19:50:12 +0000539// non-constant operand of the multiply, and set CST to point to the multiplier.
540// Otherwise, return null.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000541//
Chris Lattner50af16a2004-11-13 19:50:12 +0000542static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattner42a75512007-01-15 02:27:26 +0000543 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner50af16a2004-11-13 19:50:12 +0000544 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000545 if (I->getOpcode() == Instruction::Mul)
Chris Lattner50e60c72004-11-15 05:54:07 +0000546 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000547 return I->getOperand(0);
Chris Lattner50af16a2004-11-13 19:50:12 +0000548 if (I->getOpcode() == Instruction::Shl)
Chris Lattner50e60c72004-11-15 05:54:07 +0000549 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000550 // The multiplier is really 1 << CST.
Zhou Sheng97b52c22007-03-29 01:57:21 +0000551 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000552 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Zhou Sheng97b52c22007-03-29 01:57:21 +0000553 CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
Chris Lattner50af16a2004-11-13 19:50:12 +0000554 return I->getOperand(0);
555 }
556 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000557 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000558}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000559
Chris Lattner574da9b2005-01-13 20:14:25 +0000560/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
561/// expression, return it.
562static User *dyn_castGetElementPtr(Value *V) {
563 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
564 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
565 if (CE->getOpcode() == Instruction::GetElementPtr)
566 return cast<User>(V);
567 return false;
568}
569
Reid Spencer7177c3a2007-03-25 05:33:51 +0000570/// AddOne - Add one to a ConstantInt
Chris Lattnera96879a2004-09-29 17:40:11 +0000571static ConstantInt *AddOne(ConstantInt *C) {
Reid Spencer2149a9d2007-03-25 19:55:33 +0000572 APInt Val(C->getValue());
573 return ConstantInt::get(++Val);
Chris Lattner955f3312004-09-28 21:48:02 +0000574}
Reid Spencer7177c3a2007-03-25 05:33:51 +0000575/// SubOne - Subtract one from a ConstantInt
Chris Lattnera96879a2004-09-29 17:40:11 +0000576static ConstantInt *SubOne(ConstantInt *C) {
Reid Spencer2149a9d2007-03-25 19:55:33 +0000577 APInt Val(C->getValue());
578 return ConstantInt::get(--Val);
Reid Spencer7177c3a2007-03-25 05:33:51 +0000579}
580/// Add - Add two ConstantInts together
581static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
582 return ConstantInt::get(C1->getValue() + C2->getValue());
583}
584/// And - Bitwise AND two ConstantInts together
585static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
586 return ConstantInt::get(C1->getValue() & C2->getValue());
587}
588/// Subtract - Subtract one ConstantInt from another
589static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
590 return ConstantInt::get(C1->getValue() - C2->getValue());
591}
592/// Multiply - Multiply two ConstantInts together
593static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
594 return ConstantInt::get(C1->getValue() * C2->getValue());
Chris Lattner955f3312004-09-28 21:48:02 +0000595}
596
Chris Lattner68d5ff22006-02-09 07:38:58 +0000597/// ComputeMaskedBits - Determine which of the bits specified in Mask are
598/// known to be either zero or one and return them in the KnownZero/KnownOne
Reid Spencer3e7594f2007-03-08 01:46:38 +0000599/// bit sets. This code only analyzes bits in Mask, in order to short-circuit
600/// processing.
601/// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
602/// we cannot optimize based on the assumption that it is zero without changing
603/// it to be an explicit zero. If we don't change it to zero, other code could
604/// optimized based on the contradictory assumption that it is non-zero.
605/// Because instcombine aggressively folds operations with undef args anyway,
606/// this won't lose us code quality.
Reid Spencer55702aa2007-03-25 21:11:44 +0000607static void ComputeMaskedBits(Value *V, const APInt &Mask, APInt& KnownZero,
Reid Spencer3e7594f2007-03-08 01:46:38 +0000608 APInt& KnownOne, unsigned Depth = 0) {
Zhou Sheng771dbf72007-03-13 02:23:10 +0000609 assert(V && "No Value?");
610 assert(Depth <= 6 && "Limit Search Depth");
Reid Spencer3e7594f2007-03-08 01:46:38 +0000611 uint32_t BitWidth = Mask.getBitWidth();
Zhou Shengaa305ab2007-03-28 02:19:03 +0000612 assert(cast<IntegerType>(V->getType())->getBitWidth() == BitWidth &&
Zhou Sheng771dbf72007-03-13 02:23:10 +0000613 KnownZero.getBitWidth() == BitWidth &&
Reid Spencer3e7594f2007-03-08 01:46:38 +0000614 KnownOne.getBitWidth() == BitWidth &&
Zhou Shengaa305ab2007-03-28 02:19:03 +0000615 "V, Mask, KnownOne and KnownZero should have same BitWidth");
Reid Spencer3e7594f2007-03-08 01:46:38 +0000616 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
617 // We know all of the bits for a constant!
Zhou Sheng771dbf72007-03-13 02:23:10 +0000618 KnownOne = CI->getValue() & Mask;
Reid Spencer3e7594f2007-03-08 01:46:38 +0000619 KnownZero = ~KnownOne & Mask;
620 return;
621 }
622
Reid Spencer3e7594f2007-03-08 01:46:38 +0000623 if (Depth == 6 || Mask == 0)
624 return; // Limit search depth.
625
626 Instruction *I = dyn_cast<Instruction>(V);
627 if (!I) return;
628
Zhou Sheng771dbf72007-03-13 02:23:10 +0000629 KnownZero.clear(); KnownOne.clear(); // Don't know anything.
Reid Spencer3e7594f2007-03-08 01:46:38 +0000630 APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000631
632 switch (I->getOpcode()) {
Reid Spencer2b812072007-03-25 02:03:12 +0000633 case Instruction::And: {
Reid Spencer3e7594f2007-03-08 01:46:38 +0000634 // If either the LHS or the RHS are Zero, the result is zero.
635 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
Reid Spencer2b812072007-03-25 02:03:12 +0000636 APInt Mask2(Mask & ~KnownZero);
637 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000638 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
639 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
640
641 // Output known-1 bits are only known if set in both the LHS & RHS.
642 KnownOne &= KnownOne2;
643 // Output known-0 are known to be clear if zero in either the LHS | RHS.
644 KnownZero |= KnownZero2;
645 return;
Reid Spencer2b812072007-03-25 02:03:12 +0000646 }
647 case Instruction::Or: {
Reid Spencer3e7594f2007-03-08 01:46:38 +0000648 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
Reid Spencer2b812072007-03-25 02:03:12 +0000649 APInt Mask2(Mask & ~KnownOne);
650 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000651 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
652 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
653
654 // Output known-0 bits are only known if clear in both the LHS & RHS.
655 KnownZero &= KnownZero2;
656 // Output known-1 are known to be set if set in either the LHS | RHS.
657 KnownOne |= KnownOne2;
658 return;
Reid Spencer2b812072007-03-25 02:03:12 +0000659 }
Reid Spencer3e7594f2007-03-08 01:46:38 +0000660 case Instruction::Xor: {
661 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
662 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
663 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
664 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
665
666 // Output known-0 bits are known if clear or set in both the LHS & RHS.
667 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
668 // Output known-1 are known to be set if set in only one of the LHS, RHS.
669 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
670 KnownZero = KnownZeroOut;
671 return;
672 }
673 case Instruction::Select:
674 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
675 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
676 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
677 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
678
679 // Only known if known in both the LHS and RHS.
680 KnownOne &= KnownOne2;
681 KnownZero &= KnownZero2;
682 return;
683 case Instruction::FPTrunc:
684 case Instruction::FPExt:
685 case Instruction::FPToUI:
686 case Instruction::FPToSI:
687 case Instruction::SIToFP:
688 case Instruction::PtrToInt:
689 case Instruction::UIToFP:
690 case Instruction::IntToPtr:
691 return; // Can't work with floating point or pointers
Zhou Sheng771dbf72007-03-13 02:23:10 +0000692 case Instruction::Trunc: {
Reid Spencer3e7594f2007-03-08 01:46:38 +0000693 // All these have integer operands
Zhou Sheng771dbf72007-03-13 02:23:10 +0000694 uint32_t SrcBitWidth =
695 cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
Zhou Shengaa305ab2007-03-28 02:19:03 +0000696 APInt MaskIn(Mask);
697 MaskIn.zext(SrcBitWidth);
698 KnownZero.zext(SrcBitWidth);
699 KnownOne.zext(SrcBitWidth);
700 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
Zhou Sheng771dbf72007-03-13 02:23:10 +0000701 KnownZero.trunc(BitWidth);
702 KnownOne.trunc(BitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000703 return;
Zhou Sheng771dbf72007-03-13 02:23:10 +0000704 }
Reid Spencer3e7594f2007-03-08 01:46:38 +0000705 case Instruction::BitCast: {
706 const Type *SrcTy = I->getOperand(0)->getType();
707 if (SrcTy->isInteger()) {
708 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
709 return;
710 }
711 break;
712 }
713 case Instruction::ZExt: {
714 // Compute the bits in the result that are not present in the input.
715 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Zhou Sheng771dbf72007-03-13 02:23:10 +0000716 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer2f549172007-03-25 04:26:16 +0000717
Zhou Shengaa305ab2007-03-28 02:19:03 +0000718 APInt MaskIn(Mask);
719 MaskIn.trunc(SrcBitWidth);
720 KnownZero.trunc(SrcBitWidth);
721 KnownOne.trunc(SrcBitWidth);
722 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000723 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
724 // The top bits are known to be zero.
Zhou Sheng771dbf72007-03-13 02:23:10 +0000725 KnownZero.zext(BitWidth);
726 KnownOne.zext(BitWidth);
Zhou Shengaa305ab2007-03-28 02:19:03 +0000727 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000728 return;
729 }
730 case Instruction::SExt: {
731 // Compute the bits in the result that are not present in the input.
732 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Zhou Sheng771dbf72007-03-13 02:23:10 +0000733 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer2f549172007-03-25 04:26:16 +0000734
Zhou Shengaa305ab2007-03-28 02:19:03 +0000735 APInt MaskIn(Mask);
736 MaskIn.trunc(SrcBitWidth);
737 KnownZero.trunc(SrcBitWidth);
738 KnownOne.trunc(SrcBitWidth);
739 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000740 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Zhou Sheng771dbf72007-03-13 02:23:10 +0000741 KnownZero.zext(BitWidth);
742 KnownOne.zext(BitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000743
744 // If the sign bit of the input is known set or clear, then we know the
745 // top bits of the result.
Zhou Shengaa305ab2007-03-28 02:19:03 +0000746 if (KnownZero[SrcBitWidth-1]) // Input sign bit known zero
Zhou Sheng34a4b382007-03-28 17:38:21 +0000747 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Zhou Shengaa305ab2007-03-28 02:19:03 +0000748 else if (KnownOne[SrcBitWidth-1]) // Input sign bit known set
Zhou Sheng34a4b382007-03-28 17:38:21 +0000749 KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000750 return;
751 }
752 case Instruction::Shl:
753 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
754 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000755 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer2b812072007-03-25 02:03:12 +0000756 APInt Mask2(Mask.lshr(ShiftAmt));
757 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000758 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Zhou Sheng430f6262007-03-12 05:44:52 +0000759 KnownZero <<= ShiftAmt;
760 KnownOne <<= ShiftAmt;
Reid Spencer2149a9d2007-03-25 19:55:33 +0000761 KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt); // low bits known 0
Reid Spencer3e7594f2007-03-08 01:46:38 +0000762 return;
763 }
764 break;
765 case Instruction::LShr:
766 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
767 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
768 // Compute the new bits that are at the top now.
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000769 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000770
771 // Unsigned shift right.
Reid Spencer2b812072007-03-25 02:03:12 +0000772 APInt Mask2(Mask.shl(ShiftAmt));
773 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000774 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
775 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
776 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
Zhou Shengaa305ab2007-03-28 02:19:03 +0000777 // high bits known zero.
778 KnownZero |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000779 return;
780 }
781 break;
782 case Instruction::AShr:
Zhou Shengaa305ab2007-03-28 02:19:03 +0000783 // (ashr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
Reid Spencer3e7594f2007-03-08 01:46:38 +0000784 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
785 // Compute the new bits that are at the top now.
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000786 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000787
788 // Signed shift right.
Reid Spencer2b812072007-03-25 02:03:12 +0000789 APInt Mask2(Mask.shl(ShiftAmt));
790 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000791 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
792 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
793 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
794
Zhou Shengaa305ab2007-03-28 02:19:03 +0000795 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
796 if (KnownZero[BitWidth-ShiftAmt-1]) // New bits are known zero.
Reid Spencer3e7594f2007-03-08 01:46:38 +0000797 KnownZero |= HighBits;
Zhou Shengaa305ab2007-03-28 02:19:03 +0000798 else if (KnownOne[BitWidth-ShiftAmt-1]) // New bits are known one.
Reid Spencer3e7594f2007-03-08 01:46:38 +0000799 KnownOne |= HighBits;
Reid Spencer3e7594f2007-03-08 01:46:38 +0000800 return;
801 }
802 break;
803 }
804}
805
Reid Spencere7816b52007-03-08 01:52:58 +0000806/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
807/// this predicate to simplify operations downstream. Mask is known to be zero
808/// for bits that V cannot have.
809static bool MaskedValueIsZero(Value *V, const APInt& Mask, unsigned Depth = 0) {
Zhou Shengedd089c2007-03-12 16:54:56 +0000810 APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
Reid Spencere7816b52007-03-08 01:52:58 +0000811 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
812 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
813 return (KnownZero & Mask) == Mask;
814}
815
Chris Lattner255d8912006-02-11 09:31:47 +0000816/// ShrinkDemandedConstant - Check to see if the specified operand of the
817/// specified instruction is a constant integer. If so, check to see if there
818/// are any bits set in the constant that are not demanded. If so, shrink the
819/// constant and return true.
820static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000821 APInt Demanded) {
822 assert(I && "No instruction?");
823 assert(OpNo < I->getNumOperands() && "Operand index too large");
824
825 // If the operand is not a constant integer, nothing to do.
826 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
827 if (!OpC) return false;
828
829 // If there are no bits set that aren't demanded, nothing to do.
830 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
831 if ((~Demanded & OpC->getValue()) == 0)
832 return false;
833
834 // This instruction is producing bits that are not demanded. Shrink the RHS.
835 Demanded &= OpC->getValue();
836 I->setOperand(OpNo, ConstantInt::get(Demanded));
837 return true;
838}
839
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000840// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
841// set of known zero and one bits, compute the maximum and minimum values that
842// could have the specified known zero and known one bits, returning them in
843// min/max.
844static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
Reid Spencer0460fb32007-03-22 20:36:03 +0000845 const APInt& KnownZero,
846 const APInt& KnownOne,
847 APInt& Min, APInt& Max) {
848 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
849 assert(KnownZero.getBitWidth() == BitWidth &&
850 KnownOne.getBitWidth() == BitWidth &&
851 Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
852 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000853 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000854
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000855 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
856 // bit if it is unknown.
857 Min = KnownOne;
858 Max = KnownOne|UnknownBits;
859
Zhou Sheng4acf1552007-03-28 05:15:57 +0000860 if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
Zhou Sheng4a1822a2007-04-02 13:45:30 +0000861 Min.set(BitWidth-1);
862 Max.clear(BitWidth-1);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000863 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000864}
865
866// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
867// a set of known zero and one bits, compute the maximum and minimum values that
868// could have the specified known zero and known one bits, returning them in
869// min/max.
870static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
Reid Spencer0460fb32007-03-22 20:36:03 +0000871 const APInt& KnownZero,
872 const APInt& KnownOne,
873 APInt& Min,
874 APInt& Max) {
875 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
876 assert(KnownZero.getBitWidth() == BitWidth &&
877 KnownOne.getBitWidth() == BitWidth &&
878 Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
879 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000880 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000881
882 // The minimum value is when the unknown bits are all zeros.
883 Min = KnownOne;
884 // The maximum value is when the unknown bits are all ones.
885 Max = KnownOne|UnknownBits;
886}
Chris Lattner255d8912006-02-11 09:31:47 +0000887
Reid Spencer8cb68342007-03-12 17:25:59 +0000888/// SimplifyDemandedBits - This function attempts to replace V with a simpler
889/// value based on the demanded bits. When this function is called, it is known
890/// that only the bits set in DemandedMask of the result of V are ever used
891/// downstream. Consequently, depending on the mask and V, it may be possible
892/// to replace V with a constant or one of its operands. In such cases, this
893/// function does the replacement and returns true. In all other cases, it
894/// returns false after analyzing the expression and setting KnownOne and known
895/// to be one in the expression. KnownZero contains all the bits that are known
896/// to be zero in the expression. These are provided to potentially allow the
897/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
898/// the expression. KnownOne and KnownZero always follow the invariant that
899/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
900/// the bits in KnownOne and KnownZero may only be accurate for those bits set
901/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
902/// and KnownOne must all be the same.
903bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
904 APInt& KnownZero, APInt& KnownOne,
905 unsigned Depth) {
906 assert(V != 0 && "Null pointer of Value???");
907 assert(Depth <= 6 && "Limit Search Depth");
908 uint32_t BitWidth = DemandedMask.getBitWidth();
909 const IntegerType *VTy = cast<IntegerType>(V->getType());
910 assert(VTy->getBitWidth() == BitWidth &&
911 KnownZero.getBitWidth() == BitWidth &&
912 KnownOne.getBitWidth() == BitWidth &&
913 "Value *V, DemandedMask, KnownZero and KnownOne \
914 must have same BitWidth");
915 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
916 // We know all of the bits for a constant!
917 KnownOne = CI->getValue() & DemandedMask;
918 KnownZero = ~KnownOne & DemandedMask;
919 return false;
920 }
921
Zhou Sheng96704452007-03-14 03:21:24 +0000922 KnownZero.clear();
923 KnownOne.clear();
Reid Spencer8cb68342007-03-12 17:25:59 +0000924 if (!V->hasOneUse()) { // Other users may use these bits.
925 if (Depth != 0) { // Not at the root.
926 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
927 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
928 return false;
929 }
930 // If this is the root being simplified, allow it to have multiple uses,
931 // just set the DemandedMask to all bits.
932 DemandedMask = APInt::getAllOnesValue(BitWidth);
933 } else if (DemandedMask == 0) { // Not demanding any bits from V.
934 if (V != UndefValue::get(VTy))
935 return UpdateValueUsesWith(V, UndefValue::get(VTy));
936 return false;
937 } else if (Depth == 6) { // Limit search depth.
938 return false;
939 }
940
941 Instruction *I = dyn_cast<Instruction>(V);
942 if (!I) return false; // Only analyze instructions.
943
Reid Spencer8cb68342007-03-12 17:25:59 +0000944 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
945 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
946 switch (I->getOpcode()) {
947 default: break;
948 case Instruction::And:
949 // If either the LHS or the RHS are Zero, the result is zero.
950 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
951 RHSKnownZero, RHSKnownOne, Depth+1))
952 return true;
953 assert((RHSKnownZero & RHSKnownOne) == 0 &&
954 "Bits known to be one AND zero?");
955
956 // If something is known zero on the RHS, the bits aren't demanded on the
957 // LHS.
958 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
959 LHSKnownZero, LHSKnownOne, Depth+1))
960 return true;
961 assert((LHSKnownZero & LHSKnownOne) == 0 &&
962 "Bits known to be one AND zero?");
963
964 // If all of the demanded bits are known 1 on one side, return the other.
965 // These bits cannot contribute to the result of the 'and'.
966 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
967 (DemandedMask & ~LHSKnownZero))
968 return UpdateValueUsesWith(I, I->getOperand(0));
969 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
970 (DemandedMask & ~RHSKnownZero))
971 return UpdateValueUsesWith(I, I->getOperand(1));
972
973 // If all of the demanded bits in the inputs are known zeros, return zero.
974 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
975 return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
976
977 // If the RHS is a constant, see if we can simplify it.
978 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
979 return UpdateValueUsesWith(I, I);
980
981 // Output known-1 bits are only known if set in both the LHS & RHS.
982 RHSKnownOne &= LHSKnownOne;
983 // Output known-0 are known to be clear if zero in either the LHS | RHS.
984 RHSKnownZero |= LHSKnownZero;
985 break;
986 case Instruction::Or:
987 // If either the LHS or the RHS are One, the result is One.
988 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
989 RHSKnownZero, RHSKnownOne, Depth+1))
990 return true;
991 assert((RHSKnownZero & RHSKnownOne) == 0 &&
992 "Bits known to be one AND zero?");
993 // If something is known one on the RHS, the bits aren't demanded on the
994 // LHS.
995 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
996 LHSKnownZero, LHSKnownOne, Depth+1))
997 return true;
998 assert((LHSKnownZero & LHSKnownOne) == 0 &&
999 "Bits known to be one AND zero?");
1000
1001 // If all of the demanded bits are known zero on one side, return the other.
1002 // These bits cannot contribute to the result of the 'or'.
1003 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
1004 (DemandedMask & ~LHSKnownOne))
1005 return UpdateValueUsesWith(I, I->getOperand(0));
1006 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
1007 (DemandedMask & ~RHSKnownOne))
1008 return UpdateValueUsesWith(I, I->getOperand(1));
1009
1010 // If all of the potentially set bits on one side are known to be set on
1011 // the other side, just use the 'other' side.
1012 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
1013 (DemandedMask & (~RHSKnownZero)))
1014 return UpdateValueUsesWith(I, I->getOperand(0));
1015 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
1016 (DemandedMask & (~LHSKnownZero)))
1017 return UpdateValueUsesWith(I, I->getOperand(1));
1018
1019 // If the RHS is a constant, see if we can simplify it.
1020 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1021 return UpdateValueUsesWith(I, I);
1022
1023 // Output known-0 bits are only known if clear in both the LHS & RHS.
1024 RHSKnownZero &= LHSKnownZero;
1025 // Output known-1 are known to be set if set in either the LHS | RHS.
1026 RHSKnownOne |= LHSKnownOne;
1027 break;
1028 case Instruction::Xor: {
1029 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1030 RHSKnownZero, RHSKnownOne, Depth+1))
1031 return true;
1032 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1033 "Bits known to be one AND zero?");
1034 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1035 LHSKnownZero, LHSKnownOne, Depth+1))
1036 return true;
1037 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1038 "Bits known to be one AND zero?");
1039
1040 // If all of the demanded bits are known zero on one side, return the other.
1041 // These bits cannot contribute to the result of the 'xor'.
1042 if ((DemandedMask & RHSKnownZero) == DemandedMask)
1043 return UpdateValueUsesWith(I, I->getOperand(0));
1044 if ((DemandedMask & LHSKnownZero) == DemandedMask)
1045 return UpdateValueUsesWith(I, I->getOperand(1));
1046
1047 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1048 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1049 (RHSKnownOne & LHSKnownOne);
1050 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1051 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1052 (RHSKnownOne & LHSKnownZero);
1053
1054 // If all of the demanded bits are known to be zero on one side or the
1055 // other, turn this into an *inclusive* or.
1056 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1057 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1058 Instruction *Or =
1059 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1060 I->getName());
1061 InsertNewInstBefore(Or, *I);
1062 return UpdateValueUsesWith(I, Or);
1063 }
1064
1065 // If all of the demanded bits on one side are known, and all of the set
1066 // bits on that side are also known to be set on the other side, turn this
1067 // into an AND, as we know the bits will be cleared.
1068 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1069 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1070 // all known
1071 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1072 Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
1073 Instruction *And =
1074 BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
1075 InsertNewInstBefore(And, *I);
1076 return UpdateValueUsesWith(I, And);
1077 }
1078 }
1079
1080 // If the RHS is a constant, see if we can simplify it.
1081 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1082 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1083 return UpdateValueUsesWith(I, I);
1084
1085 RHSKnownZero = KnownZeroOut;
1086 RHSKnownOne = KnownOneOut;
1087 break;
1088 }
1089 case Instruction::Select:
1090 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
1091 RHSKnownZero, RHSKnownOne, Depth+1))
1092 return true;
1093 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1094 LHSKnownZero, LHSKnownOne, Depth+1))
1095 return true;
1096 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1097 "Bits known to be one AND zero?");
1098 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1099 "Bits known to be one AND zero?");
1100
1101 // If the operands are constants, see if we can simplify them.
1102 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1103 return UpdateValueUsesWith(I, I);
1104 if (ShrinkDemandedConstant(I, 2, DemandedMask))
1105 return UpdateValueUsesWith(I, I);
1106
1107 // Only known if known in both the LHS and RHS.
1108 RHSKnownOne &= LHSKnownOne;
1109 RHSKnownZero &= LHSKnownZero;
1110 break;
1111 case Instruction::Trunc: {
1112 uint32_t truncBf =
1113 cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
Zhou Sheng01542f32007-03-29 02:26:30 +00001114 DemandedMask.zext(truncBf);
1115 RHSKnownZero.zext(truncBf);
1116 RHSKnownOne.zext(truncBf);
1117 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1118 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer8cb68342007-03-12 17:25:59 +00001119 return true;
1120 DemandedMask.trunc(BitWidth);
1121 RHSKnownZero.trunc(BitWidth);
1122 RHSKnownOne.trunc(BitWidth);
1123 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1124 "Bits known to be one AND zero?");
1125 break;
1126 }
1127 case Instruction::BitCast:
1128 if (!I->getOperand(0)->getType()->isInteger())
1129 return false;
1130
1131 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1132 RHSKnownZero, RHSKnownOne, Depth+1))
1133 return true;
1134 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1135 "Bits known to be one AND zero?");
1136 break;
1137 case Instruction::ZExt: {
1138 // Compute the bits in the result that are not present in the input.
1139 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Reid Spencer2f549172007-03-25 04:26:16 +00001140 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer8cb68342007-03-12 17:25:59 +00001141
Zhou Shengd48653a2007-03-29 04:45:55 +00001142 DemandedMask.trunc(SrcBitWidth);
1143 RHSKnownZero.trunc(SrcBitWidth);
1144 RHSKnownOne.trunc(SrcBitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001145 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1146 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer8cb68342007-03-12 17:25:59 +00001147 return true;
1148 DemandedMask.zext(BitWidth);
1149 RHSKnownZero.zext(BitWidth);
1150 RHSKnownOne.zext(BitWidth);
1151 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1152 "Bits known to be one AND zero?");
1153 // The top bits are known to be zero.
Zhou Sheng01542f32007-03-29 02:26:30 +00001154 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001155 break;
1156 }
1157 case Instruction::SExt: {
1158 // Compute the bits in the result that are not present in the input.
1159 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Reid Spencer2f549172007-03-25 04:26:16 +00001160 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer8cb68342007-03-12 17:25:59 +00001161
Reid Spencer8cb68342007-03-12 17:25:59 +00001162 APInt InputDemandedBits = DemandedMask &
Zhou Sheng01542f32007-03-29 02:26:30 +00001163 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001164
Zhou Sheng01542f32007-03-29 02:26:30 +00001165 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
Reid Spencer8cb68342007-03-12 17:25:59 +00001166 // If any of the sign extended bits are demanded, we know that the sign
1167 // bit is demanded.
1168 if ((NewBits & DemandedMask) != 0)
Zhou Sheng4a1822a2007-04-02 13:45:30 +00001169 InputDemandedBits.set(SrcBitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001170
Zhou Shengd48653a2007-03-29 04:45:55 +00001171 InputDemandedBits.trunc(SrcBitWidth);
1172 RHSKnownZero.trunc(SrcBitWidth);
1173 RHSKnownOne.trunc(SrcBitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001174 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1175 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer8cb68342007-03-12 17:25:59 +00001176 return true;
1177 InputDemandedBits.zext(BitWidth);
1178 RHSKnownZero.zext(BitWidth);
1179 RHSKnownOne.zext(BitWidth);
1180 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1181 "Bits known to be one AND zero?");
1182
1183 // If the sign bit of the input is known set or clear, then we know the
1184 // top bits of the result.
1185
1186 // If the input sign bit is known zero, or if the NewBits are not demanded
1187 // convert this into a zero extension.
Zhou Sheng01542f32007-03-29 02:26:30 +00001188 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits)
Reid Spencer8cb68342007-03-12 17:25:59 +00001189 {
1190 // Convert to ZExt cast
1191 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1192 return UpdateValueUsesWith(I, NewCast);
Zhou Sheng01542f32007-03-29 02:26:30 +00001193 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
Reid Spencer8cb68342007-03-12 17:25:59 +00001194 RHSKnownOne |= NewBits;
Reid Spencer8cb68342007-03-12 17:25:59 +00001195 }
1196 break;
1197 }
1198 case Instruction::Add: {
1199 // Figure out what the input bits are. If the top bits of the and result
1200 // are not demanded, then the add doesn't demand them from its input
1201 // either.
Reid Spencer55702aa2007-03-25 21:11:44 +00001202 uint32_t NLZ = DemandedMask.countLeadingZeros();
Reid Spencer8cb68342007-03-12 17:25:59 +00001203
1204 // If there is a constant on the RHS, there are a variety of xformations
1205 // we can do.
1206 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1207 // If null, this should be simplified elsewhere. Some of the xforms here
1208 // won't work if the RHS is zero.
1209 if (RHS->isZero())
1210 break;
1211
1212 // If the top bit of the output is demanded, demand everything from the
1213 // input. Otherwise, we demand all the input bits except NLZ top bits.
Zhou Sheng01542f32007-03-29 02:26:30 +00001214 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001215
1216 // Find information about known zero/one bits in the input.
1217 if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits,
1218 LHSKnownZero, LHSKnownOne, Depth+1))
1219 return true;
1220
1221 // If the RHS of the add has bits set that can't affect the input, reduce
1222 // the constant.
1223 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1224 return UpdateValueUsesWith(I, I);
1225
1226 // Avoid excess work.
1227 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1228 break;
1229
1230 // Turn it into OR if input bits are zero.
1231 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1232 Instruction *Or =
1233 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1234 I->getName());
1235 InsertNewInstBefore(Or, *I);
1236 return UpdateValueUsesWith(I, Or);
1237 }
1238
1239 // We can say something about the output known-zero and known-one bits,
1240 // depending on potential carries from the input constant and the
1241 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1242 // bits set and the RHS constant is 0x01001, then we know we have a known
1243 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1244
1245 // To compute this, we first compute the potential carry bits. These are
1246 // the bits which may be modified. I'm not aware of a better way to do
1247 // this scan.
Zhou Shengb9cb95f2007-03-31 02:38:39 +00001248 const APInt& RHSVal = RHS->getValue();
1249 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
Reid Spencer8cb68342007-03-12 17:25:59 +00001250
1251 // Now that we know which bits have carries, compute the known-1/0 sets.
1252
1253 // Bits are known one if they are known zero in one operand and one in the
1254 // other, and there is no input carry.
1255 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1256 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1257
1258 // Bits are known zero if they are known zero in both operands and there
1259 // is no input carry.
1260 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1261 } else {
1262 // If the high-bits of this ADD are not demanded, then it does not demand
1263 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001264 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001265 // Right fill the mask of bits for this ADD to demand the most
1266 // significant bit and all those below it.
Zhou Sheng01542f32007-03-29 02:26:30 +00001267 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001268 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1269 LHSKnownZero, LHSKnownOne, Depth+1))
1270 return true;
1271 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1272 LHSKnownZero, LHSKnownOne, Depth+1))
1273 return true;
1274 }
1275 }
1276 break;
1277 }
1278 case Instruction::Sub:
1279 // If the high-bits of this SUB are not demanded, then it does not demand
1280 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001281 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001282 // Right fill the mask of bits for this SUB to demand the most
1283 // significant bit and all those below it.
Zhou Sheng4351c642007-04-02 08:20:41 +00001284 uint32_t NLZ = DemandedMask.countLeadingZeros();
Zhou Sheng01542f32007-03-29 02:26:30 +00001285 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001286 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1287 LHSKnownZero, LHSKnownOne, Depth+1))
1288 return true;
1289 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1290 LHSKnownZero, LHSKnownOne, Depth+1))
1291 return true;
1292 }
1293 break;
1294 case Instruction::Shl:
1295 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001296 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001297 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1298 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001299 RHSKnownZero, RHSKnownOne, Depth+1))
1300 return true;
1301 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1302 "Bits known to be one AND zero?");
1303 RHSKnownZero <<= ShiftAmt;
1304 RHSKnownOne <<= ShiftAmt;
1305 // low bits known zero.
Zhou Shengadc14952007-03-14 09:07:33 +00001306 if (ShiftAmt)
Zhou Shenge9e03f62007-03-28 15:02:20 +00001307 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
Reid Spencer8cb68342007-03-12 17:25:59 +00001308 }
1309 break;
1310 case Instruction::LShr:
1311 // For a logical shift right
1312 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001313 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001314
Reid Spencer8cb68342007-03-12 17:25:59 +00001315 // Unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001316 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1317 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001318 RHSKnownZero, RHSKnownOne, Depth+1))
1319 return true;
1320 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1321 "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001322 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1323 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
Zhou Shengadc14952007-03-14 09:07:33 +00001324 if (ShiftAmt) {
1325 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001326 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Zhou Shengadc14952007-03-14 09:07:33 +00001327 RHSKnownZero |= HighBits; // high bits known zero.
1328 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001329 }
1330 break;
1331 case Instruction::AShr:
1332 // If this is an arithmetic shift right and only the low-bit is set, we can
1333 // always convert this into a logical shr, even if the shift amount is
1334 // variable. The low bit of the shift cannot be an input sign bit unless
1335 // the shift amount is >= the size of the datatype, which is undefined.
1336 if (DemandedMask == 1) {
1337 // Perform the logical shift right.
1338 Value *NewVal = BinaryOperator::createLShr(
1339 I->getOperand(0), I->getOperand(1), I->getName());
1340 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1341 return UpdateValueUsesWith(I, NewVal);
1342 }
1343
1344 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00001345 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001346
Reid Spencer8cb68342007-03-12 17:25:59 +00001347 // Signed shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001348 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Lauro Ramos Venanciod0499af2007-06-06 17:08:48 +00001349 // If any of the "high bits" are demanded, we should set the sign bit as
1350 // demanded.
1351 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1352 DemandedMaskIn.set(BitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001353 if (SimplifyDemandedBits(I->getOperand(0),
Zhou Sheng01542f32007-03-29 02:26:30 +00001354 DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001355 RHSKnownZero, RHSKnownOne, Depth+1))
1356 return true;
1357 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1358 "Bits known to be one AND zero?");
1359 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001360 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Reid Spencer8cb68342007-03-12 17:25:59 +00001361 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1362 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1363
1364 // Handle the sign bits.
1365 APInt SignBit(APInt::getSignBit(BitWidth));
1366 // Adjust to where it is now in the mask.
1367 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1368
1369 // If the input sign bit is known to be zero, or if none of the top bits
1370 // are demanded, turn this into an unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001371 if (RHSKnownZero[BitWidth-ShiftAmt-1] ||
Reid Spencer8cb68342007-03-12 17:25:59 +00001372 (HighBits & ~DemandedMask) == HighBits) {
1373 // Perform the logical shift right.
1374 Value *NewVal = BinaryOperator::createLShr(
1375 I->getOperand(0), SA, I->getName());
1376 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1377 return UpdateValueUsesWith(I, NewVal);
1378 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1379 RHSKnownOne |= HighBits;
1380 }
1381 }
1382 break;
1383 }
1384
1385 // If the client is only demanding bits that we know, return the known
1386 // constant.
1387 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1388 return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
1389 return false;
1390}
1391
Chris Lattner867b99f2006-10-05 06:55:50 +00001392
1393/// SimplifyDemandedVectorElts - The specified value producecs a vector with
1394/// 64 or fewer elements. DemandedElts contains the set of elements that are
1395/// actually used by the caller. This method analyzes which elements of the
1396/// operand are undef and returns that information in UndefElts.
1397///
1398/// If the information about demanded elements can be used to simplify the
1399/// operation, the operation is simplified, then the resultant value is
1400/// returned. This returns null if no change was made.
1401Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1402 uint64_t &UndefElts,
1403 unsigned Depth) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001404 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner867b99f2006-10-05 06:55:50 +00001405 assert(VWidth <= 64 && "Vector too wide to analyze!");
1406 uint64_t EltMask = ~0ULL >> (64-VWidth);
1407 assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1408 "Invalid DemandedElts!");
1409
1410 if (isa<UndefValue>(V)) {
1411 // If the entire vector is undefined, just return this info.
1412 UndefElts = EltMask;
1413 return 0;
1414 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1415 UndefElts = EltMask;
1416 return UndefValue::get(V->getType());
1417 }
1418
1419 UndefElts = 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001420 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1421 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner867b99f2006-10-05 06:55:50 +00001422 Constant *Undef = UndefValue::get(EltTy);
1423
1424 std::vector<Constant*> Elts;
1425 for (unsigned i = 0; i != VWidth; ++i)
1426 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1427 Elts.push_back(Undef);
1428 UndefElts |= (1ULL << i);
1429 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1430 Elts.push_back(Undef);
1431 UndefElts |= (1ULL << i);
1432 } else { // Otherwise, defined.
1433 Elts.push_back(CP->getOperand(i));
1434 }
1435
1436 // If we changed the constant, return it.
Reid Spencer9d6565a2007-02-15 02:26:10 +00001437 Constant *NewCP = ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001438 return NewCP != CP ? NewCP : 0;
1439 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001440 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner867b99f2006-10-05 06:55:50 +00001441 // set to undef.
Reid Spencer9d6565a2007-02-15 02:26:10 +00001442 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner867b99f2006-10-05 06:55:50 +00001443 Constant *Zero = Constant::getNullValue(EltTy);
1444 Constant *Undef = UndefValue::get(EltTy);
1445 std::vector<Constant*> Elts;
1446 for (unsigned i = 0; i != VWidth; ++i)
1447 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1448 UndefElts = DemandedElts ^ EltMask;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001449 return ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001450 }
1451
1452 if (!V->hasOneUse()) { // Other users may use these bits.
1453 if (Depth != 0) { // Not at the root.
1454 // TODO: Just compute the UndefElts information recursively.
1455 return false;
1456 }
1457 return false;
1458 } else if (Depth == 10) { // Limit search depth.
1459 return false;
1460 }
1461
1462 Instruction *I = dyn_cast<Instruction>(V);
1463 if (!I) return false; // Only analyze instructions.
1464
1465 bool MadeChange = false;
1466 uint64_t UndefElts2;
1467 Value *TmpV;
1468 switch (I->getOpcode()) {
1469 default: break;
1470
1471 case Instruction::InsertElement: {
1472 // If this is a variable index, we don't know which element it overwrites.
1473 // demand exactly the same input as we produce.
Reid Spencerb83eb642006-10-20 07:07:24 +00001474 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner867b99f2006-10-05 06:55:50 +00001475 if (Idx == 0) {
1476 // Note that we can't propagate undef elt info, because we don't know
1477 // which elt is getting updated.
1478 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1479 UndefElts2, Depth+1);
1480 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1481 break;
1482 }
1483
1484 // If this is inserting an element that isn't demanded, remove this
1485 // insertelement.
Reid Spencerb83eb642006-10-20 07:07:24 +00001486 unsigned IdxNo = Idx->getZExtValue();
Chris Lattner867b99f2006-10-05 06:55:50 +00001487 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1488 return AddSoonDeadInstToWorklist(*I, 0);
1489
1490 // Otherwise, the element inserted overwrites whatever was there, so the
1491 // input demanded set is simpler than the output set.
1492 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1493 DemandedElts & ~(1ULL << IdxNo),
1494 UndefElts, Depth+1);
1495 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1496
1497 // The inserted element is defined.
1498 UndefElts |= 1ULL << IdxNo;
1499 break;
1500 }
Chris Lattner69878332007-04-14 22:29:23 +00001501 case Instruction::BitCast: {
1502 // Packed->packed casts only.
1503 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1504 if (!VTy) break;
1505 unsigned InVWidth = VTy->getNumElements();
1506 uint64_t InputDemandedElts = 0;
1507 unsigned Ratio;
1508
1509 if (VWidth == InVWidth) {
1510 // If we are converting from <4x i32> -> <4 x f32>, we demand the same
1511 // elements as are demanded of us.
1512 Ratio = 1;
1513 InputDemandedElts = DemandedElts;
1514 } else if (VWidth > InVWidth) {
1515 // Untested so far.
1516 break;
1517
1518 // If there are more elements in the result than there are in the source,
1519 // then an input element is live if any of the corresponding output
1520 // elements are live.
1521 Ratio = VWidth/InVWidth;
1522 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1523 if (DemandedElts & (1ULL << OutIdx))
1524 InputDemandedElts |= 1ULL << (OutIdx/Ratio);
1525 }
1526 } else {
1527 // Untested so far.
1528 break;
1529
1530 // If there are more elements in the source than there are in the result,
1531 // then an input element is live if the corresponding output element is
1532 // live.
1533 Ratio = InVWidth/VWidth;
1534 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1535 if (DemandedElts & (1ULL << InIdx/Ratio))
1536 InputDemandedElts |= 1ULL << InIdx;
1537 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001538
Chris Lattner69878332007-04-14 22:29:23 +00001539 // div/rem demand all inputs, because they don't want divide by zero.
1540 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1541 UndefElts2, Depth+1);
1542 if (TmpV) {
1543 I->setOperand(0, TmpV);
1544 MadeChange = true;
1545 }
1546
1547 UndefElts = UndefElts2;
1548 if (VWidth > InVWidth) {
1549 assert(0 && "Unimp");
1550 // If there are more elements in the result than there are in the source,
1551 // then an output element is undef if the corresponding input element is
1552 // undef.
1553 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1554 if (UndefElts2 & (1ULL << (OutIdx/Ratio)))
1555 UndefElts |= 1ULL << OutIdx;
1556 } else if (VWidth < InVWidth) {
1557 assert(0 && "Unimp");
1558 // If there are more elements in the source than there are in the result,
1559 // then a result element is undef if all of the corresponding input
1560 // elements are undef.
1561 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1562 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1563 if ((UndefElts2 & (1ULL << InIdx)) == 0) // Not undef?
1564 UndefElts &= ~(1ULL << (InIdx/Ratio)); // Clear undef bit.
1565 }
1566 break;
1567 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001568 case Instruction::And:
1569 case Instruction::Or:
1570 case Instruction::Xor:
1571 case Instruction::Add:
1572 case Instruction::Sub:
1573 case Instruction::Mul:
1574 // div/rem demand all inputs, because they don't want divide by zero.
1575 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1576 UndefElts, Depth+1);
1577 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1578 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1579 UndefElts2, Depth+1);
1580 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1581
1582 // Output elements are undefined if both are undefined. Consider things
1583 // like undef&0. The result is known zero, not undef.
1584 UndefElts &= UndefElts2;
1585 break;
1586
1587 case Instruction::Call: {
1588 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1589 if (!II) break;
1590 switch (II->getIntrinsicID()) {
1591 default: break;
1592
1593 // Binary vector operations that work column-wise. A dest element is a
1594 // function of the corresponding input elements from the two inputs.
1595 case Intrinsic::x86_sse_sub_ss:
1596 case Intrinsic::x86_sse_mul_ss:
1597 case Intrinsic::x86_sse_min_ss:
1598 case Intrinsic::x86_sse_max_ss:
1599 case Intrinsic::x86_sse2_sub_sd:
1600 case Intrinsic::x86_sse2_mul_sd:
1601 case Intrinsic::x86_sse2_min_sd:
1602 case Intrinsic::x86_sse2_max_sd:
1603 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1604 UndefElts, Depth+1);
1605 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1606 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1607 UndefElts2, Depth+1);
1608 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1609
1610 // If only the low elt is demanded and this is a scalarizable intrinsic,
1611 // scalarize it now.
1612 if (DemandedElts == 1) {
1613 switch (II->getIntrinsicID()) {
1614 default: break;
1615 case Intrinsic::x86_sse_sub_ss:
1616 case Intrinsic::x86_sse_mul_ss:
1617 case Intrinsic::x86_sse2_sub_sd:
1618 case Intrinsic::x86_sse2_mul_sd:
1619 // TODO: Lower MIN/MAX/ABS/etc
1620 Value *LHS = II->getOperand(1);
1621 Value *RHS = II->getOperand(2);
1622 // Extract the element as scalars.
1623 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1624 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1625
1626 switch (II->getIntrinsicID()) {
1627 default: assert(0 && "Case stmts out of sync!");
1628 case Intrinsic::x86_sse_sub_ss:
1629 case Intrinsic::x86_sse2_sub_sd:
1630 TmpV = InsertNewInstBefore(BinaryOperator::createSub(LHS, RHS,
1631 II->getName()), *II);
1632 break;
1633 case Intrinsic::x86_sse_mul_ss:
1634 case Intrinsic::x86_sse2_mul_sd:
1635 TmpV = InsertNewInstBefore(BinaryOperator::createMul(LHS, RHS,
1636 II->getName()), *II);
1637 break;
1638 }
1639
1640 Instruction *New =
1641 new InsertElementInst(UndefValue::get(II->getType()), TmpV, 0U,
1642 II->getName());
1643 InsertNewInstBefore(New, *II);
1644 AddSoonDeadInstToWorklist(*II, 0);
1645 return New;
1646 }
1647 }
1648
1649 // Output elements are undefined if both are undefined. Consider things
1650 // like undef&0. The result is known zero, not undef.
1651 UndefElts &= UndefElts2;
1652 break;
1653 }
1654 break;
1655 }
1656 }
1657 return MadeChange ? I : 0;
1658}
1659
Reid Spencere4d87aa2006-12-23 06:05:41 +00001660/// @returns true if the specified compare instruction is
1661/// true when both operands are equal...
1662/// @brief Determine if the ICmpInst returns true if both operands are equal
1663static bool isTrueWhenEqual(ICmpInst &ICI) {
1664 ICmpInst::Predicate pred = ICI.getPredicate();
1665 return pred == ICmpInst::ICMP_EQ || pred == ICmpInst::ICMP_UGE ||
1666 pred == ICmpInst::ICMP_SGE || pred == ICmpInst::ICMP_ULE ||
1667 pred == ICmpInst::ICMP_SLE;
1668}
1669
Chris Lattner564a7272003-08-13 19:01:45 +00001670/// AssociativeOpt - Perform an optimization on an associative operator. This
1671/// function is designed to check a chain of associative operators for a
1672/// potential to apply a certain optimization. Since the optimization may be
1673/// applicable if the expression was reassociated, this checks the chain, then
1674/// reassociates the expression as necessary to expose the optimization
1675/// opportunity. This makes use of a special Functor, which must define
1676/// 'shouldApply' and 'apply' methods.
1677///
1678template<typename Functor>
1679Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1680 unsigned Opcode = Root.getOpcode();
1681 Value *LHS = Root.getOperand(0);
1682
1683 // Quick check, see if the immediate LHS matches...
1684 if (F.shouldApply(LHS))
1685 return F.apply(Root);
1686
1687 // Otherwise, if the LHS is not of the same opcode as the root, return.
1688 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +00001689 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +00001690 // Should we apply this transform to the RHS?
1691 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1692
1693 // If not to the RHS, check to see if we should apply to the LHS...
1694 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1695 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1696 ShouldApply = true;
1697 }
1698
1699 // If the functor wants to apply the optimization to the RHS of LHSI,
1700 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1701 if (ShouldApply) {
1702 BasicBlock *BB = Root.getParent();
Misha Brukmanfd939082005-04-21 23:48:37 +00001703
Chris Lattner564a7272003-08-13 19:01:45 +00001704 // Now all of the instructions are in the current basic block, go ahead
1705 // and perform the reassociation.
1706 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1707
1708 // First move the selected RHS to the LHS of the root...
1709 Root.setOperand(0, LHSI->getOperand(1));
1710
1711 // Make what used to be the LHS of the root be the user of the root...
1712 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +00001713 if (&Root == TmpLHSI) {
Chris Lattner15a76c02004-04-05 02:10:19 +00001714 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1715 return 0;
1716 }
Chris Lattner65725312004-04-16 18:08:07 +00001717 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +00001718 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +00001719 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1720 BasicBlock::iterator ARI = &Root; ++ARI;
1721 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
1722 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +00001723
1724 // Now propagate the ExtraOperand down the chain of instructions until we
1725 // get to LHSI.
1726 while (TmpLHSI != LHSI) {
1727 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +00001728 // Move the instruction to immediately before the chain we are
1729 // constructing to avoid breaking dominance properties.
1730 NextLHSI->getParent()->getInstList().remove(NextLHSI);
1731 BB->getInstList().insert(ARI, NextLHSI);
1732 ARI = NextLHSI;
1733
Chris Lattner564a7272003-08-13 19:01:45 +00001734 Value *NextOp = NextLHSI->getOperand(1);
1735 NextLHSI->setOperand(1, ExtraOperand);
1736 TmpLHSI = NextLHSI;
1737 ExtraOperand = NextOp;
1738 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001739
Chris Lattner564a7272003-08-13 19:01:45 +00001740 // Now that the instructions are reassociated, have the functor perform
1741 // the transformation...
1742 return F.apply(Root);
1743 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001744
Chris Lattner564a7272003-08-13 19:01:45 +00001745 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1746 }
1747 return 0;
1748}
1749
1750
1751// AddRHS - Implements: X + X --> X << 1
1752struct AddRHS {
1753 Value *RHS;
1754 AddRHS(Value *rhs) : RHS(rhs) {}
1755 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1756 Instruction *apply(BinaryOperator &Add) const {
Reid Spencercc46cdb2007-02-02 14:08:20 +00001757 return BinaryOperator::createShl(Add.getOperand(0),
Reid Spencer832254e2007-02-02 02:16:23 +00001758 ConstantInt::get(Add.getType(), 1));
Chris Lattner564a7272003-08-13 19:01:45 +00001759 }
1760};
1761
1762// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1763// iff C1&C2 == 0
1764struct AddMaskingAnd {
1765 Constant *C2;
1766 AddMaskingAnd(Constant *c) : C2(c) {}
1767 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001768 ConstantInt *C1;
Misha Brukmanfd939082005-04-21 23:48:37 +00001769 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001770 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +00001771 }
1772 Instruction *apply(BinaryOperator &Add) const {
Chris Lattner48595f12004-06-10 02:07:29 +00001773 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +00001774 }
1775};
1776
Chris Lattner6e7ba452005-01-01 16:22:27 +00001777static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +00001778 InstCombiner *IC) {
Reid Spencer3da59db2006-11-27 01:05:10 +00001779 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Chris Lattner6e7ba452005-01-01 16:22:27 +00001780 if (Constant *SOC = dyn_cast<Constant>(SO))
Reid Spencer3da59db2006-11-27 01:05:10 +00001781 return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
Misha Brukmanfd939082005-04-21 23:48:37 +00001782
Reid Spencer3da59db2006-11-27 01:05:10 +00001783 return IC->InsertNewInstBefore(CastInst::create(
1784 CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001785 }
1786
Chris Lattner2eefe512004-04-09 19:05:30 +00001787 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +00001788 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1789 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +00001790
Chris Lattner2eefe512004-04-09 19:05:30 +00001791 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1792 if (ConstIsRHS)
Chris Lattner6e7ba452005-01-01 16:22:27 +00001793 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1794 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +00001795 }
1796
1797 Value *Op0 = SO, *Op1 = ConstOperand;
1798 if (!ConstIsRHS)
1799 std::swap(Op0, Op1);
1800 Instruction *New;
Chris Lattner6e7ba452005-01-01 16:22:27 +00001801 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1802 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Reid Spencere4d87aa2006-12-23 06:05:41 +00001803 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1804 New = CmpInst::create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
1805 SO->getName()+".cmp");
Chris Lattner326c0f32004-04-10 19:15:56 +00001806 else {
Chris Lattner2eefe512004-04-09 19:05:30 +00001807 assert(0 && "Unknown binary instruction type!");
Chris Lattner326c0f32004-04-10 19:15:56 +00001808 abort();
1809 }
Chris Lattner6e7ba452005-01-01 16:22:27 +00001810 return IC->InsertNewInstBefore(New, I);
1811}
1812
1813// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1814// constant as the other operand, try to fold the binary operator into the
1815// select arguments. This also works for Cast instructions, which obviously do
1816// not have a second operand.
1817static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1818 InstCombiner *IC) {
1819 // Don't modify shared select instructions
1820 if (!SI->hasOneUse()) return 0;
1821 Value *TV = SI->getOperand(1);
1822 Value *FV = SI->getOperand(2);
1823
1824 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +00001825 // Bool selects with constant operands can be folded to logical ops.
Reid Spencer4fe16d62007-01-11 18:21:29 +00001826 if (SI->getType() == Type::Int1Ty) return 0;
Chris Lattner956db272005-04-21 05:43:13 +00001827
Chris Lattner6e7ba452005-01-01 16:22:27 +00001828 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1829 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1830
1831 return new SelectInst(SI->getCondition(), SelectTrueVal,
1832 SelectFalseVal);
1833 }
1834 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +00001835}
1836
Chris Lattner4e998b22004-09-29 05:07:12 +00001837
1838/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1839/// node as operand #0, see if we can fold the instruction into the PHI (which
1840/// is only possible if all operands to the PHI are constants).
1841Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1842 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00001843 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001844 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner4e998b22004-09-29 05:07:12 +00001845
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001846 // Check to see if all of the operands of the PHI are constants. If there is
1847 // one non-constant value, remember the BB it is. If there is more than one
Chris Lattnerb3036682007-02-24 01:03:45 +00001848 // or if *it* is a PHI, bail out.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001849 BasicBlock *NonConstBB = 0;
1850 for (unsigned i = 0; i != NumPHIValues; ++i)
1851 if (!isa<Constant>(PN->getIncomingValue(i))) {
1852 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +00001853 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001854 NonConstBB = PN->getIncomingBlock(i);
1855
1856 // If the incoming non-constant value is in I's block, we have an infinite
1857 // loop.
1858 if (NonConstBB == I.getParent())
1859 return 0;
1860 }
1861
1862 // If there is exactly one non-constant value, we can insert a copy of the
1863 // operation in that block. However, if this is a critical edge, we would be
1864 // inserting the computation one some other paths (e.g. inside a loop). Only
1865 // do this if the pred block is unconditionally branching into the phi block.
1866 if (NonConstBB) {
1867 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1868 if (!BI || !BI->isUnconditional()) return 0;
1869 }
Chris Lattner4e998b22004-09-29 05:07:12 +00001870
1871 // Okay, we can do the transformation: create the new PHI node.
Chris Lattner6934a042007-02-11 01:23:03 +00001872 PHINode *NewPN = new PHINode(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +00001873 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner4e998b22004-09-29 05:07:12 +00001874 InsertNewInstBefore(NewPN, *PN);
Chris Lattner6934a042007-02-11 01:23:03 +00001875 NewPN->takeName(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +00001876
1877 // Next, add all of the operands to the PHI.
1878 if (I.getNumOperands() == 2) {
1879 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +00001880 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001881 Value *InV;
1882 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001883 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1884 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1885 else
1886 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001887 } else {
1888 assert(PN->getIncomingBlock(i) == NonConstBB);
1889 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1890 InV = BinaryOperator::create(BO->getOpcode(),
1891 PN->getIncomingValue(i), C, "phitmp",
1892 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +00001893 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1894 InV = CmpInst::create(CI->getOpcode(),
1895 CI->getPredicate(),
1896 PN->getIncomingValue(i), C, "phitmp",
1897 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001898 else
1899 assert(0 && "Unknown binop!");
1900
Chris Lattnerdbab3862007-03-02 21:28:56 +00001901 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001902 }
1903 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00001904 }
Reid Spencer3da59db2006-11-27 01:05:10 +00001905 } else {
1906 CastInst *CI = cast<CastInst>(&I);
1907 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +00001908 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001909 Value *InV;
1910 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00001911 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001912 } else {
1913 assert(PN->getIncomingBlock(i) == NonConstBB);
Reid Spencer3da59db2006-11-27 01:05:10 +00001914 InV = CastInst::create(CI->getOpcode(), PN->getIncomingValue(i),
1915 I.getType(), "phitmp",
1916 NonConstBB->getTerminator());
Chris Lattnerdbab3862007-03-02 21:28:56 +00001917 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001918 }
1919 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00001920 }
1921 }
1922 return ReplaceInstUsesWith(I, NewPN);
1923}
1924
Chris Lattner7e708292002-06-25 16:13:24 +00001925Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00001926 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00001927 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +00001928
Chris Lattner66331a42004-04-10 22:01:55 +00001929 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattnere87597f2004-10-16 18:11:37 +00001930 // X + undef -> undef
1931 if (isa<UndefValue>(RHS))
1932 return ReplaceInstUsesWith(I, RHS);
1933
Chris Lattner66331a42004-04-10 22:01:55 +00001934 // X + 0 --> X
Chris Lattner9919e3d2006-12-02 00:13:08 +00001935 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
Chris Lattner5e678e02005-10-17 17:56:38 +00001936 if (RHSC->isNullValue())
1937 return ReplaceInstUsesWith(I, LHS);
Chris Lattner8532cf62005-10-17 20:18:38 +00001938 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1939 if (CFP->isExactlyValue(-0.0))
1940 return ReplaceInstUsesWith(I, LHS);
Chris Lattner5e678e02005-10-17 17:56:38 +00001941 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001942
Chris Lattner66331a42004-04-10 22:01:55 +00001943 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerb4a2f052006-11-09 05:12:27 +00001944 // X + (signbit) --> X ^ signbit
Zhou Sheng3a507fd2007-04-01 17:13:37 +00001945 const APInt& Val = CI->getValue();
Zhou Sheng4351c642007-04-02 08:20:41 +00001946 uint32_t BitWidth = Val.getBitWidth();
Reid Spencer2ec619a2007-03-23 21:24:59 +00001947 if (Val == APInt::getSignBit(BitWidth))
Chris Lattner48595f12004-06-10 02:07:29 +00001948 return BinaryOperator::createXor(LHS, RHS);
Chris Lattnerb4a2f052006-11-09 05:12:27 +00001949
1950 // See if SimplifyDemandedBits can simplify this. This handles stuff like
1951 // (X & 254)+1 -> (X&254)|1
Reid Spencer2ec619a2007-03-23 21:24:59 +00001952 if (!isa<VectorType>(I.getType())) {
1953 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
1954 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
1955 KnownZero, KnownOne))
1956 return &I;
1957 }
Chris Lattner66331a42004-04-10 22:01:55 +00001958 }
Chris Lattner4e998b22004-09-29 05:07:12 +00001959
1960 if (isa<PHINode>(LHS))
1961 if (Instruction *NV = FoldOpIntoPhi(I))
1962 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +00001963
Chris Lattner4f637d42006-01-06 17:59:59 +00001964 ConstantInt *XorRHS = 0;
1965 Value *XorLHS = 0;
Chris Lattnerc5eff442007-01-30 22:32:46 +00001966 if (isa<ConstantInt>(RHSC) &&
1967 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Zhou Sheng4351c642007-04-02 08:20:41 +00001968 uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00001969 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner5931c542005-09-24 23:43:33 +00001970
Zhou Sheng4351c642007-04-02 08:20:41 +00001971 uint32_t Size = TySizeBits / 2;
Reid Spencer2ec619a2007-03-23 21:24:59 +00001972 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
1973 APInt CFF80Val(-C0080Val);
Chris Lattner5931c542005-09-24 23:43:33 +00001974 do {
1975 if (TySizeBits > Size) {
Chris Lattner5931c542005-09-24 23:43:33 +00001976 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1977 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer2ec619a2007-03-23 21:24:59 +00001978 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
1979 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner5931c542005-09-24 23:43:33 +00001980 // This is a sign extend if the top bits are known zero.
Zhou Sheng290bec52007-03-29 08:15:12 +00001981 if (!MaskedValueIsZero(XorLHS,
1982 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner5931c542005-09-24 23:43:33 +00001983 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer2ec619a2007-03-23 21:24:59 +00001984 break;
Chris Lattner5931c542005-09-24 23:43:33 +00001985 }
1986 }
1987 Size >>= 1;
Reid Spencer2ec619a2007-03-23 21:24:59 +00001988 C0080Val = APIntOps::lshr(C0080Val, Size);
1989 CFF80Val = APIntOps::ashr(CFF80Val, Size);
1990 } while (Size >= 1);
Chris Lattner5931c542005-09-24 23:43:33 +00001991
Reid Spencer35c38852007-03-28 01:36:16 +00001992 // FIXME: This shouldn't be necessary. When the backends can handle types
1993 // with funny bit widths then this whole cascade of if statements should
1994 // be removed. It is just here to get the size of the "middle" type back
1995 // up to something that the back ends can handle.
1996 const Type *MiddleType = 0;
1997 switch (Size) {
1998 default: break;
1999 case 32: MiddleType = Type::Int32Ty; break;
2000 case 16: MiddleType = Type::Int16Ty; break;
2001 case 8: MiddleType = Type::Int8Ty; break;
2002 }
2003 if (MiddleType) {
Reid Spencerd977d862006-12-12 23:36:14 +00002004 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
Chris Lattner5931c542005-09-24 23:43:33 +00002005 InsertNewInstBefore(NewTrunc, I);
Reid Spencer35c38852007-03-28 01:36:16 +00002006 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner5931c542005-09-24 23:43:33 +00002007 }
2008 }
Chris Lattner66331a42004-04-10 22:01:55 +00002009 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002010
Chris Lattner564a7272003-08-13 19:01:45 +00002011 // X + X --> X << 1
Chris Lattner42a75512007-01-15 02:27:26 +00002012 if (I.getType()->isInteger() && I.getType() != Type::Int1Ty) {
Chris Lattner564a7272003-08-13 19:01:45 +00002013 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +00002014
2015 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2016 if (RHSI->getOpcode() == Instruction::Sub)
2017 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2018 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2019 }
2020 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2021 if (LHSI->getOpcode() == Instruction::Sub)
2022 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2023 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2024 }
Robert Bocchino71698282004-07-27 21:02:21 +00002025 }
Chris Lattnere92d2f42003-08-13 04:18:28 +00002026
Chris Lattner5c4afb92002-05-08 22:46:53 +00002027 // -A + B --> B - A
Chris Lattner8d969642003-03-10 23:06:50 +00002028 if (Value *V = dyn_castNegVal(LHS))
Chris Lattner48595f12004-06-10 02:07:29 +00002029 return BinaryOperator::createSub(RHS, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002030
2031 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +00002032 if (!isa<Constant>(RHS))
2033 if (Value *V = dyn_castNegVal(RHS))
Chris Lattner48595f12004-06-10 02:07:29 +00002034 return BinaryOperator::createSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002035
Misha Brukmanfd939082005-04-21 23:48:37 +00002036
Chris Lattner50af16a2004-11-13 19:50:12 +00002037 ConstantInt *C2;
2038 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2039 if (X == RHS) // X*C + X --> X * (C+1)
2040 return BinaryOperator::createMul(RHS, AddOne(C2));
2041
2042 // X*C1 + X*C2 --> X * (C1+C2)
2043 ConstantInt *C1;
2044 if (X == dyn_castFoldableMul(RHS, C1))
Reid Spencer7177c3a2007-03-25 05:33:51 +00002045 return BinaryOperator::createMul(X, Add(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002046 }
2047
2048 // X + X*C --> X * (C+1)
Chris Lattner50af16a2004-11-13 19:50:12 +00002049 if (dyn_castFoldableMul(RHS, C2) == LHS)
2050 return BinaryOperator::createMul(LHS, AddOne(C2));
2051
Chris Lattnere617c9e2007-01-05 02:17:46 +00002052 // X + ~X --> -1 since ~X = -X-1
2053 if (dyn_castNotVal(LHS) == RHS ||
2054 dyn_castNotVal(RHS) == LHS)
2055 return ReplaceInstUsesWith(I, ConstantInt::getAllOnesValue(I.getType()));
2056
Chris Lattnerad3448c2003-02-18 19:57:07 +00002057
Chris Lattner564a7272003-08-13 19:01:45 +00002058 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002059 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnere617c9e2007-01-05 02:17:46 +00002060 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2061 return R;
Chris Lattnerc8802d22003-03-11 00:12:48 +00002062
Chris Lattner6b032052003-10-02 15:11:26 +00002063 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002064 Value *X = 0;
Reid Spencer7177c3a2007-03-25 05:33:51 +00002065 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
2066 return BinaryOperator::createSub(SubOne(CRHS), X);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002067
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002068 // (X & FF00) + xx00 -> (X+xx00) & FF00
2069 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002070 Constant *Anded = And(CRHS, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002071 if (Anded == CRHS) {
2072 // See if all bits from the first bit set in the Add RHS up are included
2073 // in the mask. First, get the rightmost bit.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002074 const APInt& AddRHSV = CRHS->getValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002075
2076 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002077 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002078
2079 // See if the and mask includes all of these bits.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002080 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanfd939082005-04-21 23:48:37 +00002081
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002082 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2083 // Okay, the xform is safe. Insert the new add pronto.
2084 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
2085 LHS->getName()), I);
2086 return BinaryOperator::createAnd(NewAdd, C2);
2087 }
2088 }
2089 }
2090
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002091 // Try to fold constant add into select arguments.
2092 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002093 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002094 return R;
Chris Lattner6b032052003-10-02 15:11:26 +00002095 }
2096
Reid Spencer1628cec2006-10-26 06:15:43 +00002097 // add (cast *A to intptrtype) B ->
2098 // cast (GEP (cast *A to sbyte*) B) ->
2099 // intptrtype
Andrew Lenharth16d79552006-09-19 18:24:51 +00002100 {
Reid Spencer3da59db2006-11-27 01:05:10 +00002101 CastInst *CI = dyn_cast<CastInst>(LHS);
2102 Value *Other = RHS;
Andrew Lenharth16d79552006-09-19 18:24:51 +00002103 if (!CI) {
2104 CI = dyn_cast<CastInst>(RHS);
2105 Other = LHS;
2106 }
Andrew Lenharth45633262006-09-20 15:37:57 +00002107 if (CI && CI->getType()->isSized() &&
Reid Spencerabaa8ca2007-01-08 16:32:00 +00002108 (CI->getType()->getPrimitiveSizeInBits() ==
2109 TD->getIntPtrType()->getPrimitiveSizeInBits())
Andrew Lenharth45633262006-09-20 15:37:57 +00002110 && isa<PointerType>(CI->getOperand(0)->getType())) {
Reid Spencer17212df2006-12-12 09:18:51 +00002111 Value *I2 = InsertCastBefore(Instruction::BitCast, CI->getOperand(0),
Reid Spencerc5b206b2006-12-31 05:48:39 +00002112 PointerType::get(Type::Int8Ty), I);
Andrew Lenharth45633262006-09-20 15:37:57 +00002113 I2 = InsertNewInstBefore(new GetElementPtrInst(I2, Other, "ctg2"), I);
Reid Spencer3da59db2006-11-27 01:05:10 +00002114 return new PtrToIntInst(I2, CI->getType());
Andrew Lenharth16d79552006-09-19 18:24:51 +00002115 }
2116 }
2117
Chris Lattner7e708292002-06-25 16:13:24 +00002118 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002119}
2120
Chris Lattner1ba5bcd2003-07-22 21:46:59 +00002121// isSignBit - Return true if the value represented by the constant only has the
2122// highest order bit set.
2123static bool isSignBit(ConstantInt *CI) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002124 uint32_t NumBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencer5a1e3e12007-03-19 20:58:18 +00002125 return CI->getValue() == APInt::getSignBit(NumBits);
Chris Lattner1ba5bcd2003-07-22 21:46:59 +00002126}
2127
Chris Lattner7e708292002-06-25 16:13:24 +00002128Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00002129 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002130
Chris Lattner233f7dc2002-08-12 21:17:25 +00002131 if (Op0 == Op1) // sub X, X -> 0
2132 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002133
Chris Lattner233f7dc2002-08-12 21:17:25 +00002134 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattner8d969642003-03-10 23:06:50 +00002135 if (Value *V = dyn_castNegVal(Op1))
Chris Lattner48595f12004-06-10 02:07:29 +00002136 return BinaryOperator::createAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002137
Chris Lattnere87597f2004-10-16 18:11:37 +00002138 if (isa<UndefValue>(Op0))
2139 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2140 if (isa<UndefValue>(Op1))
2141 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2142
Chris Lattnerd65460f2003-11-05 01:06:05 +00002143 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2144 // Replace (-1 - A) with (~A)...
Chris Lattnera2881962003-02-18 19:28:33 +00002145 if (C->isAllOnesValue())
2146 return BinaryOperator::createNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +00002147
Chris Lattnerd65460f2003-11-05 01:06:05 +00002148 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002149 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002150 if (match(Op1, m_Not(m_Value(X))))
Reid Spencer7177c3a2007-03-25 05:33:51 +00002151 return BinaryOperator::createAdd(X, AddOne(C));
2152
Chris Lattner76b7a062007-01-15 07:02:54 +00002153 // -(X >>u 31) -> (X >>s 31)
2154 // -(X >>s 31) -> (X >>u 31)
Zhou Sheng302748d2007-03-30 17:20:39 +00002155 if (C->isZero()) {
Reid Spencer832254e2007-02-02 02:16:23 +00002156 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1))
Reid Spencer3822ff52006-11-08 06:47:33 +00002157 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002158 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00002159 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002160 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerb83eb642006-10-20 07:07:24 +00002161 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002162 // Ok, the transformation is safe. Insert AShr.
Reid Spencer832254e2007-02-02 02:16:23 +00002163 return BinaryOperator::create(Instruction::AShr,
2164 SI->getOperand(0), CU, SI->getName());
Chris Lattner9c290672004-03-12 23:53:13 +00002165 }
2166 }
Reid Spencer3822ff52006-11-08 06:47:33 +00002167 }
2168 else if (SI->getOpcode() == Instruction::AShr) {
2169 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2170 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002171 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencer3822ff52006-11-08 06:47:33 +00002172 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00002173 // Ok, the transformation is safe. Insert LShr.
Reid Spencercc46cdb2007-02-02 14:08:20 +00002174 return BinaryOperator::createLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00002175 SI->getOperand(0), CU, SI->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00002176 }
2177 }
2178 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00002179 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002180
2181 // Try to fold constant sub into select arguments.
2182 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002183 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002184 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002185
2186 if (isa<PHINode>(Op0))
2187 if (Instruction *NV = FoldOpIntoPhi(I))
2188 return NV;
Chris Lattnerd65460f2003-11-05 01:06:05 +00002189 }
2190
Chris Lattner43d84d62005-04-07 16:15:25 +00002191 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2192 if (Op1I->getOpcode() == Instruction::Add &&
Chris Lattner9919e3d2006-12-02 00:13:08 +00002193 !Op0->getType()->isFPOrFPVector()) {
Chris Lattner08954a22005-04-07 16:28:01 +00002194 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Chris Lattner43d84d62005-04-07 16:15:25 +00002195 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002196 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Chris Lattner43d84d62005-04-07 16:15:25 +00002197 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002198 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2199 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2200 // C1-(X+C2) --> (C1-C2)-X
Reid Spencer7177c3a2007-03-25 05:33:51 +00002201 return BinaryOperator::createSub(Subtract(CI1, CI2),
Chris Lattner08954a22005-04-07 16:28:01 +00002202 Op1I->getOperand(0));
2203 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002204 }
2205
Chris Lattnerfd059242003-10-15 16:48:29 +00002206 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002207 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2208 // is not used by anyone else...
2209 //
Chris Lattner0517e722004-02-02 20:09:56 +00002210 if (Op1I->getOpcode() == Instruction::Sub &&
Chris Lattner9919e3d2006-12-02 00:13:08 +00002211 !Op1I->getType()->isFPOrFPVector()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002212 // Swap the two operands of the subexpr...
2213 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2214 Op1I->setOperand(0, IIOp1);
2215 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00002216
Chris Lattnera2881962003-02-18 19:28:33 +00002217 // Create the new top level add instruction...
Chris Lattner48595f12004-06-10 02:07:29 +00002218 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00002219 }
2220
2221 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2222 //
2223 if (Op1I->getOpcode() == Instruction::And &&
2224 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2225 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2226
Chris Lattnerf523d062004-06-09 05:08:07 +00002227 Value *NewNot =
2228 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattner48595f12004-06-10 02:07:29 +00002229 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00002230 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00002231
Reid Spencerac5209e2006-10-16 23:08:08 +00002232 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer1628cec2006-10-26 06:15:43 +00002233 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencerb83eb642006-10-20 07:07:24 +00002234 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Zhou Sheng843f07672007-04-19 05:39:12 +00002235 if (CSI->isZero())
Chris Lattner91ccc152004-10-06 15:08:25 +00002236 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Reid Spencer1628cec2006-10-26 06:15:43 +00002237 return BinaryOperator::createSDiv(Op1I->getOperand(0),
Chris Lattner91ccc152004-10-06 15:08:25 +00002238 ConstantExpr::getNeg(DivRHS));
2239
Chris Lattnerad3448c2003-02-18 19:57:07 +00002240 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002241 ConstantInt *C2 = 0;
Chris Lattner50af16a2004-11-13 19:50:12 +00002242 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002243 Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
Chris Lattner48595f12004-06-10 02:07:29 +00002244 return BinaryOperator::createMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00002245 }
Chris Lattner40371712002-05-09 01:29:19 +00002246 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002247 }
Chris Lattnera2881962003-02-18 19:28:33 +00002248
Chris Lattner9919e3d2006-12-02 00:13:08 +00002249 if (!Op0->getType()->isFPOrFPVector())
Chris Lattner7edc8c22005-04-07 17:14:51 +00002250 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2251 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00002252 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2253 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2254 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2255 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner7edc8c22005-04-07 17:14:51 +00002256 } else if (Op0I->getOpcode() == Instruction::Sub) {
2257 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
2258 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00002259 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002260
Chris Lattner50af16a2004-11-13 19:50:12 +00002261 ConstantInt *C1;
2262 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002263 if (X == Op1) // X*C - X --> X * (C-1)
2264 return BinaryOperator::createMul(Op1, SubOne(C1));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002265
Chris Lattner50af16a2004-11-13 19:50:12 +00002266 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2267 if (X == dyn_castFoldableMul(Op1, C2))
Reid Spencer7177c3a2007-03-25 05:33:51 +00002268 return BinaryOperator::createMul(Op1, Subtract(C1, C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002269 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002270 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002271}
2272
Reid Spencere4d87aa2006-12-23 06:05:41 +00002273/// isSignBitCheck - Given an exploded icmp instruction, return true if it
Chris Lattner4cb170c2004-02-23 06:38:22 +00002274/// really just returns true if the most significant (sign) bit is set.
Reid Spencere4d87aa2006-12-23 06:05:41 +00002275static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS) {
2276 switch (pred) {
2277 case ICmpInst::ICMP_SLT:
2278 // True if LHS s< RHS and RHS == 0
Zhou Sheng843f07672007-04-19 05:39:12 +00002279 return RHS->isZero();
Reid Spencere4d87aa2006-12-23 06:05:41 +00002280 case ICmpInst::ICMP_SLE:
2281 // True if LHS s<= RHS and RHS == -1
2282 return RHS->isAllOnesValue();
2283 case ICmpInst::ICMP_UGE:
2284 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
Reid Spencerf2442522007-03-24 00:42:08 +00002285 return RHS->getValue() ==
2286 APInt::getSignBit(RHS->getType()->getPrimitiveSizeInBits());
Reid Spencere4d87aa2006-12-23 06:05:41 +00002287 case ICmpInst::ICMP_UGT:
2288 // True if LHS u> RHS and RHS == high-bit-mask - 1
Reid Spencerf2442522007-03-24 00:42:08 +00002289 return RHS->getValue() ==
2290 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
Reid Spencere4d87aa2006-12-23 06:05:41 +00002291 default:
2292 return false;
Chris Lattner4cb170c2004-02-23 06:38:22 +00002293 }
Chris Lattner4cb170c2004-02-23 06:38:22 +00002294}
2295
Chris Lattner7e708292002-06-25 16:13:24 +00002296Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002297 bool Changed = SimplifyCommutative(I);
Chris Lattnera2881962003-02-18 19:28:33 +00002298 Value *Op0 = I.getOperand(0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002299
Chris Lattnere87597f2004-10-16 18:11:37 +00002300 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2301 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2302
Chris Lattner233f7dc2002-08-12 21:17:25 +00002303 // Simplify mul instructions with a constant RHS...
Chris Lattnera2881962003-02-18 19:28:33 +00002304 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2305 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00002306
2307 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer832254e2007-02-02 02:16:23 +00002308 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnere92d2f42003-08-13 04:18:28 +00002309 if (SI->getOpcode() == Instruction::Shl)
2310 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattner48595f12004-06-10 02:07:29 +00002311 return BinaryOperator::createMul(SI->getOperand(0),
2312 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00002313
Zhou Sheng843f07672007-04-19 05:39:12 +00002314 if (CI->isZero())
Chris Lattner515c97c2003-09-11 22:24:54 +00002315 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2316 if (CI->equalsInt(1)) // X * 1 == X
2317 return ReplaceInstUsesWith(I, Op0);
2318 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner0af1fab2003-06-25 17:09:20 +00002319 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00002320
Zhou Sheng97b52c22007-03-29 01:57:21 +00002321 const APInt& Val = cast<ConstantInt>(CI)->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002322 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Reid Spencercc46cdb2007-02-02 14:08:20 +00002323 return BinaryOperator::createShl(Op0,
Reid Spencerbca0e382007-03-23 20:05:17 +00002324 ConstantInt::get(Op0->getType(), Val.logBase2()));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00002325 }
Robert Bocchino71698282004-07-27 21:02:21 +00002326 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattnera2881962003-02-18 19:28:33 +00002327 if (Op1F->isNullValue())
2328 return ReplaceInstUsesWith(I, Op1);
Chris Lattner6c1ce212002-04-29 22:24:47 +00002329
Chris Lattnera2881962003-02-18 19:28:33 +00002330 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2331 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2332 if (Op1F->getValue() == 1.0)
2333 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2334 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002335
2336 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2337 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2338 isa<ConstantInt>(Op0I->getOperand(1))) {
2339 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2340 Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
2341 Op1, "tmp");
2342 InsertNewInstBefore(Add, I);
2343 Value *C1C2 = ConstantExpr::getMul(Op1,
2344 cast<Constant>(Op0I->getOperand(1)));
2345 return BinaryOperator::createAdd(Add, C1C2);
2346
2347 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002348
2349 // Try to fold constant mul into select arguments.
2350 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002351 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002352 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002353
2354 if (isa<PHINode>(Op0))
2355 if (Instruction *NV = FoldOpIntoPhi(I))
2356 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002357 }
2358
Chris Lattnera4f445b2003-03-10 23:23:04 +00002359 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2360 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattner48595f12004-06-10 02:07:29 +00002361 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00002362
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002363 // If one of the operands of the multiply is a cast from a boolean value, then
2364 // we know the bool is either zero or one, so this is a 'masking' multiply.
2365 // See if we can simplify things based on how the boolean was originally
2366 // formed.
2367 CastInst *BoolCast = 0;
Reid Spencerc55b2432006-12-13 18:21:21 +00002368 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(0)))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002369 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002370 BoolCast = CI;
2371 if (!BoolCast)
Reid Spencerc55b2432006-12-13 18:21:21 +00002372 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002373 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002374 BoolCast = CI;
2375 if (BoolCast) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002376 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002377 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2378 const Type *SCOpTy = SCIOp0->getType();
2379
Reid Spencere4d87aa2006-12-23 06:05:41 +00002380 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattner4cb170c2004-02-23 06:38:22 +00002381 // multiply into a shift/and combination.
2382 if (isa<ConstantInt>(SCIOp1) &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00002383 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1))) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002384 // Shift the X value right to turn it into "all signbits".
Reid Spencer832254e2007-02-02 02:16:23 +00002385 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
Chris Lattner484d3cf2005-04-24 06:59:08 +00002386 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattner4cb170c2004-02-23 06:38:22 +00002387 Value *V =
Reid Spencer832254e2007-02-02 02:16:23 +00002388 InsertNewInstBefore(
2389 BinaryOperator::create(Instruction::AShr, SCIOp0, Amt,
Chris Lattner4cb170c2004-02-23 06:38:22 +00002390 BoolCast->getOperand(0)->getName()+
2391 ".mask"), I);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002392
2393 // If the multiply type is not the same as the source type, sign extend
2394 // or truncate to the multiply type.
Reid Spencer17212df2006-12-12 09:18:51 +00002395 if (I.getType() != V->getType()) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002396 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2397 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +00002398 Instruction::CastOps opcode =
2399 (SrcBits == DstBits ? Instruction::BitCast :
2400 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2401 V = InsertCastBefore(opcode, V, I.getType(), I);
2402 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002403
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002404 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattner48595f12004-06-10 02:07:29 +00002405 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002406 }
2407 }
2408 }
2409
Chris Lattner7e708292002-06-25 16:13:24 +00002410 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002411}
2412
Reid Spencer1628cec2006-10-26 06:15:43 +00002413/// This function implements the transforms on div instructions that work
2414/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2415/// used by the visitors to those instructions.
2416/// @brief Transforms common to all three div instructions
Reid Spencer3da59db2006-11-27 01:05:10 +00002417Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002418 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00002419
Reid Spencer1628cec2006-10-26 06:15:43 +00002420 // undef / X -> 0
2421 if (isa<UndefValue>(Op0))
Chris Lattner857e8cd2004-12-12 21:48:58 +00002422 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Reid Spencer1628cec2006-10-26 06:15:43 +00002423
2424 // X / undef -> undef
Chris Lattner857e8cd2004-12-12 21:48:58 +00002425 if (isa<UndefValue>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00002426 return ReplaceInstUsesWith(I, Op1);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002427
Reid Spencer1628cec2006-10-26 06:15:43 +00002428 // Handle cases involving: div X, (select Cond, Y, Z)
Chris Lattner8e49e082006-09-09 20:26:32 +00002429 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2430 // div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in the
Reid Spencer1628cec2006-10-26 06:15:43 +00002431 // same basic block, then we replace the select with Y, and the condition
2432 // of the select with false (if the cond value is in the same BB). If the
Chris Lattner8e49e082006-09-09 20:26:32 +00002433 // select has uses other than the div, this allows them to be simplified
Reid Spencer1628cec2006-10-26 06:15:43 +00002434 // also. Note that div X, Y is just as good as div X, 0 (undef)
Chris Lattner8e49e082006-09-09 20:26:32 +00002435 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2436 if (ST->isNullValue()) {
2437 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2438 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002439 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Chris Lattner8e49e082006-09-09 20:26:32 +00002440 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2441 I.setOperand(1, SI->getOperand(2));
2442 else
2443 UpdateValueUsesWith(SI, SI->getOperand(2));
2444 return &I;
2445 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002446
Chris Lattner8e49e082006-09-09 20:26:32 +00002447 // Likewise for: div X, (Cond ? Y : 0) -> div X, Y
2448 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2449 if (ST->isNullValue()) {
2450 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2451 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002452 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Chris Lattner8e49e082006-09-09 20:26:32 +00002453 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2454 I.setOperand(1, SI->getOperand(1));
2455 else
2456 UpdateValueUsesWith(SI, SI->getOperand(1));
2457 return &I;
2458 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002459 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002460
Reid Spencer1628cec2006-10-26 06:15:43 +00002461 return 0;
2462}
Misha Brukmanfd939082005-04-21 23:48:37 +00002463
Reid Spencer1628cec2006-10-26 06:15:43 +00002464/// This function implements the transforms common to both integer division
2465/// instructions (udiv and sdiv). It is called by the visitors to those integer
2466/// division instructions.
2467/// @brief Common integer divide transforms
Reid Spencer3da59db2006-11-27 01:05:10 +00002468Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002469 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2470
2471 if (Instruction *Common = commonDivTransforms(I))
2472 return Common;
2473
2474 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2475 // div X, 1 == X
2476 if (RHS->equalsInt(1))
2477 return ReplaceInstUsesWith(I, Op0);
2478
2479 // (X / C1) / C2 -> X / (C1*C2)
2480 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2481 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2482 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2483 return BinaryOperator::create(I.getOpcode(), LHS->getOperand(0),
Reid Spencer7177c3a2007-03-25 05:33:51 +00002484 Multiply(RHS, LHSRHS));
Chris Lattnerbf70b832005-04-08 04:03:26 +00002485 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002486
Reid Spencerbca0e382007-03-23 20:05:17 +00002487 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer1628cec2006-10-26 06:15:43 +00002488 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2489 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2490 return R;
2491 if (isa<PHINode>(Op0))
2492 if (Instruction *NV = FoldOpIntoPhi(I))
2493 return NV;
2494 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002495 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002496
Chris Lattnera2881962003-02-18 19:28:33 +00002497 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00002498 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00002499 if (LHS->equalsInt(0))
2500 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2501
Reid Spencer1628cec2006-10-26 06:15:43 +00002502 return 0;
2503}
2504
2505Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2506 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2507
2508 // Handle the integer div common cases
2509 if (Instruction *Common = commonIDivTransforms(I))
2510 return Common;
2511
2512 // X udiv C^2 -> X >> C
2513 // Check to see if this is an unsigned division with an exact power of 2,
2514 // if so, convert to a right shift.
2515 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Reid Spencer6eb0d992007-03-26 23:58:26 +00002516 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Reid Spencerbca0e382007-03-23 20:05:17 +00002517 return BinaryOperator::createLShr(Op0,
Zhou Sheng0fc50952007-03-25 05:01:29 +00002518 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Reid Spencer1628cec2006-10-26 06:15:43 +00002519 }
2520
2521 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer832254e2007-02-02 02:16:23 +00002522 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002523 if (RHSI->getOpcode() == Instruction::Shl &&
2524 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002525 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002526 if (C1.isPowerOf2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002527 Value *N = RHSI->getOperand(1);
Reid Spencer3da59db2006-11-27 01:05:10 +00002528 const Type *NTy = N->getType();
Reid Spencer2ec619a2007-03-23 21:24:59 +00002529 if (uint32_t C2 = C1.logBase2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002530 Constant *C2V = ConstantInt::get(NTy, C2);
2531 N = InsertNewInstBefore(BinaryOperator::createAdd(N, C2V, "tmp"), I);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002532 }
Reid Spencercc46cdb2007-02-02 14:08:20 +00002533 return BinaryOperator::createLShr(Op0, N);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002534 }
2535 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00002536 }
2537
Reid Spencer1628cec2006-10-26 06:15:43 +00002538 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2539 // where C1&C2 are powers of two.
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002540 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00002541 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002542 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002543 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002544 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002545 // Compute the shift amounts
Reid Spencerbca0e382007-03-23 20:05:17 +00002546 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002547 // Construct the "on true" case of the select
2548 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
2549 Instruction *TSI = BinaryOperator::createLShr(
2550 Op0, TC, SI->getName()+".t");
2551 TSI = InsertNewInstBefore(TSI, I);
2552
2553 // Construct the "on false" case of the select
2554 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
2555 Instruction *FSI = BinaryOperator::createLShr(
2556 Op0, FC, SI->getName()+".f");
2557 FSI = InsertNewInstBefore(FSI, I);
Reid Spencer1628cec2006-10-26 06:15:43 +00002558
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002559 // construct the select instruction and return it.
2560 return new SelectInst(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00002561 }
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002562 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002563 return 0;
2564}
2565
Reid Spencer1628cec2006-10-26 06:15:43 +00002566Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2567 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2568
2569 // Handle the integer div common cases
2570 if (Instruction *Common = commonIDivTransforms(I))
2571 return Common;
2572
2573 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2574 // sdiv X, -1 == -X
2575 if (RHS->isAllOnesValue())
2576 return BinaryOperator::createNeg(Op0);
2577
2578 // -X/C -> X/-C
2579 if (Value *LHSNeg = dyn_castNegVal(Op0))
2580 return BinaryOperator::createSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2581 }
2582
2583 // If the sign bits of both operands are zero (i.e. we can prove they are
2584 // unsigned inputs), turn this into a udiv.
Chris Lattner42a75512007-01-15 02:27:26 +00002585 if (I.getType()->isInteger()) {
Reid Spencerbca0e382007-03-23 20:05:17 +00002586 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Reid Spencer1628cec2006-10-26 06:15:43 +00002587 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2588 return BinaryOperator::createUDiv(Op0, Op1, I.getName());
2589 }
2590 }
2591
2592 return 0;
2593}
2594
2595Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2596 return commonDivTransforms(I);
2597}
Chris Lattner3f5b8772002-05-06 16:14:14 +00002598
Chris Lattnerdb3f8732006-03-02 06:50:58 +00002599/// GetFactor - If we can prove that the specified value is at least a multiple
2600/// of some factor, return that factor.
2601static Constant *GetFactor(Value *V) {
2602 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2603 return CI;
2604
2605 // Unless we can be tricky, we know this is a multiple of 1.
2606 Constant *Result = ConstantInt::get(V->getType(), 1);
2607
2608 Instruction *I = dyn_cast<Instruction>(V);
2609 if (!I) return Result;
2610
2611 if (I->getOpcode() == Instruction::Mul) {
2612 // Handle multiplies by a constant, etc.
2613 return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
2614 GetFactor(I->getOperand(1)));
2615 } else if (I->getOpcode() == Instruction::Shl) {
2616 // (X<<C) -> X * (1 << C)
2617 if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
2618 ShRHS = ConstantExpr::getShl(Result, ShRHS);
2619 return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
2620 }
2621 } else if (I->getOpcode() == Instruction::And) {
2622 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
2623 // X & 0xFFF0 is known to be a multiple of 16.
Reid Spencerf2442522007-03-24 00:42:08 +00002624 uint32_t Zeros = RHS->getValue().countTrailingZeros();
Chris Lattnerdb3f8732006-03-02 06:50:58 +00002625 if (Zeros != V->getType()->getPrimitiveSizeInBits())
2626 return ConstantExpr::getShl(Result,
Reid Spencer832254e2007-02-02 02:16:23 +00002627 ConstantInt::get(Result->getType(), Zeros));
Chris Lattnerdb3f8732006-03-02 06:50:58 +00002628 }
Reid Spencer3da59db2006-11-27 01:05:10 +00002629 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
Chris Lattnerdb3f8732006-03-02 06:50:58 +00002630 // Only handle int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00002631 if (!CI->isIntegerCast())
2632 return Result;
2633 Value *Op = CI->getOperand(0);
2634 return ConstantExpr::getCast(CI->getOpcode(), GetFactor(Op), V->getType());
Chris Lattnerdb3f8732006-03-02 06:50:58 +00002635 }
2636 return Result;
2637}
2638
Reid Spencer0a783f72006-11-02 01:53:59 +00002639/// This function implements the transforms on rem instructions that work
2640/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
2641/// is used by the visitors to those instructions.
2642/// @brief Transforms common to all three rem instructions
2643Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002644 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer0a783f72006-11-02 01:53:59 +00002645
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002646 // 0 % X == 0, we don't need to preserve faults!
2647 if (Constant *LHS = dyn_cast<Constant>(Op0))
2648 if (LHS->isNullValue())
2649 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2650
2651 if (isa<UndefValue>(Op0)) // undef % X -> 0
2652 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2653 if (isa<UndefValue>(Op1))
2654 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer0a783f72006-11-02 01:53:59 +00002655
2656 // Handle cases involving: rem X, (select Cond, Y, Z)
2657 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2658 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
2659 // the same basic block, then we replace the select with Y, and the
2660 // condition of the select with false (if the cond value is in the same
2661 // BB). If the select has uses other than the div, this allows them to be
2662 // simplified also.
2663 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2664 if (ST->isNullValue()) {
2665 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2666 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002667 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Reid Spencer0a783f72006-11-02 01:53:59 +00002668 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2669 I.setOperand(1, SI->getOperand(2));
2670 else
2671 UpdateValueUsesWith(SI, SI->getOperand(2));
Chris Lattner5b73c082004-07-06 07:01:22 +00002672 return &I;
2673 }
Reid Spencer0a783f72006-11-02 01:53:59 +00002674 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2675 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2676 if (ST->isNullValue()) {
2677 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2678 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002679 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Reid Spencer0a783f72006-11-02 01:53:59 +00002680 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2681 I.setOperand(1, SI->getOperand(1));
2682 else
2683 UpdateValueUsesWith(SI, SI->getOperand(1));
2684 return &I;
2685 }
Chris Lattner11a49f22005-11-05 07:28:37 +00002686 }
Chris Lattner5b73c082004-07-06 07:01:22 +00002687
Reid Spencer0a783f72006-11-02 01:53:59 +00002688 return 0;
2689}
2690
2691/// This function implements the transforms common to both integer remainder
2692/// instructions (urem and srem). It is called by the visitors to those integer
2693/// remainder instructions.
2694/// @brief Common integer remainder transforms
2695Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2696 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2697
2698 if (Instruction *common = commonRemTransforms(I))
2699 return common;
2700
Chris Lattner857e8cd2004-12-12 21:48:58 +00002701 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002702 // X % 0 == undef, we don't need to preserve faults!
2703 if (RHS->equalsInt(0))
2704 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2705
Chris Lattnera2881962003-02-18 19:28:33 +00002706 if (RHS->equalsInt(1)) // X % 1 == 0
2707 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2708
Chris Lattner97943922006-02-28 05:49:21 +00002709 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2710 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2711 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2712 return R;
2713 } else if (isa<PHINode>(Op0I)) {
2714 if (Instruction *NV = FoldOpIntoPhi(I))
2715 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00002716 }
Reid Spencer0a783f72006-11-02 01:53:59 +00002717 // (X * C1) % C2 --> 0 iff C1 % C2 == 0
2718 if (ConstantExpr::getSRem(GetFactor(Op0I), RHS)->isNullValue())
Chris Lattnerdb3f8732006-03-02 06:50:58 +00002719 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner97943922006-02-28 05:49:21 +00002720 }
Chris Lattnera2881962003-02-18 19:28:33 +00002721 }
2722
Reid Spencer0a783f72006-11-02 01:53:59 +00002723 return 0;
2724}
2725
2726Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2727 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2728
2729 if (Instruction *common = commonIRemTransforms(I))
2730 return common;
2731
2732 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2733 // X urem C^2 -> X and C
2734 // Check to see if this is an unsigned remainder with an exact power of 2,
2735 // if so, convert to a bitwise and.
2736 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencerbca0e382007-03-23 20:05:17 +00002737 if (C->getValue().isPowerOf2())
Reid Spencer0a783f72006-11-02 01:53:59 +00002738 return BinaryOperator::createAnd(Op0, SubOne(C));
2739 }
2740
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002741 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer0a783f72006-11-02 01:53:59 +00002742 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
2743 if (RHSI->getOpcode() == Instruction::Shl &&
2744 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng0fc50952007-03-25 05:01:29 +00002745 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002746 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2747 Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
2748 "tmp"), I);
2749 return BinaryOperator::createAnd(Op0, Add);
2750 }
2751 }
Reid Spencer0a783f72006-11-02 01:53:59 +00002752 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002753
Reid Spencer0a783f72006-11-02 01:53:59 +00002754 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
2755 // where C1&C2 are powers of two.
2756 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2757 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2758 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2759 // STO == 0 and SFO == 0 handled above.
Reid Spencerbca0e382007-03-23 20:05:17 +00002760 if ((STO->getValue().isPowerOf2()) &&
2761 (SFO->getValue().isPowerOf2())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00002762 Value *TrueAnd = InsertNewInstBefore(
2763 BinaryOperator::createAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
2764 Value *FalseAnd = InsertNewInstBefore(
2765 BinaryOperator::createAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
2766 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
2767 }
2768 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002769 }
2770
Chris Lattner3f5b8772002-05-06 16:14:14 +00002771 return 0;
2772}
2773
Reid Spencer0a783f72006-11-02 01:53:59 +00002774Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
2775 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2776
2777 if (Instruction *common = commonIRemTransforms(I))
2778 return common;
2779
2780 if (Value *RHSNeg = dyn_castNegVal(Op1))
2781 if (!isa<ConstantInt>(RHSNeg) ||
Zhou Sheng0fc50952007-03-25 05:01:29 +00002782 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive()) {
Reid Spencer0a783f72006-11-02 01:53:59 +00002783 // X % -Y -> X % Y
2784 AddUsesToWorkList(I);
2785 I.setOperand(1, RHSNeg);
2786 return &I;
2787 }
2788
2789 // If the top bits of both operands are zero (i.e. we can prove they are
2790 // unsigned inputs), turn this into a urem.
Reid Spencerbca0e382007-03-23 20:05:17 +00002791 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Reid Spencer0a783f72006-11-02 01:53:59 +00002792 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2793 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
2794 return BinaryOperator::createURem(Op0, Op1, I.getName());
2795 }
2796
2797 return 0;
2798}
2799
2800Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer0a783f72006-11-02 01:53:59 +00002801 return commonRemTransforms(I);
2802}
2803
Chris Lattner8b170942002-08-09 23:47:40 +00002804// isMaxValueMinusOne - return true if this is Max-1
Reid Spencere4d87aa2006-12-23 06:05:41 +00002805static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
Reid Spencer3a2a9fb2007-03-19 21:10:28 +00002806 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
Reid Spencere4d87aa2006-12-23 06:05:41 +00002807 if (isSigned) {
2808 // Calculate 0111111111..11111
Reid Spencer3a2a9fb2007-03-19 21:10:28 +00002809 APInt Val(APInt::getSignedMaxValue(TypeBits));
2810 return C->getValue() == Val-1;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002811 }
Reid Spencer3a2a9fb2007-03-19 21:10:28 +00002812 return C->getValue() == APInt::getAllOnesValue(TypeBits) - 1;
Chris Lattner8b170942002-08-09 23:47:40 +00002813}
2814
2815// isMinValuePlusOne - return true if this is Min+1
Reid Spencere4d87aa2006-12-23 06:05:41 +00002816static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
2817 if (isSigned) {
2818 // Calculate 1111111111000000000000
Reid Spencer727992c2007-03-19 21:08:07 +00002819 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
2820 APInt Val(APInt::getSignedMinValue(TypeBits));
2821 return C->getValue() == Val+1;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002822 }
Reid Spencer727992c2007-03-19 21:08:07 +00002823 return C->getValue() == 1; // unsigned
Chris Lattner8b170942002-08-09 23:47:40 +00002824}
2825
Chris Lattner457dd822004-06-09 07:59:58 +00002826// isOneBitSet - Return true if there is exactly one bit set in the specified
2827// constant.
2828static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer5f6a8952007-03-20 00:16:52 +00002829 return CI->getValue().isPowerOf2();
Chris Lattner457dd822004-06-09 07:59:58 +00002830}
2831
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00002832// isHighOnes - Return true if the constant is of the form 1+0+.
2833// This is the same as lowones(~X).
2834static bool isHighOnes(const ConstantInt *CI) {
Zhou Sheng2cde46c2007-03-20 12:49:06 +00002835 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00002836}
2837
Reid Spencere4d87aa2006-12-23 06:05:41 +00002838/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002839/// are carefully arranged to allow folding of expressions such as:
2840///
2841/// (A < B) | (A > B) --> (A != B)
2842///
Reid Spencere4d87aa2006-12-23 06:05:41 +00002843/// Note that this is only valid if the first and second predicates have the
2844/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002845///
Reid Spencere4d87aa2006-12-23 06:05:41 +00002846/// Three bits are used to represent the condition, as follows:
2847/// 0 A > B
2848/// 1 A == B
2849/// 2 A < B
2850///
2851/// <=> Value Definition
2852/// 000 0 Always false
2853/// 001 1 A > B
2854/// 010 2 A == B
2855/// 011 3 A >= B
2856/// 100 4 A < B
2857/// 101 5 A != B
2858/// 110 6 A <= B
2859/// 111 7 Always true
2860///
2861static unsigned getICmpCode(const ICmpInst *ICI) {
2862 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002863 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00002864 case ICmpInst::ICMP_UGT: return 1; // 001
2865 case ICmpInst::ICMP_SGT: return 1; // 001
2866 case ICmpInst::ICMP_EQ: return 2; // 010
2867 case ICmpInst::ICMP_UGE: return 3; // 011
2868 case ICmpInst::ICMP_SGE: return 3; // 011
2869 case ICmpInst::ICMP_ULT: return 4; // 100
2870 case ICmpInst::ICMP_SLT: return 4; // 100
2871 case ICmpInst::ICMP_NE: return 5; // 101
2872 case ICmpInst::ICMP_ULE: return 6; // 110
2873 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002874 // True -> 7
2875 default:
Reid Spencere4d87aa2006-12-23 06:05:41 +00002876 assert(0 && "Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002877 return 0;
2878 }
2879}
2880
Reid Spencere4d87aa2006-12-23 06:05:41 +00002881/// getICmpValue - This is the complement of getICmpCode, which turns an
2882/// opcode and two operands into either a constant true or false, or a brand
2883/// new /// ICmp instruction. The sign is passed in to determine which kind
2884/// of predicate to use in new icmp instructions.
2885static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
2886 switch (code) {
2887 default: assert(0 && "Illegal ICmp code!");
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002888 case 0: return ConstantInt::getFalse();
Reid Spencere4d87aa2006-12-23 06:05:41 +00002889 case 1:
2890 if (sign)
2891 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
2892 else
2893 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
2894 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
2895 case 3:
2896 if (sign)
2897 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
2898 else
2899 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
2900 case 4:
2901 if (sign)
2902 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
2903 else
2904 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
2905 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
2906 case 6:
2907 if (sign)
2908 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
2909 else
2910 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002911 case 7: return ConstantInt::getTrue();
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002912 }
2913}
2914
Reid Spencere4d87aa2006-12-23 06:05:41 +00002915static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
2916 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
2917 (ICmpInst::isSignedPredicate(p1) &&
2918 (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
2919 (ICmpInst::isSignedPredicate(p2) &&
2920 (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
2921}
2922
2923namespace {
2924// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
2925struct FoldICmpLogical {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002926 InstCombiner &IC;
2927 Value *LHS, *RHS;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002928 ICmpInst::Predicate pred;
2929 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
2930 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
2931 pred(ICI->getPredicate()) {}
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002932 bool shouldApply(Value *V) const {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002933 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
2934 if (PredicatesFoldable(pred, ICI->getPredicate()))
2935 return (ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS ||
2936 ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002937 return false;
2938 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00002939 Instruction *apply(Instruction &Log) const {
2940 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
2941 if (ICI->getOperand(0) != LHS) {
2942 assert(ICI->getOperand(1) == LHS);
2943 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002944 }
2945
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00002946 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00002947 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00002948 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002949 unsigned Code;
2950 switch (Log.getOpcode()) {
2951 case Instruction::And: Code = LHSCode & RHSCode; break;
2952 case Instruction::Or: Code = LHSCode | RHSCode; break;
2953 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner021c1902003-09-22 20:33:34 +00002954 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002955 }
2956
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00002957 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
2958 ICmpInst::isSignedPredicate(ICI->getPredicate());
2959
2960 Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002961 if (Instruction *I = dyn_cast<Instruction>(RV))
2962 return I;
2963 // Otherwise, it's a constant boolean value...
2964 return IC.ReplaceInstUsesWith(Log, RV);
2965 }
2966};
Chris Lattnerd23b5ba2006-11-15 04:53:24 +00002967} // end anonymous namespace
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002968
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002969// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
2970// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +00002971// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002972Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002973 ConstantInt *OpRHS,
2974 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002975 BinaryOperator &TheAnd) {
2976 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00002977 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +00002978 if (!Op->isShift())
Reid Spencer7177c3a2007-03-25 05:33:51 +00002979 Together = And(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00002980
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002981 switch (Op->getOpcode()) {
2982 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00002983 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002984 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Chris Lattner6934a042007-02-11 01:23:03 +00002985 Instruction *And = BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002986 InsertNewInstBefore(And, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00002987 And->takeName(Op);
Chris Lattner48595f12004-06-10 02:07:29 +00002988 return BinaryOperator::createXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002989 }
2990 break;
2991 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00002992 if (Together == AndRHS) // (X | C) & C --> C
2993 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00002994
Chris Lattner6e7ba452005-01-01 16:22:27 +00002995 if (Op->hasOneUse() && Together != OpRHS) {
2996 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Chris Lattner6934a042007-02-11 01:23:03 +00002997 Instruction *Or = BinaryOperator::createOr(X, Together);
Chris Lattner6e7ba452005-01-01 16:22:27 +00002998 InsertNewInstBefore(Or, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00002999 Or->takeName(Op);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003000 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003001 }
3002 break;
3003 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00003004 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003005 // Adding a one to a single bit bit-field should be turned into an XOR
3006 // of the bit. First thing to check is to see if this AND is with a
3007 // single bit constant.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003008 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003009
3010 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00003011 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003012 // Ok, at this point, we know that we are masking the result of the
3013 // ADD down to exactly one bit. If the constant we are adding has
3014 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003015 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00003016
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003017 // Check to see if any bits below the one bit set in AndRHSV are set.
3018 if ((AddRHS & (AndRHSV-1)) == 0) {
3019 // If not, the only thing that can effect the output of the AND is
3020 // the bit specified by AndRHSV. If that bit is set, the effect of
3021 // the XOR is to toggle the bit. If it is clear, then the ADD has
3022 // no effect.
3023 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3024 TheAnd.setOperand(0, X);
3025 return &TheAnd;
3026 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003027 // Pull the XOR out of the AND.
Chris Lattner6934a042007-02-11 01:23:03 +00003028 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003029 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003030 NewAnd->takeName(Op);
Chris Lattner48595f12004-06-10 02:07:29 +00003031 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003032 }
3033 }
3034 }
3035 }
3036 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00003037
3038 case Instruction::Shl: {
3039 // We know that the AND will not produce any of the bits shifted in, so if
3040 // the anded constant includes them, clear them now!
3041 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003042 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003043 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003044 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3045 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00003046
Zhou Sheng290bec52007-03-29 08:15:12 +00003047 if (CI->getValue() == ShlMask) {
3048 // Masking out bits that the shift already masks
Chris Lattner0c967662004-09-24 15:21:34 +00003049 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3050 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00003051 TheAnd.setOperand(1, CI);
3052 return &TheAnd;
3053 }
3054 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00003055 }
Reid Spencer3822ff52006-11-08 06:47:33 +00003056 case Instruction::LShr:
3057 {
Chris Lattner62a355c2003-09-19 19:05:02 +00003058 // We know that the AND will not produce any of the bits shifted in, so if
3059 // the anded constant includes them, clear them now! This only applies to
3060 // unsigned shifts, because a signed shr may bring in set bits!
3061 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003062 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003063 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003064 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3065 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00003066
Zhou Sheng290bec52007-03-29 08:15:12 +00003067 if (CI->getValue() == ShrMask) {
3068 // Masking out bits that the shift already masks.
Reid Spencer3822ff52006-11-08 06:47:33 +00003069 return ReplaceInstUsesWith(TheAnd, Op);
3070 } else if (CI != AndRHS) {
3071 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3072 return &TheAnd;
3073 }
3074 break;
3075 }
3076 case Instruction::AShr:
3077 // Signed shr.
3078 // See if this is shifting in some sign extension, then masking it out
3079 // with an and.
3080 if (Op->hasOneUse()) {
Zhou Sheng290bec52007-03-29 08:15:12 +00003081 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003082 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003083 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3084 Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
Reid Spencer7eb76382006-12-13 17:19:09 +00003085 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +00003086 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +00003087 // Make the argument unsigned.
3088 Value *ShVal = Op->getOperand(0);
Reid Spencer832254e2007-02-02 02:16:23 +00003089 ShVal = InsertNewInstBefore(
Reid Spencercc46cdb2007-02-02 14:08:20 +00003090 BinaryOperator::createLShr(ShVal, OpRHS,
Reid Spencer832254e2007-02-02 02:16:23 +00003091 Op->getName()), TheAnd);
Reid Spencer7eb76382006-12-13 17:19:09 +00003092 return BinaryOperator::createAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00003093 }
Chris Lattner62a355c2003-09-19 19:05:02 +00003094 }
3095 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003096 }
3097 return 0;
3098}
3099
Chris Lattner8b170942002-08-09 23:47:40 +00003100
Chris Lattnera96879a2004-09-29 17:40:11 +00003101/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3102/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +00003103/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3104/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +00003105/// insert new instructions.
3106Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003107 bool isSigned, bool Inside,
3108 Instruction &IB) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003109 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +00003110 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +00003111 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003112
Chris Lattnera96879a2004-09-29 17:40:11 +00003113 if (Inside) {
3114 if (Lo == Hi) // Trivially false.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003115 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +00003116
Reid Spencere4d87aa2006-12-23 06:05:41 +00003117 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003118 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4e40032007-03-21 23:19:50 +00003119 ICmpInst::Predicate pred = (isSigned ?
Reid Spencere4d87aa2006-12-23 06:05:41 +00003120 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3121 return new ICmpInst(pred, V, Hi);
3122 }
3123
3124 // Emit V-Lo <u Hi-Lo
3125 Constant *NegLo = ConstantExpr::getNeg(Lo);
3126 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003127 InsertNewInstBefore(Add, IB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003128 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3129 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003130 }
3131
3132 if (Lo == Hi) // Trivially true.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003133 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +00003134
Reid Spencere4e40032007-03-21 23:19:50 +00003135 // V < Min || V >= Hi -> V > Hi-1
Chris Lattnera96879a2004-09-29 17:40:11 +00003136 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003137 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003138 ICmpInst::Predicate pred = (isSigned ?
3139 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3140 return new ICmpInst(pred, V, Hi);
3141 }
Reid Spencerb83eb642006-10-20 07:07:24 +00003142
Reid Spencere4e40032007-03-21 23:19:50 +00003143 // Emit V-Lo >u Hi-1-Lo
3144 // Note that Hi has already had one subtracted from it, above.
3145 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003146 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003147 InsertNewInstBefore(Add, IB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003148 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3149 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003150}
3151
Chris Lattner7203e152005-09-18 07:22:02 +00003152// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3153// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3154// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3155// not, since all 1s are not contiguous.
Zhou Sheng4351c642007-04-02 08:20:41 +00003156static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003157 const APInt& V = Val->getValue();
Reid Spencerf2442522007-03-24 00:42:08 +00003158 uint32_t BitWidth = Val->getType()->getBitWidth();
3159 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattner7203e152005-09-18 07:22:02 +00003160
3161 // look for the first zero bit after the run of ones
Reid Spencerf2442522007-03-24 00:42:08 +00003162 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattner7203e152005-09-18 07:22:02 +00003163 // look for the first non-zero bit
Reid Spencerf2442522007-03-24 00:42:08 +00003164 ME = V.getActiveBits();
Chris Lattner7203e152005-09-18 07:22:02 +00003165 return true;
3166}
3167
Chris Lattner7203e152005-09-18 07:22:02 +00003168/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3169/// where isSub determines whether the operator is a sub. If we can fold one of
3170/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00003171///
3172/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3173/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3174/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3175///
3176/// return (A +/- B).
3177///
3178Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003179 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +00003180 Instruction &I) {
3181 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3182 if (!LHSI || LHSI->getNumOperands() != 2 ||
3183 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3184
3185 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3186
3187 switch (LHSI->getOpcode()) {
3188 default: return 0;
3189 case Instruction::And:
Reid Spencer7177c3a2007-03-25 05:33:51 +00003190 if (And(N, Mask) == Mask) {
Chris Lattner7203e152005-09-18 07:22:02 +00003191 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Sheng00f436c2007-03-24 15:34:37 +00003192 if ((Mask->getValue().countLeadingZeros() +
3193 Mask->getValue().countPopulation()) ==
3194 Mask->getValue().getBitWidth())
Chris Lattner7203e152005-09-18 07:22:02 +00003195 break;
3196
3197 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3198 // part, we don't need any explicit masks to take them out of A. If that
3199 // is all N is, ignore it.
Zhou Sheng4351c642007-04-02 08:20:41 +00003200 uint32_t MB = 0, ME = 0;
Chris Lattner7203e152005-09-18 07:22:02 +00003201 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerb35ae032007-03-23 18:46:34 +00003202 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Sheng290bec52007-03-29 08:15:12 +00003203 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattner3bedbd92006-02-07 07:27:52 +00003204 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00003205 break;
3206 }
3207 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00003208 return 0;
3209 case Instruction::Or:
3210 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00003211 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Sheng00f436c2007-03-24 15:34:37 +00003212 if ((Mask->getValue().countLeadingZeros() +
3213 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Reid Spencer6eb0d992007-03-26 23:58:26 +00003214 && And(N, Mask)->isZero())
Chris Lattnerc8e77562005-09-18 04:24:45 +00003215 break;
3216 return 0;
3217 }
3218
3219 Instruction *New;
3220 if (isSub)
3221 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
3222 else
3223 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
3224 return InsertNewInstBefore(New, I);
3225}
3226
Chris Lattner7e708292002-06-25 16:13:24 +00003227Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003228 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00003229 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003230
Chris Lattnere87597f2004-10-16 18:11:37 +00003231 if (isa<UndefValue>(Op1)) // X & undef -> 0
3232 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3233
Chris Lattner6e7ba452005-01-01 16:22:27 +00003234 // and X, X = X
3235 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00003236 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003237
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003238 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00003239 // purpose is to compute bits we don't care about.
Reid Spencer9d6565a2007-02-15 02:26:10 +00003240 if (!isa<VectorType>(I.getType())) {
Reid Spencera03d45f2007-03-22 22:19:58 +00003241 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3242 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3243 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
Chris Lattner696ee0a2007-01-18 22:16:33 +00003244 KnownZero, KnownOne))
Reid Spencer6eb0d992007-03-26 23:58:26 +00003245 return &I;
Chris Lattner696ee0a2007-01-18 22:16:33 +00003246 } else {
Reid Spencer9d6565a2007-02-15 02:26:10 +00003247 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
Chris Lattner041a6c92007-06-15 05:26:55 +00003248 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
Chris Lattner696ee0a2007-01-18 22:16:33 +00003249 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner041a6c92007-06-15 05:26:55 +00003250 } else if (isa<ConstantAggregateZero>(Op1)) {
3251 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
Chris Lattner696ee0a2007-01-18 22:16:33 +00003252 }
3253 }
Chris Lattner9ca96412006-02-08 03:25:32 +00003254
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003255 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003256 const APInt& AndRHSMask = AndRHS->getValue();
3257 APInt NotAndRHS(~AndRHSMask);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003258
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003259 // Optimize a variety of ((val OP C1) & C2) combinations...
Reid Spencer832254e2007-02-02 02:16:23 +00003260 if (isa<BinaryOperator>(Op0)) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003261 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003262 Value *Op0LHS = Op0I->getOperand(0);
3263 Value *Op0RHS = Op0I->getOperand(1);
3264 switch (Op0I->getOpcode()) {
3265 case Instruction::Xor:
3266 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00003267 // If the mask is only needed on one incoming arm, push it up.
3268 if (Op0I->hasOneUse()) {
3269 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3270 // Not masking anything out for the LHS, move to RHS.
3271 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
3272 Op0RHS->getName()+".masked");
3273 InsertNewInstBefore(NewRHS, I);
3274 return BinaryOperator::create(
3275 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003276 }
Chris Lattner3bedbd92006-02-07 07:27:52 +00003277 if (!isa<Constant>(Op0RHS) &&
Chris Lattnerad1e3022005-01-23 20:26:55 +00003278 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3279 // Not masking anything out for the RHS, move to LHS.
3280 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
3281 Op0LHS->getName()+".masked");
3282 InsertNewInstBefore(NewLHS, I);
3283 return BinaryOperator::create(
3284 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3285 }
3286 }
3287
Chris Lattner6e7ba452005-01-01 16:22:27 +00003288 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00003289 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00003290 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3291 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3292 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3293 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3294 return BinaryOperator::createAnd(V, AndRHS);
3295 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3296 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00003297 break;
3298
3299 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00003300 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3301 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3302 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3303 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3304 return BinaryOperator::createAnd(V, AndRHS);
Chris Lattnerc8e77562005-09-18 04:24:45 +00003305 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00003306 }
3307
Chris Lattner58403262003-07-23 19:25:52 +00003308 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003309 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003310 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00003311 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00003312 // If this is an integer truncation or change from signed-to-unsigned, and
3313 // if the source is an and/or with immediate, transform it. This
3314 // frequently occurs for bitfield accesses.
3315 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00003316 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00003317 CastOp->getNumOperands() == 2)
Chris Lattner7560c3a2006-02-08 07:34:50 +00003318 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
Chris Lattner2b83af22005-08-07 07:03:10 +00003319 if (CastOp->getOpcode() == Instruction::And) {
3320 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00003321 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
3322 // This will fold the two constants together, which may allow
3323 // other simplifications.
Reid Spencerd977d862006-12-12 23:36:14 +00003324 Instruction *NewCast = CastInst::createTruncOrBitCast(
3325 CastOp->getOperand(0), I.getType(),
3326 CastOp->getName()+".shrunk");
Chris Lattner2b83af22005-08-07 07:03:10 +00003327 NewCast = InsertNewInstBefore(NewCast, I);
Reid Spencer3da59db2006-11-27 01:05:10 +00003328 // trunc_or_bitcast(C1)&C2
Reid Spencerd977d862006-12-12 23:36:14 +00003329 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00003330 C3 = ConstantExpr::getAnd(C3, AndRHS);
Chris Lattner2b83af22005-08-07 07:03:10 +00003331 return BinaryOperator::createAnd(NewCast, C3);
3332 } else if (CastOp->getOpcode() == Instruction::Or) {
3333 // Change: and (cast (or X, C1) to T), C2
3334 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattnerbb4e7b22006-12-12 19:11:20 +00003335 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Chris Lattner2b83af22005-08-07 07:03:10 +00003336 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3337 return ReplaceInstUsesWith(I, AndRHS);
3338 }
3339 }
Chris Lattner06782f82003-07-23 19:36:21 +00003340 }
Chris Lattner2eefe512004-04-09 19:05:30 +00003341
3342 // Try to fold constant and into select arguments.
3343 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003344 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00003345 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00003346 if (isa<PHINode>(Op0))
3347 if (Instruction *NV = FoldOpIntoPhi(I))
3348 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00003349 }
3350
Chris Lattner8d969642003-03-10 23:06:50 +00003351 Value *Op0NotVal = dyn_castNotVal(Op0);
3352 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00003353
Chris Lattner5b62aa72004-06-18 06:07:51 +00003354 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3355 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3356
Misha Brukmancb6267b2004-07-30 12:50:08 +00003357 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00003358 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattner48595f12004-06-10 02:07:29 +00003359 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
3360 I.getName()+".demorgan");
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00003361 InsertNewInstBefore(Or, I);
Chris Lattnera2881962003-02-18 19:28:33 +00003362 return BinaryOperator::createNot(Or);
3363 }
Chris Lattner2082ad92006-02-13 23:07:23 +00003364
3365 {
3366 Value *A = 0, *B = 0;
Chris Lattner2082ad92006-02-13 23:07:23 +00003367 if (match(Op0, m_Or(m_Value(A), m_Value(B))))
3368 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3369 return ReplaceInstUsesWith(I, Op1);
3370 if (match(Op1, m_Or(m_Value(A), m_Value(B))))
3371 if (A == Op0 || B == Op0) // A & (A | ?) --> A
3372 return ReplaceInstUsesWith(I, Op0);
Chris Lattner64daab52006-04-01 08:03:55 +00003373
3374 if (Op0->hasOneUse() &&
3375 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3376 if (A == Op1) { // (A^B)&A -> A&(A^B)
3377 I.swapOperands(); // Simplify below
3378 std::swap(Op0, Op1);
3379 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
3380 cast<BinaryOperator>(Op0)->swapOperands();
3381 I.swapOperands(); // Simplify below
3382 std::swap(Op0, Op1);
3383 }
3384 }
3385 if (Op1->hasOneUse() &&
3386 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3387 if (B == Op0) { // B&(A^B) -> B&(B^A)
3388 cast<BinaryOperator>(Op1)->swapOperands();
3389 std::swap(A, B);
3390 }
3391 if (A == Op0) { // A&(A^B) -> A & ~B
3392 Instruction *NotB = BinaryOperator::createNot(B, "tmp");
3393 InsertNewInstBefore(NotB, I);
3394 return BinaryOperator::createAnd(A, NotB);
3395 }
3396 }
Chris Lattner2082ad92006-02-13 23:07:23 +00003397 }
3398
Reid Spencere4d87aa2006-12-23 06:05:41 +00003399 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3400 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3401 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003402 return R;
3403
Chris Lattner955f3312004-09-28 21:48:02 +00003404 Value *LHSVal, *RHSVal;
3405 ConstantInt *LHSCst, *RHSCst;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003406 ICmpInst::Predicate LHSCC, RHSCC;
3407 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3408 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3409 if (LHSVal == RHSVal && // Found (X icmp C1) & (X icmp C2)
3410 // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3411 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3412 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3413 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3414 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE) {
Chris Lattner955f3312004-09-28 21:48:02 +00003415 // Ensure that the larger constant is on the RHS.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003416 ICmpInst::Predicate GT = ICmpInst::isSignedPredicate(LHSCC) ?
3417 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
3418 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3419 ICmpInst *LHS = cast<ICmpInst>(Op0);
Reid Spencer579dca12007-01-12 04:24:46 +00003420 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
Chris Lattner955f3312004-09-28 21:48:02 +00003421 std::swap(LHS, RHS);
3422 std::swap(LHSCst, RHSCst);
3423 std::swap(LHSCC, RHSCC);
3424 }
3425
Reid Spencere4d87aa2006-12-23 06:05:41 +00003426 // At this point, we know we have have two icmp instructions
Chris Lattner955f3312004-09-28 21:48:02 +00003427 // comparing a value against two constants and and'ing the result
3428 // together. Because of the above check, we know that we only have
Reid Spencere4d87aa2006-12-23 06:05:41 +00003429 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3430 // (from the FoldICmpLogical check above), that the two constants
3431 // are not equal and that the larger constant is on the RHS
Chris Lattner955f3312004-09-28 21:48:02 +00003432 assert(LHSCst != RHSCst && "Compares not folded above?");
3433
3434 switch (LHSCC) {
3435 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003436 case ICmpInst::ICMP_EQ:
Chris Lattner955f3312004-09-28 21:48:02 +00003437 switch (RHSCC) {
3438 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003439 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3440 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3441 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003442 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00003443 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3444 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3445 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
Chris Lattner955f3312004-09-28 21:48:02 +00003446 return ReplaceInstUsesWith(I, LHS);
3447 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003448 case ICmpInst::ICMP_NE:
Chris Lattner955f3312004-09-28 21:48:02 +00003449 switch (RHSCC) {
3450 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003451 case ICmpInst::ICMP_ULT:
3452 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3453 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
3454 break; // (X != 13 & X u< 15) -> no change
3455 case ICmpInst::ICMP_SLT:
3456 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3457 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
3458 break; // (X != 13 & X s< 15) -> no change
3459 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3460 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3461 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
Chris Lattner955f3312004-09-28 21:48:02 +00003462 return ReplaceInstUsesWith(I, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003463 case ICmpInst::ICMP_NE:
3464 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Chris Lattner955f3312004-09-28 21:48:02 +00003465 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3466 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3467 LHSVal->getName()+".off");
3468 InsertNewInstBefore(Add, I);
Chris Lattner424db022007-01-27 23:08:34 +00003469 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3470 ConstantInt::get(Add->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +00003471 }
3472 break; // (X != 13 & X != 15) -> no change
3473 }
3474 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003475 case ICmpInst::ICMP_ULT:
Chris Lattner955f3312004-09-28 21:48:02 +00003476 switch (RHSCC) {
3477 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003478 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3479 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003480 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00003481 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3482 break;
3483 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3484 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
Chris Lattner955f3312004-09-28 21:48:02 +00003485 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003486 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3487 break;
Chris Lattner955f3312004-09-28 21:48:02 +00003488 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003489 break;
3490 case ICmpInst::ICMP_SLT:
Chris Lattner955f3312004-09-28 21:48:02 +00003491 switch (RHSCC) {
3492 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003493 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3494 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003495 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00003496 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3497 break;
3498 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3499 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
Chris Lattner955f3312004-09-28 21:48:02 +00003500 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003501 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3502 break;
Chris Lattner955f3312004-09-28 21:48:02 +00003503 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003504 break;
3505 case ICmpInst::ICMP_UGT:
3506 switch (RHSCC) {
3507 default: assert(0 && "Unknown integer condition code!");
3508 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X > 13
3509 return ReplaceInstUsesWith(I, LHS);
3510 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3511 return ReplaceInstUsesWith(I, RHS);
3512 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3513 break;
3514 case ICmpInst::ICMP_NE:
3515 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3516 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3517 break; // (X u> 13 & X != 15) -> no change
3518 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) ->(X-14) <u 1
3519 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false,
3520 true, I);
3521 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3522 break;
3523 }
3524 break;
3525 case ICmpInst::ICMP_SGT:
3526 switch (RHSCC) {
3527 default: assert(0 && "Unknown integer condition code!");
3528 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X s> 13
3529 return ReplaceInstUsesWith(I, LHS);
3530 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3531 return ReplaceInstUsesWith(I, RHS);
3532 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3533 break;
3534 case ICmpInst::ICMP_NE:
3535 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3536 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3537 break; // (X s> 13 & X != 15) -> no change
3538 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) ->(X-14) s< 1
3539 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true,
3540 true, I);
3541 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3542 break;
3543 }
3544 break;
Chris Lattner955f3312004-09-28 21:48:02 +00003545 }
3546 }
3547 }
3548
Chris Lattner6fc205f2006-05-05 06:39:07 +00003549 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003550 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3551 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3552 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3553 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00003554 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003555 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003556 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
3557 I.getType(), TD) &&
3558 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
3559 I.getType(), TD)) {
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003560 Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
3561 Op1C->getOperand(0),
3562 I.getName());
3563 InsertNewInstBefore(NewOp, I);
3564 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3565 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00003566 }
Chris Lattnere511b742006-11-14 07:46:50 +00003567
3568 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00003569 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3570 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3571 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00003572 SI0->getOperand(1) == SI1->getOperand(1) &&
3573 (SI0->hasOneUse() || SI1->hasOneUse())) {
3574 Instruction *NewOp =
3575 InsertNewInstBefore(BinaryOperator::createAnd(SI0->getOperand(0),
3576 SI1->getOperand(0),
3577 SI0->getName()), I);
Reid Spencer832254e2007-02-02 02:16:23 +00003578 return BinaryOperator::create(SI1->getOpcode(), NewOp,
3579 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00003580 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00003581 }
3582
Chris Lattner7e708292002-06-25 16:13:24 +00003583 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00003584}
3585
Chris Lattnerafe91a52006-06-15 19:07:26 +00003586/// CollectBSwapParts - Look to see if the specified value defines a single byte
3587/// in the result. If it does, and if the specified byte hasn't been filled in
3588/// yet, fill it in and return false.
Chris Lattner535014f2007-02-15 22:52:10 +00003589static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00003590 Instruction *I = dyn_cast<Instruction>(V);
3591 if (I == 0) return true;
3592
3593 // If this is an or instruction, it is an inner node of the bswap.
3594 if (I->getOpcode() == Instruction::Or)
3595 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3596 CollectBSwapParts(I->getOperand(1), ByteValues);
3597
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003598 uint32_t BitWidth = I->getType()->getPrimitiveSizeInBits();
Chris Lattnerafe91a52006-06-15 19:07:26 +00003599 // If this is a shift by a constant int, and it is "24", then its operand
3600 // defines a byte. We only handle unsigned types here.
Reid Spencer832254e2007-02-02 02:16:23 +00003601 if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00003602 // Not shifting the entire input by N-1 bytes?
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003603 if (cast<ConstantInt>(I->getOperand(1))->getLimitedValue(BitWidth) !=
Chris Lattnerafe91a52006-06-15 19:07:26 +00003604 8*(ByteValues.size()-1))
3605 return true;
3606
3607 unsigned DestNo;
3608 if (I->getOpcode() == Instruction::Shl) {
3609 // X << 24 defines the top byte with the lowest of the input bytes.
3610 DestNo = ByteValues.size()-1;
3611 } else {
3612 // X >>u 24 defines the low byte with the highest of the input bytes.
3613 DestNo = 0;
3614 }
3615
3616 // If the destination byte value is already defined, the values are or'd
3617 // together, which isn't a bswap (unless it's an or of the same bits).
3618 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3619 return true;
3620 ByteValues[DestNo] = I->getOperand(0);
3621 return false;
3622 }
3623
3624 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
3625 // don't have this.
3626 Value *Shift = 0, *ShiftLHS = 0;
3627 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3628 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3629 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3630 return true;
3631 Instruction *SI = cast<Instruction>(Shift);
3632
3633 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003634 if (ShiftAmt->getLimitedValue(BitWidth) & 7 ||
3635 ShiftAmt->getLimitedValue(BitWidth) > 8*ByteValues.size())
Chris Lattnerafe91a52006-06-15 19:07:26 +00003636 return true;
3637
3638 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3639 unsigned DestByte;
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003640 if (AndAmt->getValue().getActiveBits() > 64)
3641 return true;
3642 uint64_t AndAmtVal = AndAmt->getZExtValue();
Chris Lattnerafe91a52006-06-15 19:07:26 +00003643 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003644 if (AndAmtVal == uint64_t(0xFF) << 8*DestByte)
Chris Lattnerafe91a52006-06-15 19:07:26 +00003645 break;
3646 // Unknown mask for bswap.
3647 if (DestByte == ByteValues.size()) return true;
3648
Reid Spencerb83eb642006-10-20 07:07:24 +00003649 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
Chris Lattnerafe91a52006-06-15 19:07:26 +00003650 unsigned SrcByte;
3651 if (SI->getOpcode() == Instruction::Shl)
3652 SrcByte = DestByte - ShiftBytes;
3653 else
3654 SrcByte = DestByte + ShiftBytes;
3655
3656 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3657 if (SrcByte != ByteValues.size()-DestByte-1)
3658 return true;
3659
3660 // If the destination byte value is already defined, the values are or'd
3661 // together, which isn't a bswap (unless it's an or of the same bits).
3662 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3663 return true;
3664 ByteValues[DestByte] = SI->getOperand(0);
3665 return false;
3666}
3667
3668/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3669/// If so, insert the new bswap intrinsic and return it.
3670Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattner55fc8c42007-04-01 20:57:36 +00003671 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
3672 if (!ITy || ITy->getBitWidth() % 16)
3673 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerafe91a52006-06-15 19:07:26 +00003674
3675 /// ByteValues - For each byte of the result, we keep track of which value
3676 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00003677 SmallVector<Value*, 8> ByteValues;
Chris Lattner55fc8c42007-04-01 20:57:36 +00003678 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerafe91a52006-06-15 19:07:26 +00003679
3680 // Try to find all the pieces corresponding to the bswap.
3681 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3682 CollectBSwapParts(I.getOperand(1), ByteValues))
3683 return 0;
3684
3685 // Check to see if all of the bytes come from the same value.
3686 Value *V = ByteValues[0];
3687 if (V == 0) return 0; // Didn't find a byte? Must be zero.
3688
3689 // Check to make sure that all of the bytes come from the same value.
3690 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3691 if (ByteValues[i] != V)
3692 return 0;
Chris Lattner55fc8c42007-04-01 20:57:36 +00003693 const Type *Tys[] = { ITy, ITy };
Chris Lattnerafe91a52006-06-15 19:07:26 +00003694 Module *M = I.getParent()->getParent()->getParent();
Chris Lattner55fc8c42007-04-01 20:57:36 +00003695 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 2);
Chris Lattnerafe91a52006-06-15 19:07:26 +00003696 return new CallInst(F, V);
3697}
3698
3699
Chris Lattner7e708292002-06-25 16:13:24 +00003700Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003701 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00003702 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003703
Chris Lattner42593e62007-03-24 23:56:43 +00003704 if (isa<UndefValue>(Op1)) // X | undef -> -1
3705 return ReplaceInstUsesWith(I, ConstantInt::getAllOnesValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00003706
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003707 // or X, X = X
3708 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00003709 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003710
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003711 // See if we can simplify any instructions used by the instruction whose sole
3712 // purpose is to compute bits we don't care about.
Chris Lattner42593e62007-03-24 23:56:43 +00003713 if (!isa<VectorType>(I.getType())) {
3714 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3715 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3716 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3717 KnownZero, KnownOne))
3718 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00003719 } else if (isa<ConstantAggregateZero>(Op1)) {
3720 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
3721 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3722 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
3723 return ReplaceInstUsesWith(I, I.getOperand(1));
Chris Lattner42593e62007-03-24 23:56:43 +00003724 }
Chris Lattner041a6c92007-06-15 05:26:55 +00003725
3726
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003727
Chris Lattner3f5b8772002-05-06 16:14:14 +00003728 // or X, -1 == -1
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003729 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00003730 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003731 // (X & C1) | C2 --> (X | C2) & (C1|C2)
3732 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattner6934a042007-02-11 01:23:03 +00003733 Instruction *Or = BinaryOperator::createOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003734 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00003735 Or->takeName(Op0);
Zhou Sheng4a1822a2007-04-02 13:45:30 +00003736 return BinaryOperator::createAnd(Or,
3737 ConstantInt::get(RHS->getValue() | C1->getValue()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003738 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00003739
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003740 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3741 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattner6934a042007-02-11 01:23:03 +00003742 Instruction *Or = BinaryOperator::createOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003743 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00003744 Or->takeName(Op0);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003745 return BinaryOperator::createXor(Or,
Zhou Sheng4a1822a2007-04-02 13:45:30 +00003746 ConstantInt::get(C1->getValue() & ~RHS->getValue()));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00003747 }
Chris Lattner2eefe512004-04-09 19:05:30 +00003748
3749 // Try to fold constant and into select arguments.
3750 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003751 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00003752 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00003753 if (isa<PHINode>(Op0))
3754 if (Instruction *NV = FoldOpIntoPhi(I))
3755 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00003756 }
3757
Chris Lattner4f637d42006-01-06 17:59:59 +00003758 Value *A = 0, *B = 0;
3759 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00003760
3761 if (match(Op0, m_And(m_Value(A), m_Value(B))))
3762 if (A == Op1 || B == Op1) // (A & ?) | A --> A
3763 return ReplaceInstUsesWith(I, Op1);
3764 if (match(Op1, m_And(m_Value(A), m_Value(B))))
3765 if (A == Op0 || B == Op0) // A | (A & ?) --> A
3766 return ReplaceInstUsesWith(I, Op0);
3767
Chris Lattner6423d4c2006-07-10 20:25:24 +00003768 // (A | B) | C and A | (B | C) -> bswap if possible.
3769 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Chris Lattnerafe91a52006-06-15 19:07:26 +00003770 if (match(Op0, m_Or(m_Value(), m_Value())) ||
Chris Lattner6423d4c2006-07-10 20:25:24 +00003771 match(Op1, m_Or(m_Value(), m_Value())) ||
3772 (match(Op0, m_Shift(m_Value(), m_Value())) &&
3773 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00003774 if (Instruction *BSwap = MatchBSwap(I))
3775 return BSwap;
3776 }
3777
Chris Lattner6e4c6492005-05-09 04:58:36 +00003778 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
3779 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00003780 MaskedValueIsZero(Op1, C1->getValue())) {
Chris Lattner6934a042007-02-11 01:23:03 +00003781 Instruction *NOr = BinaryOperator::createOr(A, Op1);
3782 InsertNewInstBefore(NOr, I);
3783 NOr->takeName(Op0);
3784 return BinaryOperator::createXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00003785 }
3786
3787 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
3788 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00003789 MaskedValueIsZero(Op0, C1->getValue())) {
Chris Lattner6934a042007-02-11 01:23:03 +00003790 Instruction *NOr = BinaryOperator::createOr(A, Op0);
3791 InsertNewInstBefore(NOr, I);
3792 NOr->takeName(Op0);
3793 return BinaryOperator::createXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00003794 }
3795
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00003796 // (A & C)|(B & D)
3797 Value *C, *D;
3798 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
3799 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00003800 Value *V1 = 0, *V2 = 0, *V3 = 0;
3801 C1 = dyn_cast<ConstantInt>(C);
3802 C2 = dyn_cast<ConstantInt>(D);
3803 if (C1 && C2) { // (A & C1)|(B & C2)
3804 // If we have: ((V + N) & C1) | (V & C2)
3805 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
3806 // replace with V+N.
3807 if (C1->getValue() == ~C2->getValue()) {
3808 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
3809 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
3810 // Add commutes, try both ways.
3811 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
3812 return ReplaceInstUsesWith(I, A);
3813 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
3814 return ReplaceInstUsesWith(I, A);
3815 }
3816 // Or commutes, try both ways.
3817 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
3818 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
3819 // Add commutes, try both ways.
3820 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
3821 return ReplaceInstUsesWith(I, B);
3822 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
3823 return ReplaceInstUsesWith(I, B);
3824 }
3825 }
Chris Lattner044e5332007-04-08 08:01:49 +00003826 V1 = 0; V2 = 0; V3 = 0;
Chris Lattner6cae0e02007-04-08 07:55:22 +00003827 }
3828
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00003829 // Check to see if we have any common things being and'ed. If so, find the
3830 // terms for V1 & (V2|V3).
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00003831 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
3832 if (A == B) // (A & C)|(A & D) == A & (C|D)
3833 V1 = A, V2 = C, V3 = D;
3834 else if (A == D) // (A & C)|(B & A) == A & (B|C)
3835 V1 = A, V2 = B, V3 = C;
3836 else if (C == B) // (A & C)|(C & D) == C & (A|D)
3837 V1 = C, V2 = A, V3 = D;
3838 else if (C == D) // (A & C)|(B & C) == C & (A|B)
3839 V1 = C, V2 = A, V3 = B;
3840
3841 if (V1) {
3842 Value *Or =
3843 InsertNewInstBefore(BinaryOperator::createOr(V2, V3, "tmp"), I);
3844 return BinaryOperator::createAnd(V1, Or);
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00003845 }
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00003846
3847 // (V1 & V3)|(V2 & ~V3) -> ((V1 ^ V2) & V3) ^ V2
Chris Lattner044e5332007-04-08 08:01:49 +00003848 if (isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00003849 // Try all combination of terms to find V3 and ~V3.
3850 if (A->hasOneUse() && match(A, m_Not(m_Value(V3)))) {
3851 if (V3 == B)
3852 V1 = D, V2 = C;
3853 else if (V3 == D)
3854 V1 = B, V2 = C;
3855 }
3856 if (B->hasOneUse() && match(B, m_Not(m_Value(V3)))) {
3857 if (V3 == A)
3858 V1 = C, V2 = D;
3859 else if (V3 == C)
3860 V1 = A, V2 = D;
3861 }
3862 if (C->hasOneUse() && match(C, m_Not(m_Value(V3)))) {
3863 if (V3 == B)
3864 V1 = D, V2 = A;
3865 else if (V3 == D)
3866 V1 = B, V2 = A;
3867 }
3868 if (D->hasOneUse() && match(D, m_Not(m_Value(V3)))) {
3869 if (V3 == A)
3870 V1 = C, V2 = B;
3871 else if (V3 == C)
3872 V1 = A, V2 = B;
3873 }
3874 if (V1) {
3875 A = InsertNewInstBefore(BinaryOperator::createXor(V1, V2, "tmp"), I);
3876 A = InsertNewInstBefore(BinaryOperator::createAnd(A, V3, "tmp"), I);
3877 return BinaryOperator::createXor(A, V2);
3878 }
3879 }
3880 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00003881 }
Chris Lattnere511b742006-11-14 07:46:50 +00003882
3883 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00003884 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3885 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3886 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00003887 SI0->getOperand(1) == SI1->getOperand(1) &&
3888 (SI0->hasOneUse() || SI1->hasOneUse())) {
3889 Instruction *NewOp =
3890 InsertNewInstBefore(BinaryOperator::createOr(SI0->getOperand(0),
3891 SI1->getOperand(0),
3892 SI0->getName()), I);
Reid Spencer832254e2007-02-02 02:16:23 +00003893 return BinaryOperator::create(SI1->getOpcode(), NewOp,
3894 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00003895 }
3896 }
Chris Lattner67ca7682003-08-12 19:11:07 +00003897
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003898 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
3899 if (A == Op1) // ~A | A == -1
Misha Brukmanfd939082005-04-21 23:48:37 +00003900 return ReplaceInstUsesWith(I,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003901 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003902 } else {
3903 A = 0;
3904 }
Chris Lattnerf4d4c872005-05-07 23:49:08 +00003905 // Note, A is still live here!
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003906 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
3907 if (Op0 == B)
Misha Brukmanfd939082005-04-21 23:48:37 +00003908 return ReplaceInstUsesWith(I,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003909 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattnera27231a2003-03-10 23:13:59 +00003910
Misha Brukmancb6267b2004-07-30 12:50:08 +00003911 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003912 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3913 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
3914 I.getName()+".demorgan"), I);
3915 return BinaryOperator::createNot(And);
3916 }
Chris Lattnera27231a2003-03-10 23:13:59 +00003917 }
Chris Lattnera2881962003-02-18 19:28:33 +00003918
Reid Spencere4d87aa2006-12-23 06:05:41 +00003919 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
3920 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
3921 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003922 return R;
3923
Chris Lattnerb4f40d22004-09-28 22:33:08 +00003924 Value *LHSVal, *RHSVal;
3925 ConstantInt *LHSCst, *RHSCst;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003926 ICmpInst::Predicate LHSCC, RHSCC;
3927 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3928 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3929 if (LHSVal == RHSVal && // Found (X icmp C1) | (X icmp C2)
3930 // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
3931 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3932 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3933 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
Chris Lattner88858872007-05-11 05:55:56 +00003934 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
3935 // We can't fold (ugt x, C) | (sgt x, C2).
3936 PredicatesFoldable(LHSCC, RHSCC)) {
Chris Lattnerb4f40d22004-09-28 22:33:08 +00003937 // Ensure that the larger constant is on the RHS.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003938 ICmpInst *LHS = cast<ICmpInst>(Op0);
Chris Lattner88858872007-05-11 05:55:56 +00003939 bool NeedsSwap;
3940 if (ICmpInst::isSignedPredicate(LHSCC))
Chris Lattner3aea1bd2007-05-11 16:58:45 +00003941 NeedsSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner88858872007-05-11 05:55:56 +00003942 else
Chris Lattner3aea1bd2007-05-11 16:58:45 +00003943 NeedsSwap = LHSCst->getValue().ugt(RHSCst->getValue());
Chris Lattner88858872007-05-11 05:55:56 +00003944
3945 if (NeedsSwap) {
Chris Lattnerb4f40d22004-09-28 22:33:08 +00003946 std::swap(LHS, RHS);
3947 std::swap(LHSCst, RHSCst);
3948 std::swap(LHSCC, RHSCC);
3949 }
3950
Reid Spencere4d87aa2006-12-23 06:05:41 +00003951 // At this point, we know we have have two icmp instructions
Chris Lattnerb4f40d22004-09-28 22:33:08 +00003952 // comparing a value against two constants and or'ing the result
3953 // together. Because of the above check, we know that we only have
Reid Spencere4d87aa2006-12-23 06:05:41 +00003954 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
3955 // FoldICmpLogical check above), that the two constants are not
Chris Lattnerb4f40d22004-09-28 22:33:08 +00003956 // equal.
3957 assert(LHSCst != RHSCst && "Compares not folded above?");
3958
3959 switch (LHSCC) {
3960 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003961 case ICmpInst::ICMP_EQ:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00003962 switch (RHSCC) {
3963 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003964 case ICmpInst::ICMP_EQ:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00003965 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
3966 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3967 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3968 LHSVal->getName()+".off");
3969 InsertNewInstBefore(Add, I);
Zhou Sheng4a1822a2007-04-02 13:45:30 +00003970 AddCST = Subtract(AddOne(RHSCst), LHSCst);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003971 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattnerb4f40d22004-09-28 22:33:08 +00003972 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003973 break; // (X == 13 | X == 15) -> no change
3974 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
3975 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
Chris Lattner240d6f42005-04-19 06:04:18 +00003976 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003977 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
3978 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
3979 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
Chris Lattnerb4f40d22004-09-28 22:33:08 +00003980 return ReplaceInstUsesWith(I, RHS);
3981 }
3982 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003983 case ICmpInst::ICMP_NE:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00003984 switch (RHSCC) {
3985 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003986 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
3987 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
3988 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
Chris Lattnerb4f40d22004-09-28 22:33:08 +00003989 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003990 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
3991 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
3992 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003993 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnerb4f40d22004-09-28 22:33:08 +00003994 }
3995 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003996 case ICmpInst::ICMP_ULT:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00003997 switch (RHSCC) {
3998 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003999 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004000 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004001 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) ->(X-13) u> 2
4002 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false,
4003 false, I);
4004 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4005 break;
4006 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4007 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004008 return ReplaceInstUsesWith(I, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004009 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4010 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004011 }
4012 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004013 case ICmpInst::ICMP_SLT:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004014 switch (RHSCC) {
4015 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004016 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4017 break;
4018 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) ->(X-13) s> 2
4019 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true,
4020 false, I);
4021 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4022 break;
4023 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4024 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4025 return ReplaceInstUsesWith(I, RHS);
4026 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4027 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004028 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004029 break;
4030 case ICmpInst::ICMP_UGT:
4031 switch (RHSCC) {
4032 default: assert(0 && "Unknown integer condition code!");
4033 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4034 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4035 return ReplaceInstUsesWith(I, LHS);
4036 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4037 break;
4038 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4039 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004040 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004041 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4042 break;
4043 }
4044 break;
4045 case ICmpInst::ICMP_SGT:
4046 switch (RHSCC) {
4047 default: assert(0 && "Unknown integer condition code!");
4048 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4049 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4050 return ReplaceInstUsesWith(I, LHS);
4051 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4052 break;
4053 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4054 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004055 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004056 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4057 break;
4058 }
4059 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004060 }
4061 }
4062 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004063
4064 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004065 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
Chris Lattner6fc205f2006-05-05 06:39:07 +00004066 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004067 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4068 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00004069 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004070 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004071 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4072 I.getType(), TD) &&
4073 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4074 I.getType(), TD)) {
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004075 Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
4076 Op1C->getOperand(0),
4077 I.getName());
4078 InsertNewInstBefore(NewOp, I);
4079 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4080 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004081 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004082
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004083
Chris Lattner7e708292002-06-25 16:13:24 +00004084 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004085}
4086
Chris Lattnerc317d392004-02-16 01:20:27 +00004087// XorSelf - Implements: X ^ X --> 0
4088struct XorSelf {
4089 Value *RHS;
4090 XorSelf(Value *rhs) : RHS(rhs) {}
4091 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4092 Instruction *apply(BinaryOperator &Xor) const {
4093 return &Xor;
4094 }
4095};
Chris Lattner3f5b8772002-05-06 16:14:14 +00004096
4097
Chris Lattner7e708292002-06-25 16:13:24 +00004098Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004099 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004100 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004101
Chris Lattnere87597f2004-10-16 18:11:37 +00004102 if (isa<UndefValue>(Op1))
4103 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
4104
Chris Lattnerc317d392004-02-16 01:20:27 +00004105 // xor X, X = 0, even if X is nested in a sequence of Xor's.
4106 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
4107 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattner233f7dc2002-08-12 21:17:25 +00004108 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00004109 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004110
4111 // See if we can simplify any instructions used by the instruction whose sole
4112 // purpose is to compute bits we don't care about.
Reid Spencera03d45f2007-03-22 22:19:58 +00004113 if (!isa<VectorType>(I.getType())) {
4114 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4115 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4116 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4117 KnownZero, KnownOne))
4118 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00004119 } else if (isa<ConstantAggregateZero>(Op1)) {
4120 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Reid Spencera03d45f2007-03-22 22:19:58 +00004121 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00004122
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004123 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00004124 // xor (icmp A, B), true = not (icmp A, B) = !icmp A, B
4125 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004126 if (RHS == ConstantInt::getTrue() && ICI->hasOneUse())
Reid Spencere4d87aa2006-12-23 06:05:41 +00004127 return new ICmpInst(ICI->getInversePredicate(),
4128 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00004129
Reid Spencere4d87aa2006-12-23 06:05:41 +00004130 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00004131 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00004132 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4133 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattner48595f12004-06-10 02:07:29 +00004134 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4135 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattner7c4049c2004-01-12 19:35:11 +00004136 ConstantInt::get(I.getType(), 1));
Chris Lattner48595f12004-06-10 02:07:29 +00004137 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00004138 }
Chris Lattner5b62aa72004-06-18 06:07:51 +00004139
4140 // ~(~X & Y) --> (X | ~Y)
4141 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
4142 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4143 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4144 Instruction *NotY =
Misha Brukmanfd939082005-04-21 23:48:37 +00004145 BinaryOperator::createNot(Op0I->getOperand(1),
Chris Lattner5b62aa72004-06-18 06:07:51 +00004146 Op0I->getOperand(1)->getName()+".not");
4147 InsertNewInstBefore(NotY, I);
4148 return BinaryOperator::createOr(Op0NotVal, NotY);
4149 }
4150 }
Chris Lattner5c6e2db2007-04-02 05:36:22 +00004151
Chris Lattnereca0c5c2003-07-23 21:37:07 +00004152 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004153 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00004154 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00004155 if (RHS->isAllOnesValue()) {
Chris Lattner48595f12004-06-10 02:07:29 +00004156 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
4157 return BinaryOperator::createSub(
4158 ConstantExpr::getSub(NegOp0CI,
Chris Lattner7c4049c2004-01-12 19:35:11 +00004159 ConstantInt::get(I.getType(), 1)),
Chris Lattner689d24b2003-11-04 23:37:10 +00004160 Op0I->getOperand(0));
Chris Lattneracf4e072007-04-02 05:42:22 +00004161 } else if (RHS->getValue().isSignBit()) {
Chris Lattner5c6e2db2007-04-02 05:36:22 +00004162 // (X + C) ^ signbit -> (X + C + signbit)
4163 Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
4164 return BinaryOperator::createAdd(Op0I->getOperand(0), C);
Chris Lattnercd1d6d52007-04-02 05:48:58 +00004165
Chris Lattner7c4049c2004-01-12 19:35:11 +00004166 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00004167 } else if (Op0I->getOpcode() == Instruction::Or) {
4168 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencera03d45f2007-03-22 22:19:58 +00004169 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Chris Lattner02bd1b32006-02-26 19:57:54 +00004170 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4171 // Anything in both C1 and C2 is known to be zero, remove it from
4172 // NewRHS.
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004173 Constant *CommonBits = And(Op0CI, RHS);
Chris Lattner02bd1b32006-02-26 19:57:54 +00004174 NewRHS = ConstantExpr::getAnd(NewRHS,
4175 ConstantExpr::getNot(CommonBits));
Chris Lattnerdbab3862007-03-02 21:28:56 +00004176 AddToWorkList(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00004177 I.setOperand(0, Op0I->getOperand(0));
4178 I.setOperand(1, NewRHS);
4179 return &I;
4180 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00004181 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00004182 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004183
4184 // Try to fold constant and into select arguments.
4185 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004186 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004187 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004188 if (isa<PHINode>(Op0))
4189 if (Instruction *NV = FoldOpIntoPhi(I))
4190 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004191 }
4192
Chris Lattner8d969642003-03-10 23:06:50 +00004193 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00004194 if (X == Op1)
4195 return ReplaceInstUsesWith(I,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004196 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00004197
Chris Lattner8d969642003-03-10 23:06:50 +00004198 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00004199 if (X == Op0)
Chris Lattner318bf792007-03-18 22:51:34 +00004200 return ReplaceInstUsesWith(I, ConstantInt::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00004201
Chris Lattner318bf792007-03-18 22:51:34 +00004202
4203 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
4204 if (Op1I) {
4205 Value *A, *B;
4206 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
4207 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00004208 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00004209 I.swapOperands();
4210 std::swap(Op0, Op1);
Chris Lattner318bf792007-03-18 22:51:34 +00004211 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00004212 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00004213 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00004214 }
Chris Lattner318bf792007-03-18 22:51:34 +00004215 } else if (match(Op1I, m_Xor(m_Value(A), m_Value(B)))) {
4216 if (Op0 == A) // A^(A^B) == B
4217 return ReplaceInstUsesWith(I, B);
4218 else if (Op0 == B) // A^(B^A) == B
4219 return ReplaceInstUsesWith(I, A);
4220 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
Chris Lattner6abbdf92007-04-01 05:36:37 +00004221 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattner64daab52006-04-01 08:03:55 +00004222 Op1I->swapOperands();
Chris Lattner6abbdf92007-04-01 05:36:37 +00004223 std::swap(A, B);
4224 }
Chris Lattner318bf792007-03-18 22:51:34 +00004225 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattner64daab52006-04-01 08:03:55 +00004226 I.swapOperands(); // Simplified below.
4227 std::swap(Op0, Op1);
4228 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00004229 }
Chris Lattner318bf792007-03-18 22:51:34 +00004230 }
4231
4232 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
4233 if (Op0I) {
4234 Value *A, *B;
4235 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
4236 if (A == Op1) // (B|A)^B == (A|B)^B
4237 std::swap(A, B);
4238 if (B == Op1) { // (A|B)^B == A & ~B
4239 Instruction *NotB =
4240 InsertNewInstBefore(BinaryOperator::createNot(Op1, "tmp"), I);
4241 return BinaryOperator::createAnd(A, NotB);
Chris Lattnercb40a372003-03-10 18:24:17 +00004242 }
Chris Lattner318bf792007-03-18 22:51:34 +00004243 } else if (match(Op0I, m_Xor(m_Value(A), m_Value(B)))) {
4244 if (Op1 == A) // (A^B)^A == B
4245 return ReplaceInstUsesWith(I, B);
4246 else if (Op1 == B) // (B^A)^A == B
4247 return ReplaceInstUsesWith(I, A);
4248 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
4249 if (A == Op1) // (A&B)^A -> (B&A)^A
4250 std::swap(A, B);
4251 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattnerae1ab392006-04-01 22:05:01 +00004252 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner318bf792007-03-18 22:51:34 +00004253 Instruction *N =
4254 InsertNewInstBefore(BinaryOperator::createNot(A, "tmp"), I);
Chris Lattner64daab52006-04-01 08:03:55 +00004255 return BinaryOperator::createAnd(N, Op1);
4256 }
Chris Lattnercb40a372003-03-10 18:24:17 +00004257 }
Chris Lattner318bf792007-03-18 22:51:34 +00004258 }
4259
4260 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
4261 if (Op0I && Op1I && Op0I->isShift() &&
4262 Op0I->getOpcode() == Op1I->getOpcode() &&
4263 Op0I->getOperand(1) == Op1I->getOperand(1) &&
4264 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
4265 Instruction *NewOp =
4266 InsertNewInstBefore(BinaryOperator::createXor(Op0I->getOperand(0),
4267 Op1I->getOperand(0),
4268 Op0I->getName()), I);
4269 return BinaryOperator::create(Op1I->getOpcode(), NewOp,
4270 Op1I->getOperand(1));
4271 }
4272
4273 if (Op0I && Op1I) {
4274 Value *A, *B, *C, *D;
4275 // (A & B)^(A | B) -> A ^ B
4276 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4277 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
4278 if ((A == C && B == D) || (A == D && B == C))
4279 return BinaryOperator::createXor(A, B);
4280 }
4281 // (A | B)^(A & B) -> A ^ B
4282 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
4283 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4284 if ((A == C && B == D) || (A == D && B == C))
4285 return BinaryOperator::createXor(A, B);
4286 }
4287
4288 // (A & B)^(C & D)
4289 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
4290 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4291 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4292 // (X & Y)^(X & Y) -> (Y^Z) & X
4293 Value *X = 0, *Y = 0, *Z = 0;
4294 if (A == C)
4295 X = A, Y = B, Z = D;
4296 else if (A == D)
4297 X = A, Y = B, Z = C;
4298 else if (B == C)
4299 X = B, Y = A, Z = D;
4300 else if (B == D)
4301 X = B, Y = A, Z = C;
4302
4303 if (X) {
4304 Instruction *NewOp =
4305 InsertNewInstBefore(BinaryOperator::createXor(Y, Z, Op0->getName()), I);
4306 return BinaryOperator::createAnd(NewOp, X);
4307 }
4308 }
4309 }
4310
Reid Spencere4d87aa2006-12-23 06:05:41 +00004311 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4312 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4313 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004314 return R;
4315
Chris Lattner6fc205f2006-05-05 06:39:07 +00004316 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004317 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
Chris Lattner6fc205f2006-05-05 06:39:07 +00004318 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004319 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4320 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00004321 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004322 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004323 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4324 I.getType(), TD) &&
4325 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4326 I.getType(), TD)) {
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004327 Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
4328 Op1C->getOperand(0),
4329 I.getName());
4330 InsertNewInstBefore(NewOp, I);
4331 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4332 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004333 }
Chris Lattnere511b742006-11-14 07:46:50 +00004334
Chris Lattner7e708292002-06-25 16:13:24 +00004335 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004336}
4337
Chris Lattnera96879a2004-09-29 17:40:11 +00004338/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4339/// overflowed for this type.
4340static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
Reid Spencere4e40032007-03-21 23:19:50 +00004341 ConstantInt *In2, bool IsSigned = false) {
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004342 Result = cast<ConstantInt>(Add(In1, In2));
Chris Lattnera96879a2004-09-29 17:40:11 +00004343
Reid Spencere4e40032007-03-21 23:19:50 +00004344 if (IsSigned)
4345 if (In2->getValue().isNegative())
4346 return Result->getValue().sgt(In1->getValue());
4347 else
4348 return Result->getValue().slt(In1->getValue());
4349 else
4350 return Result->getValue().ult(In1->getValue());
Chris Lattnera96879a2004-09-29 17:40:11 +00004351}
4352
Chris Lattner574da9b2005-01-13 20:14:25 +00004353/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4354/// code necessary to compute the offset from the base pointer (without adding
4355/// in the base pointer). Return the result as a signed integer of intptr size.
4356static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4357 TargetData &TD = IC.getTargetData();
4358 gep_type_iterator GTI = gep_type_begin(GEP);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004359 const Type *IntPtrTy = TD.getIntPtrType();
4360 Value *Result = Constant::getNullValue(IntPtrTy);
Chris Lattner574da9b2005-01-13 20:14:25 +00004361
4362 // Build a mask for high order bits.
Chris Lattnere62f0212007-04-28 04:52:43 +00004363 unsigned IntPtrWidth = TD.getPointerSize()*8;
4364 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Chris Lattner574da9b2005-01-13 20:14:25 +00004365
Chris Lattner574da9b2005-01-13 20:14:25 +00004366 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
4367 Value *Op = GEP->getOperand(i);
Chris Lattner0b84c802005-01-13 23:26:48 +00004368 uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattnere62f0212007-04-28 04:52:43 +00004369 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
4370 if (OpC->isZero()) continue;
4371
4372 // Handle a struct index, which adds its field offset to the pointer.
4373 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4374 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
4375
4376 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
4377 Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
Chris Lattner9bc14642007-04-28 00:57:34 +00004378 else
Chris Lattnere62f0212007-04-28 04:52:43 +00004379 Result = IC.InsertNewInstBefore(
4380 BinaryOperator::createAdd(Result,
4381 ConstantInt::get(IntPtrTy, Size),
4382 GEP->getName()+".offs"), I);
4383 continue;
Chris Lattner9bc14642007-04-28 00:57:34 +00004384 }
Chris Lattnere62f0212007-04-28 04:52:43 +00004385
4386 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4387 Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
4388 Scale = ConstantExpr::getMul(OC, Scale);
4389 if (Constant *RC = dyn_cast<Constant>(Result))
4390 Result = ConstantExpr::getAdd(RC, Scale);
4391 else {
4392 // Emit an add instruction.
4393 Result = IC.InsertNewInstBefore(
4394 BinaryOperator::createAdd(Result, Scale,
4395 GEP->getName()+".offs"), I);
Chris Lattner9bc14642007-04-28 00:57:34 +00004396 }
Chris Lattnere62f0212007-04-28 04:52:43 +00004397 continue;
Chris Lattner574da9b2005-01-13 20:14:25 +00004398 }
Chris Lattnere62f0212007-04-28 04:52:43 +00004399 // Convert to correct type.
4400 if (Op->getType() != IntPtrTy) {
4401 if (Constant *OpC = dyn_cast<Constant>(Op))
4402 Op = ConstantExpr::getSExt(OpC, IntPtrTy);
4403 else
4404 Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
4405 Op->getName()+".c"), I);
4406 }
4407 if (Size != 1) {
4408 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4409 if (Constant *OpC = dyn_cast<Constant>(Op))
4410 Op = ConstantExpr::getMul(OpC, Scale);
4411 else // We'll let instcombine(mul) convert this to a shl if possible.
4412 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
4413 GEP->getName()+".idx"), I);
4414 }
4415
4416 // Emit an add instruction.
4417 if (isa<Constant>(Op) && isa<Constant>(Result))
4418 Result = ConstantExpr::getAdd(cast<Constant>(Op),
4419 cast<Constant>(Result));
4420 else
4421 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
4422 GEP->getName()+".offs"), I);
Chris Lattner574da9b2005-01-13 20:14:25 +00004423 }
4424 return Result;
4425}
4426
Reid Spencere4d87aa2006-12-23 06:05:41 +00004427/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner574da9b2005-01-13 20:14:25 +00004428/// else. At this point we know that the GEP is on the LHS of the comparison.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004429Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
4430 ICmpInst::Predicate Cond,
4431 Instruction &I) {
Chris Lattner574da9b2005-01-13 20:14:25 +00004432 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattnere9d782b2005-01-13 22:25:21 +00004433
4434 if (CastInst *CI = dyn_cast<CastInst>(RHS))
4435 if (isa<PointerType>(CI->getOperand(0)->getType()))
4436 RHS = CI->getOperand(0);
4437
Chris Lattner574da9b2005-01-13 20:14:25 +00004438 Value *PtrBase = GEPLHS->getOperand(0);
4439 if (PtrBase == RHS) {
4440 // As an optimization, we don't actually have to compute the actual value of
Reid Spencere4d87aa2006-12-23 06:05:41 +00004441 // OFFSET if this is a icmp_eq or icmp_ne comparison, just return whether
4442 // each index is zero or not.
4443 if (Cond == ICmpInst::ICMP_EQ || Cond == ICmpInst::ICMP_NE) {
Chris Lattnere9d782b2005-01-13 22:25:21 +00004444 Instruction *InVal = 0;
Chris Lattnerad5fec12005-01-28 19:32:01 +00004445 gep_type_iterator GTI = gep_type_begin(GEPLHS);
4446 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattnere9d782b2005-01-13 22:25:21 +00004447 bool EmitIt = true;
4448 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
4449 if (isa<UndefValue>(C)) // undef index -> undef.
4450 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
4451 if (C->isNullValue())
4452 EmitIt = false;
Chris Lattnerad5fec12005-01-28 19:32:01 +00004453 else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
4454 EmitIt = false; // This is indexing into a zero sized array?
Misha Brukmanfd939082005-04-21 23:48:37 +00004455 } else if (isa<ConstantInt>(C))
Chris Lattnere9d782b2005-01-13 22:25:21 +00004456 return ReplaceInstUsesWith(I, // No comparison is needed here.
Reid Spencer579dca12007-01-12 04:24:46 +00004457 ConstantInt::get(Type::Int1Ty,
4458 Cond == ICmpInst::ICMP_NE));
Chris Lattnere9d782b2005-01-13 22:25:21 +00004459 }
4460
4461 if (EmitIt) {
Misha Brukmanfd939082005-04-21 23:48:37 +00004462 Instruction *Comp =
Reid Spencere4d87aa2006-12-23 06:05:41 +00004463 new ICmpInst(Cond, GEPLHS->getOperand(i),
Chris Lattnere9d782b2005-01-13 22:25:21 +00004464 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
4465 if (InVal == 0)
4466 InVal = Comp;
4467 else {
4468 InVal = InsertNewInstBefore(InVal, I);
4469 InsertNewInstBefore(Comp, I);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004470 if (Cond == ICmpInst::ICMP_NE) // True if any are unequal
Chris Lattnere9d782b2005-01-13 22:25:21 +00004471 InVal = BinaryOperator::createOr(InVal, Comp);
4472 else // True if all are equal
4473 InVal = BinaryOperator::createAnd(InVal, Comp);
4474 }
4475 }
4476 }
4477
4478 if (InVal)
4479 return InVal;
4480 else
Reid Spencere4d87aa2006-12-23 06:05:41 +00004481 // No comparison is needed here, all indexes = 0
Reid Spencer579dca12007-01-12 04:24:46 +00004482 ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4483 Cond == ICmpInst::ICMP_EQ));
Chris Lattnere9d782b2005-01-13 22:25:21 +00004484 }
Chris Lattner574da9b2005-01-13 20:14:25 +00004485
Reid Spencere4d87aa2006-12-23 06:05:41 +00004486 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00004487 // the result to fold to a constant!
4488 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
4489 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
4490 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004491 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
4492 Constant::getNullValue(Offset->getType()));
Chris Lattner574da9b2005-01-13 20:14:25 +00004493 }
4494 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00004495 // If the base pointers are different, but the indices are the same, just
4496 // compare the base pointer.
4497 if (PtrBase != GEPRHS->getOperand(0)) {
4498 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00004499 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00004500 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00004501 if (IndicesTheSame)
4502 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4503 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4504 IndicesTheSame = false;
4505 break;
4506 }
4507
4508 // If all indices are the same, just compare the base pointers.
4509 if (IndicesTheSame)
Reid Spencere4d87aa2006-12-23 06:05:41 +00004510 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
4511 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera70b66d2005-04-25 20:17:30 +00004512
4513 // Otherwise, the base pointers are different and the indices are
4514 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00004515 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00004516 }
Chris Lattner574da9b2005-01-13 20:14:25 +00004517
Chris Lattnere9d782b2005-01-13 22:25:21 +00004518 // If one of the GEPs has all zero indices, recurse.
4519 bool AllZeros = true;
4520 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4521 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4522 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4523 AllZeros = false;
4524 break;
4525 }
4526 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00004527 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
4528 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00004529
4530 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00004531 AllZeros = true;
4532 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4533 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4534 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4535 AllZeros = false;
4536 break;
4537 }
4538 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00004539 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattnere9d782b2005-01-13 22:25:21 +00004540
Chris Lattner4401c9c2005-01-14 00:20:05 +00004541 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4542 // If the GEPs only differ by one index, compare it.
4543 unsigned NumDifferences = 0; // Keep track of # differences.
4544 unsigned DiffOperand = 0; // The operand that differs.
4545 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4546 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00004547 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4548 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00004549 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00004550 NumDifferences = 2;
4551 break;
4552 } else {
4553 if (NumDifferences++) break;
4554 DiffOperand = i;
4555 }
4556 }
4557
4558 if (NumDifferences == 0) // SAME GEP?
4559 return ReplaceInstUsesWith(I, // No comparison is needed here.
Reid Spencer579dca12007-01-12 04:24:46 +00004560 ConstantInt::get(Type::Int1Ty,
4561 Cond == ICmpInst::ICMP_EQ));
Chris Lattner4401c9c2005-01-14 00:20:05 +00004562 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00004563 Value *LHSV = GEPLHS->getOperand(DiffOperand);
4564 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004565 // Make sure we do a signed comparison here.
4566 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00004567 }
4568 }
4569
Reid Spencere4d87aa2006-12-23 06:05:41 +00004570 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00004571 // the result to fold to a constant!
4572 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4573 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4574 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
4575 Value *L = EmitGEPOffset(GEPLHS, I, *this);
4576 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004577 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner574da9b2005-01-13 20:14:25 +00004578 }
4579 }
4580 return 0;
4581}
4582
Reid Spencere4d87aa2006-12-23 06:05:41 +00004583Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
4584 bool Changed = SimplifyCompare(I);
Chris Lattner8b170942002-08-09 23:47:40 +00004585 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004586
Chris Lattner58e97462007-01-14 19:42:17 +00004587 // Fold trivial predicates.
4588 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
4589 return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
4590 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
4591 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4592
4593 // Simplify 'fcmp pred X, X'
4594 if (Op0 == Op1) {
4595 switch (I.getPredicate()) {
4596 default: assert(0 && "Unknown predicate!");
4597 case FCmpInst::FCMP_UEQ: // True if unordered or equal
4598 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
4599 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
4600 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4601 case FCmpInst::FCMP_OGT: // True if ordered and greater than
4602 case FCmpInst::FCMP_OLT: // True if ordered and less than
4603 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
4604 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4605
4606 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
4607 case FCmpInst::FCMP_ULT: // True if unordered or less than
4608 case FCmpInst::FCMP_UGT: // True if unordered or greater than
4609 case FCmpInst::FCMP_UNE: // True if unordered or not equal
4610 // Canonicalize these to be 'fcmp uno %X, 0.0'.
4611 I.setPredicate(FCmpInst::FCMP_UNO);
4612 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4613 return &I;
4614
4615 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
4616 case FCmpInst::FCMP_OEQ: // True if ordered and equal
4617 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
4618 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
4619 // Canonicalize these to be 'fcmp ord %X, 0.0'.
4620 I.setPredicate(FCmpInst::FCMP_ORD);
4621 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4622 return &I;
4623 }
4624 }
4625
Reid Spencere4d87aa2006-12-23 06:05:41 +00004626 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Reid Spencer4fe16d62007-01-11 18:21:29 +00004627 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Chris Lattnere87597f2004-10-16 18:11:37 +00004628
Reid Spencere4d87aa2006-12-23 06:05:41 +00004629 // Handle fcmp with constant RHS
4630 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4631 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4632 switch (LHSI->getOpcode()) {
4633 case Instruction::PHI:
4634 if (Instruction *NV = FoldOpIntoPhi(I))
4635 return NV;
4636 break;
4637 case Instruction::Select:
4638 // If either operand of the select is a constant, we can fold the
4639 // comparison into the select arms, which will cause one to be
4640 // constant folded and the select turned into a bitwise or.
4641 Value *Op1 = 0, *Op2 = 0;
4642 if (LHSI->hasOneUse()) {
4643 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4644 // Fold the known value into the constant operand.
4645 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4646 // Insert a new FCmp of the other select operand.
4647 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4648 LHSI->getOperand(2), RHSC,
4649 I.getName()), I);
4650 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4651 // Fold the known value into the constant operand.
4652 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4653 // Insert a new FCmp of the other select operand.
4654 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4655 LHSI->getOperand(1), RHSC,
4656 I.getName()), I);
4657 }
4658 }
4659
4660 if (Op1)
4661 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4662 break;
4663 }
4664 }
4665
4666 return Changed ? &I : 0;
4667}
4668
4669Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
4670 bool Changed = SimplifyCompare(I);
4671 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4672 const Type *Ty = Op0->getType();
4673
4674 // icmp X, X
4675 if (Op0 == Op1)
Reid Spencer579dca12007-01-12 04:24:46 +00004676 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4677 isTrueWhenEqual(I)));
Reid Spencere4d87aa2006-12-23 06:05:41 +00004678
4679 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Reid Spencer4fe16d62007-01-11 18:21:29 +00004680 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Reid Spencere4d87aa2006-12-23 06:05:41 +00004681
4682 // icmp of GlobalValues can never equal each other as long as they aren't
4683 // external weak linkage type.
4684 if (GlobalValue *GV0 = dyn_cast<GlobalValue>(Op0))
4685 if (GlobalValue *GV1 = dyn_cast<GlobalValue>(Op1))
4686 if (!GV0->hasExternalWeakLinkage() || !GV1->hasExternalWeakLinkage())
Reid Spencer579dca12007-01-12 04:24:46 +00004687 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4688 !isTrueWhenEqual(I)));
Reid Spencere4d87aa2006-12-23 06:05:41 +00004689
4690 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner711b3402004-11-14 07:33:16 +00004691 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanfd939082005-04-21 23:48:37 +00004692 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
4693 isa<ConstantPointerNull>(Op0)) &&
4694 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner711b3402004-11-14 07:33:16 +00004695 isa<ConstantPointerNull>(Op1)))
Reid Spencer579dca12007-01-12 04:24:46 +00004696 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4697 !isTrueWhenEqual(I)));
Chris Lattner8b170942002-08-09 23:47:40 +00004698
Reid Spencere4d87aa2006-12-23 06:05:41 +00004699 // icmp's with boolean values can always be turned into bitwise operations
Reid Spencer4fe16d62007-01-11 18:21:29 +00004700 if (Ty == Type::Int1Ty) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00004701 switch (I.getPredicate()) {
4702 default: assert(0 && "Invalid icmp instruction!");
4703 case ICmpInst::ICMP_EQ: { // icmp eq bool %A, %B -> ~(A^B)
Chris Lattner48595f12004-06-10 02:07:29 +00004704 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner8b170942002-08-09 23:47:40 +00004705 InsertNewInstBefore(Xor, I);
Chris Lattnerde90b762003-11-03 04:25:02 +00004706 return BinaryOperator::createNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00004707 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004708 case ICmpInst::ICMP_NE: // icmp eq bool %A, %B -> A^B
Chris Lattner5dbef222004-08-11 00:50:51 +00004709 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00004710
Reid Spencere4d87aa2006-12-23 06:05:41 +00004711 case ICmpInst::ICMP_UGT:
4712 case ICmpInst::ICMP_SGT:
4713 std::swap(Op0, Op1); // Change icmp gt -> icmp lt
Chris Lattner5dbef222004-08-11 00:50:51 +00004714 // FALL THROUGH
Reid Spencere4d87aa2006-12-23 06:05:41 +00004715 case ICmpInst::ICMP_ULT:
4716 case ICmpInst::ICMP_SLT: { // icmp lt bool A, B -> ~X & Y
Chris Lattner5dbef222004-08-11 00:50:51 +00004717 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4718 InsertNewInstBefore(Not, I);
4719 return BinaryOperator::createAnd(Not, Op1);
4720 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004721 case ICmpInst::ICMP_UGE:
4722 case ICmpInst::ICMP_SGE:
4723 std::swap(Op0, Op1); // Change icmp ge -> icmp le
Chris Lattner5dbef222004-08-11 00:50:51 +00004724 // FALL THROUGH
Reid Spencere4d87aa2006-12-23 06:05:41 +00004725 case ICmpInst::ICMP_ULE:
4726 case ICmpInst::ICMP_SLE: { // icmp le bool %A, %B -> ~A | B
Chris Lattner5dbef222004-08-11 00:50:51 +00004727 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4728 InsertNewInstBefore(Not, I);
4729 return BinaryOperator::createOr(Not, Op1);
4730 }
4731 }
Chris Lattner8b170942002-08-09 23:47:40 +00004732 }
4733
Chris Lattner2be51ae2004-06-09 04:24:29 +00004734 // See if we are doing a comparison between a constant and an instruction that
4735 // can be folded into the comparison.
Chris Lattner8b170942002-08-09 23:47:40 +00004736 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00004737 switch (I.getPredicate()) {
4738 default: break;
4739 case ICmpInst::ICMP_ULT: // A <u MIN -> FALSE
4740 if (CI->isMinValue(false))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004741 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004742 if (CI->isMaxValue(false)) // A <u MAX -> A != MAX
4743 return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
4744 if (isMinValuePlusOne(CI,false)) // A <u MIN+1 -> A == MIN
4745 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
Chris Lattnerba417832007-04-11 06:12:58 +00004746 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
4747 if (CI->isMinValue(true))
4748 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
4749 ConstantInt::getAllOnesValue(Op0->getType()));
4750
Reid Spencere4d87aa2006-12-23 06:05:41 +00004751 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00004752
Reid Spencere4d87aa2006-12-23 06:05:41 +00004753 case ICmpInst::ICMP_SLT:
4754 if (CI->isMinValue(true)) // A <s MIN -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004755 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004756 if (CI->isMaxValue(true)) // A <s MAX -> A != MAX
4757 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4758 if (isMinValuePlusOne(CI,true)) // A <s MIN+1 -> A == MIN
4759 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4760 break;
4761
4762 case ICmpInst::ICMP_UGT:
4763 if (CI->isMaxValue(false)) // A >u MAX -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004764 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004765 if (CI->isMinValue(false)) // A >u MIN -> A != MIN
4766 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4767 if (isMaxValueMinusOne(CI, false)) // A >u MAX-1 -> A == MAX
4768 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
Chris Lattnerba417832007-04-11 06:12:58 +00004769
4770 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
4771 if (CI->isMaxValue(true))
4772 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
4773 ConstantInt::getNullValue(Op0->getType()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00004774 break;
4775
4776 case ICmpInst::ICMP_SGT:
4777 if (CI->isMaxValue(true)) // A >s MAX -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004778 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004779 if (CI->isMinValue(true)) // A >s MIN -> A != MIN
4780 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4781 if (isMaxValueMinusOne(CI, true)) // A >s MAX-1 -> A == MAX
4782 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4783 break;
4784
4785 case ICmpInst::ICMP_ULE:
4786 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004787 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004788 if (CI->isMinValue(false)) // A <=u MIN -> A == MIN
4789 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4790 if (isMaxValueMinusOne(CI,false)) // A <=u MAX-1 -> A != MAX
4791 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4792 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00004793
Reid Spencere4d87aa2006-12-23 06:05:41 +00004794 case ICmpInst::ICMP_SLE:
4795 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004796 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004797 if (CI->isMinValue(true)) // A <=s MIN -> A == MIN
4798 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4799 if (isMaxValueMinusOne(CI,true)) // A <=s MAX-1 -> A != MAX
4800 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4801 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00004802
Reid Spencere4d87aa2006-12-23 06:05:41 +00004803 case ICmpInst::ICMP_UGE:
4804 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004805 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004806 if (CI->isMaxValue(false)) // A >=u MAX -> A == MAX
4807 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4808 if (isMinValuePlusOne(CI,false)) // A >=u MIN-1 -> A != MIN
4809 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4810 break;
4811
4812 case ICmpInst::ICMP_SGE:
4813 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004814 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004815 if (CI->isMaxValue(true)) // A >=s MAX -> A == MAX
4816 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4817 if (isMinValuePlusOne(CI,true)) // A >=s MIN-1 -> A != MIN
4818 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4819 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00004820 }
4821
Reid Spencere4d87aa2006-12-23 06:05:41 +00004822 // If we still have a icmp le or icmp ge instruction, turn it into the
4823 // appropriate icmp lt or icmp gt instruction. Since the border cases have
Chris Lattnera96879a2004-09-29 17:40:11 +00004824 // already been handled above, this requires little checking.
4825 //
Reid Spencer2149a9d2007-03-25 19:55:33 +00004826 switch (I.getPredicate()) {
4827 default: break;
4828 case ICmpInst::ICMP_ULE:
4829 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
4830 case ICmpInst::ICMP_SLE:
4831 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
4832 case ICmpInst::ICMP_UGE:
4833 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
4834 case ICmpInst::ICMP_SGE:
4835 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
4836 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00004837
4838 // See if we can fold the comparison based on bits known to be zero or one
4839 // in the input.
Reid Spencer0460fb32007-03-22 20:36:03 +00004840 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
4841 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4842 if (SimplifyDemandedBits(Op0, APInt::getAllOnesValue(BitWidth),
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00004843 KnownZero, KnownOne, 0))
4844 return &I;
4845
4846 // Given the known and unknown bits, compute a range that the LHS could be
4847 // in.
Reid Spencer0460fb32007-03-22 20:36:03 +00004848 if ((KnownOne | KnownZero) != 0) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00004849 // Compute the Min, Max and RHS values based on the known bits. For the
4850 // EQ and NE we use unsigned values.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00004851 APInt Min(BitWidth, 0), Max(BitWidth, 0);
4852 const APInt& RHSVal = CI->getValue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00004853 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
Reid Spencer0460fb32007-03-22 20:36:03 +00004854 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
4855 Max);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004856 } else {
Reid Spencer0460fb32007-03-22 20:36:03 +00004857 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
4858 Max);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004859 }
4860 switch (I.getPredicate()) { // LE/GE have been folded already.
4861 default: assert(0 && "Unknown icmp opcode!");
4862 case ICmpInst::ICMP_EQ:
Reid Spencer0460fb32007-03-22 20:36:03 +00004863 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004864 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004865 break;
4866 case ICmpInst::ICMP_NE:
Reid Spencer0460fb32007-03-22 20:36:03 +00004867 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004868 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004869 break;
4870 case ICmpInst::ICMP_ULT:
Reid Spencer0460fb32007-03-22 20:36:03 +00004871 if (Max.ult(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004872 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00004873 if (Min.uge(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004874 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004875 break;
4876 case ICmpInst::ICMP_UGT:
Reid Spencer0460fb32007-03-22 20:36:03 +00004877 if (Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004878 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00004879 if (Max.ule(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004880 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004881 break;
4882 case ICmpInst::ICMP_SLT:
Reid Spencer0460fb32007-03-22 20:36:03 +00004883 if (Max.slt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004884 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer0460fb32007-03-22 20:36:03 +00004885 if (Min.sgt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004886 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004887 break;
4888 case ICmpInst::ICMP_SGT:
Reid Spencer0460fb32007-03-22 20:36:03 +00004889 if (Min.sgt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004890 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00004891 if (Max.sle(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004892 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004893 break;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00004894 }
4895 }
4896
Reid Spencere4d87aa2006-12-23 06:05:41 +00004897 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer1628cec2006-10-26 06:15:43 +00004898 // instruction, see if that instruction also has constants so that the
Reid Spencere4d87aa2006-12-23 06:05:41 +00004899 // instruction can be folded into the icmp
Chris Lattner3c6a0d42004-05-25 06:32:08 +00004900 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner01deb9d2007-04-03 17:43:25 +00004901 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
4902 return Res;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004903 }
4904
Chris Lattner01deb9d2007-04-03 17:43:25 +00004905 // Handle icmp with constant (but not simple integer constant) RHS
Chris Lattner6970b662005-04-23 15:31:55 +00004906 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4907 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4908 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00004909 case Instruction::GetElementPtr:
4910 if (RHSC->isNullValue()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00004911 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattner9fb25db2005-05-01 04:42:15 +00004912 bool isAllZeros = true;
4913 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
4914 if (!isa<Constant>(LHSI->getOperand(i)) ||
4915 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
4916 isAllZeros = false;
4917 break;
4918 }
4919 if (isAllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00004920 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Chris Lattner9fb25db2005-05-01 04:42:15 +00004921 Constant::getNullValue(LHSI->getOperand(0)->getType()));
4922 }
4923 break;
4924
Chris Lattner6970b662005-04-23 15:31:55 +00004925 case Instruction::PHI:
4926 if (Instruction *NV = FoldOpIntoPhi(I))
4927 return NV;
4928 break;
Chris Lattner4802d902007-04-06 18:57:34 +00004929 case Instruction::Select: {
Chris Lattner6970b662005-04-23 15:31:55 +00004930 // If either operand of the select is a constant, we can fold the
4931 // comparison into the select arms, which will cause one to be
4932 // constant folded and the select turned into a bitwise or.
4933 Value *Op1 = 0, *Op2 = 0;
4934 if (LHSI->hasOneUse()) {
4935 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4936 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004937 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
4938 // Insert a new ICmp of the other select operand.
4939 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
4940 LHSI->getOperand(2), RHSC,
4941 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00004942 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4943 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004944 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
4945 // Insert a new ICmp of the other select operand.
4946 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
4947 LHSI->getOperand(1), RHSC,
4948 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00004949 }
4950 }
Jeff Cohen9d809302005-04-23 21:38:35 +00004951
Chris Lattner6970b662005-04-23 15:31:55 +00004952 if (Op1)
4953 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4954 break;
4955 }
Chris Lattner4802d902007-04-06 18:57:34 +00004956 case Instruction::Malloc:
4957 // If we have (malloc != null), and if the malloc has a single use, we
4958 // can assume it is successful and remove the malloc.
4959 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
4960 AddToWorkList(LHSI);
4961 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4962 !isTrueWhenEqual(I)));
4963 }
4964 break;
4965 }
Chris Lattner6970b662005-04-23 15:31:55 +00004966 }
4967
Reid Spencere4d87aa2006-12-23 06:05:41 +00004968 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Chris Lattner574da9b2005-01-13 20:14:25 +00004969 if (User *GEP = dyn_castGetElementPtr(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00004970 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00004971 return NI;
4972 if (User *GEP = dyn_castGetElementPtr(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00004973 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
4974 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00004975 return NI;
4976
Reid Spencere4d87aa2006-12-23 06:05:41 +00004977 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner57d86372007-01-06 01:45:59 +00004978 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
4979 // now.
4980 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
4981 if (isa<PointerType>(Op0->getType()) &&
4982 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattnerde90b762003-11-03 04:25:02 +00004983 // We keep moving the cast from the left operand over to the right
4984 // operand, where it can often be eliminated completely.
Chris Lattner57d86372007-01-06 01:45:59 +00004985 Op0 = CI->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00004986
Chris Lattner57d86372007-01-06 01:45:59 +00004987 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
4988 // so eliminate it as well.
4989 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
4990 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00004991
Chris Lattnerde90b762003-11-03 04:25:02 +00004992 // If Op1 is a constant, we can fold the cast into the constant.
Chris Lattner57d86372007-01-06 01:45:59 +00004993 if (Op0->getType() != Op1->getType())
Chris Lattnerde90b762003-11-03 04:25:02 +00004994 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Reid Spencerd977d862006-12-12 23:36:14 +00004995 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00004996 } else {
Reid Spencere4d87aa2006-12-23 06:05:41 +00004997 // Otherwise, cast the RHS right before the icmp
Reid Spencer17212df2006-12-12 09:18:51 +00004998 Op1 = InsertCastBefore(Instruction::BitCast, Op1, Op0->getType(), I);
Chris Lattnerde90b762003-11-03 04:25:02 +00004999 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00005000 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattnerde90b762003-11-03 04:25:02 +00005001 }
Chris Lattner57d86372007-01-06 01:45:59 +00005002 }
5003
5004 if (isa<CastInst>(Op0)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005005 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner68708052003-11-03 05:17:03 +00005006 // This comes up when you have code like
5007 // int X = A < B;
5008 // if (X) ...
5009 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00005010 // with a constant or another cast from the same type.
5011 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005012 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattner484d3cf2005-04-24 06:59:08 +00005013 return R;
Chris Lattner68708052003-11-03 05:17:03 +00005014 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00005015
Chris Lattner65b72ba2006-09-18 04:22:48 +00005016 if (I.isEquality()) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005017 Value *A, *B, *C, *D;
5018 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
5019 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
5020 Value *OtherVal = A == Op1 ? B : A;
5021 return new ICmpInst(I.getPredicate(), OtherVal,
5022 Constant::getNullValue(A->getType()));
5023 }
5024
5025 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5026 // A^c1 == C^c2 --> A == C^(c1^c2)
5027 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
5028 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
5029 if (Op1->hasOneUse()) {
Zhou Sheng4a1822a2007-04-02 13:45:30 +00005030 Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005031 Instruction *Xor = BinaryOperator::createXor(C, NC, "tmp");
5032 return new ICmpInst(I.getPredicate(), A,
5033 InsertNewInstBefore(Xor, I));
5034 }
5035
5036 // A^B == A^D -> B == D
5037 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
5038 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
5039 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
5040 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
5041 }
5042 }
5043
5044 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5045 (A == Op0 || B == Op0)) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00005046 // A == (A^B) -> B == 0
5047 Value *OtherVal = A == Op0 ? B : A;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005048 return new ICmpInst(I.getPredicate(), OtherVal,
5049 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005050 }
5051 if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00005052 // (A-B) == A -> B == 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00005053 return new ICmpInst(I.getPredicate(), B,
5054 Constant::getNullValue(B->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005055 }
5056 if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00005057 // A == (A-B) -> B == 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00005058 return new ICmpInst(I.getPredicate(), B,
5059 Constant::getNullValue(B->getType()));
Chris Lattner26ab9a92006-02-27 01:44:11 +00005060 }
Chris Lattner9c2328e2006-11-14 06:06:06 +00005061
Chris Lattner9c2328e2006-11-14 06:06:06 +00005062 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5063 if (Op0->hasOneUse() && Op1->hasOneUse() &&
5064 match(Op0, m_And(m_Value(A), m_Value(B))) &&
5065 match(Op1, m_And(m_Value(C), m_Value(D)))) {
5066 Value *X = 0, *Y = 0, *Z = 0;
5067
5068 if (A == C) {
5069 X = B; Y = D; Z = A;
5070 } else if (A == D) {
5071 X = B; Y = C; Z = A;
5072 } else if (B == C) {
5073 X = A; Y = D; Z = B;
5074 } else if (B == D) {
5075 X = A; Y = C; Z = B;
5076 }
5077
5078 if (X) { // Build (X^Y) & Z
5079 Op1 = InsertNewInstBefore(BinaryOperator::createXor(X, Y, "tmp"), I);
5080 Op1 = InsertNewInstBefore(BinaryOperator::createAnd(Op1, Z, "tmp"), I);
5081 I.setOperand(0, Op1);
5082 I.setOperand(1, Constant::getNullValue(Op1->getType()));
5083 return &I;
5084 }
5085 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00005086 }
Chris Lattner7e708292002-06-25 16:13:24 +00005087 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005088}
5089
Chris Lattner01deb9d2007-04-03 17:43:25 +00005090/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
5091///
5092Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
5093 Instruction *LHSI,
5094 ConstantInt *RHS) {
5095 const APInt &RHSV = RHS->getValue();
5096
5097 switch (LHSI->getOpcode()) {
Duncan Sands0091bf22007-04-04 06:42:45 +00005098 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
Chris Lattner01deb9d2007-04-03 17:43:25 +00005099 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
5100 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
5101 // fold the xor.
5102 if (ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0 ||
5103 ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue()) {
5104 Value *CompareVal = LHSI->getOperand(0);
5105
5106 // If the sign bit of the XorCST is not set, there is no change to
5107 // the operation, just stop using the Xor.
5108 if (!XorCST->getValue().isNegative()) {
5109 ICI.setOperand(0, CompareVal);
5110 AddToWorkList(LHSI);
5111 return &ICI;
5112 }
5113
5114 // Was the old condition true if the operand is positive?
5115 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
5116
5117 // If so, the new one isn't.
5118 isTrueIfPositive ^= true;
5119
5120 if (isTrueIfPositive)
5121 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
5122 else
5123 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
5124 }
5125 }
5126 break;
5127 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
5128 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
5129 LHSI->getOperand(0)->hasOneUse()) {
5130 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
5131
5132 // If the LHS is an AND of a truncating cast, we can widen the
5133 // and/compare to be the input width without changing the value
5134 // produced, eliminating a cast.
5135 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
5136 // We can do this transformation if either the AND constant does not
5137 // have its sign bit set or if it is an equality comparison.
5138 // Extending a relational comparison when we're checking the sign
5139 // bit would not work.
5140 if (Cast->hasOneUse() &&
5141 (ICI.isEquality() || AndCST->getValue().isPositive() &&
5142 RHSV.isPositive())) {
5143 uint32_t BitWidth =
5144 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
5145 APInt NewCST = AndCST->getValue();
5146 NewCST.zext(BitWidth);
5147 APInt NewCI = RHSV;
5148 NewCI.zext(BitWidth);
5149 Instruction *NewAnd =
5150 BinaryOperator::createAnd(Cast->getOperand(0),
5151 ConstantInt::get(NewCST),LHSI->getName());
5152 InsertNewInstBefore(NewAnd, ICI);
5153 return new ICmpInst(ICI.getPredicate(), NewAnd,
5154 ConstantInt::get(NewCI));
5155 }
5156 }
5157
5158 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
5159 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
5160 // happens a LOT in code produced by the C front-end, for bitfield
5161 // access.
5162 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
5163 if (Shift && !Shift->isShift())
5164 Shift = 0;
5165
5166 ConstantInt *ShAmt;
5167 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
5168 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
5169 const Type *AndTy = AndCST->getType(); // Type of the and.
5170
5171 // We can fold this as long as we can't shift unknown bits
5172 // into the mask. This can only happen with signed shift
5173 // rights, as they sign-extend.
5174 if (ShAmt) {
5175 bool CanFold = Shift->isLogicalShift();
5176 if (!CanFold) {
5177 // To test for the bad case of the signed shr, see if any
5178 // of the bits shifted in could be tested after the mask.
5179 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
5180 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
5181
5182 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
5183 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
5184 AndCST->getValue()) == 0)
5185 CanFold = true;
5186 }
5187
5188 if (CanFold) {
5189 Constant *NewCst;
5190 if (Shift->getOpcode() == Instruction::Shl)
5191 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
5192 else
5193 NewCst = ConstantExpr::getShl(RHS, ShAmt);
5194
5195 // Check to see if we are shifting out any of the bits being
5196 // compared.
5197 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
5198 // If we shifted bits out, the fold is not going to work out.
5199 // As a special case, check to see if this means that the
5200 // result is always true or false now.
5201 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
5202 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5203 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
5204 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5205 } else {
5206 ICI.setOperand(1, NewCst);
5207 Constant *NewAndCST;
5208 if (Shift->getOpcode() == Instruction::Shl)
5209 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
5210 else
5211 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
5212 LHSI->setOperand(1, NewAndCST);
5213 LHSI->setOperand(0, Shift->getOperand(0));
5214 AddToWorkList(Shift); // Shift is dead.
5215 AddUsesToWorkList(ICI);
5216 return &ICI;
5217 }
5218 }
5219 }
5220
5221 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
5222 // preferable because it allows the C<<Y expression to be hoisted out
5223 // of a loop if Y is invariant and X is not.
5224 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
5225 ICI.isEquality() && !Shift->isArithmeticShift() &&
5226 isa<Instruction>(Shift->getOperand(0))) {
5227 // Compute C << Y.
5228 Value *NS;
5229 if (Shift->getOpcode() == Instruction::LShr) {
5230 NS = BinaryOperator::createShl(AndCST,
5231 Shift->getOperand(1), "tmp");
5232 } else {
5233 // Insert a logical shift.
5234 NS = BinaryOperator::createLShr(AndCST,
5235 Shift->getOperand(1), "tmp");
5236 }
5237 InsertNewInstBefore(cast<Instruction>(NS), ICI);
5238
5239 // Compute X & (C << Y).
5240 Instruction *NewAnd =
5241 BinaryOperator::createAnd(Shift->getOperand(0), NS, LHSI->getName());
5242 InsertNewInstBefore(NewAnd, ICI);
5243
5244 ICI.setOperand(0, NewAnd);
5245 return &ICI;
5246 }
5247 }
5248 break;
5249
5250 case Instruction::Shl: // (icmp pred (shl X, ShAmt), CI)
5251 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
5252 if (ICI.isEquality()) {
5253 uint32_t TypeBits = RHSV.getBitWidth();
5254
5255 // Check that the shift amount is in range. If not, don't perform
5256 // undefined shifts. When the shift is visited it will be
5257 // simplified.
5258 if (ShAmt->uge(TypeBits))
5259 break;
5260
5261 // If we are comparing against bits always shifted out, the
5262 // comparison cannot succeed.
5263 Constant *Comp =
5264 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
5265 if (Comp != RHS) {// Comparing against a bit that we know is zero.
5266 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5267 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5268 return ReplaceInstUsesWith(ICI, Cst);
5269 }
5270
5271 if (LHSI->hasOneUse()) {
5272 // Otherwise strength reduce the shift into an and.
5273 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
5274 Constant *Mask =
5275 ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
5276
5277 Instruction *AndI =
5278 BinaryOperator::createAnd(LHSI->getOperand(0),
5279 Mask, LHSI->getName()+".mask");
5280 Value *And = InsertNewInstBefore(AndI, ICI);
5281 return new ICmpInst(ICI.getPredicate(), And,
Chris Lattner73050842007-04-03 23:29:39 +00005282 ConstantInt::get(RHSV.lshr(ShAmtVal)));
Chris Lattner01deb9d2007-04-03 17:43:25 +00005283 }
5284 }
5285 }
5286 break;
5287
5288 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
5289 case Instruction::AShr:
5290 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
5291 if (ICI.isEquality()) {
5292 // Check that the shift amount is in range. If not, don't perform
5293 // undefined shifts. When the shift is visited it will be
5294 // simplified.
5295 uint32_t TypeBits = RHSV.getBitWidth();
5296 if (ShAmt->uge(TypeBits))
5297 break;
5298 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
5299
5300 // If we are comparing against bits always shifted out, the
5301 // comparison cannot succeed.
5302 APInt Comp = RHSV << ShAmtVal;
5303 if (LHSI->getOpcode() == Instruction::LShr)
5304 Comp = Comp.lshr(ShAmtVal);
5305 else
5306 Comp = Comp.ashr(ShAmtVal);
5307
5308 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
5309 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5310 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5311 return ReplaceInstUsesWith(ICI, Cst);
5312 }
5313
5314 if (LHSI->hasOneUse() || RHSV == 0) {
5315 // Otherwise strength reduce the shift into an and.
5316 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
5317 Constant *Mask = ConstantInt::get(Val);
5318
5319 Instruction *AndI =
5320 BinaryOperator::createAnd(LHSI->getOperand(0),
5321 Mask, LHSI->getName()+".mask");
5322 Value *And = InsertNewInstBefore(AndI, ICI);
5323 return new ICmpInst(ICI.getPredicate(), And,
5324 ConstantExpr::getShl(RHS, ShAmt));
5325 }
5326 }
5327 }
5328 break;
5329
5330 case Instruction::SDiv:
5331 case Instruction::UDiv:
5332 // Fold: icmp pred ([us]div X, C1), C2 -> range test
5333 // Fold this div into the comparison, producing a range check.
5334 // Determine, based on the divide type, what the range is being
5335 // checked. If there is an overflow on the low or high side, remember
5336 // it, otherwise compute the range [low, hi) bounding the new value.
5337 // See: InsertRangeTest above for the kinds of replacements possible.
5338 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
5339 // FIXME: If the operand types don't match the type of the divide
5340 // then don't attempt this transform. The code below doesn't have the
5341 // logic to deal with a signed divide and an unsigned compare (and
5342 // vice versa). This is because (x /s C1) <s C2 produces different
5343 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
5344 // (x /u C1) <u C2. Simply casting the operands and result won't
5345 // work. :( The if statement below tests that condition and bails
5346 // if it finds it.
5347 bool DivIsSigned = LHSI->getOpcode() == Instruction::SDiv;
5348 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
5349 break;
5350 if (DivRHS->isZero())
5351 break; // Don't hack on div by zero
5352
5353 // Initialize the variables that will indicate the nature of the
5354 // range check.
5355 bool LoOverflow = false, HiOverflow = false;
5356 ConstantInt *LoBound = 0, *HiBound = 0;
5357
5358 // Compute Prod = CI * DivRHS. We are essentially solving an equation
5359 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
5360 // C2 (CI). By solving for X we can turn this into a range check
5361 // instead of computing a divide.
5362 ConstantInt *Prod = Multiply(RHS, DivRHS);
5363
5364 // Determine if the product overflows by seeing if the product is
5365 // not equal to the divide. Make sure we do the same kind of divide
5366 // as in the LHS instruction that we're folding.
5367 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
5368 ConstantExpr::getUDiv(Prod, DivRHS)) != RHS;
5369
5370 // Get the ICmp opcode
5371 ICmpInst::Predicate predicate = ICI.getPredicate();
5372
5373 if (!DivIsSigned) { // udiv
5374 LoBound = Prod;
5375 LoOverflow = ProdOV;
5376 HiOverflow = ProdOV ||
5377 AddWithOverflow(HiBound, LoBound, DivRHS, false);
5378 } else if (DivRHS->getValue().isPositive()) { // Divisor is > 0.
5379 if (RHSV == 0) { // (X / pos) op 0
5380 // Can't overflow.
5381 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
5382 HiBound = DivRHS;
5383 } else if (RHSV.isPositive()) { // (X / pos) op pos
5384 LoBound = Prod;
5385 LoOverflow = ProdOV;
5386 HiOverflow = ProdOV ||
5387 AddWithOverflow(HiBound, Prod, DivRHS, true);
5388 } else { // (X / pos) op neg
5389 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
5390 LoOverflow = AddWithOverflow(LoBound, Prod,
5391 cast<ConstantInt>(DivRHSH), true);
5392 HiBound = AddOne(Prod);
5393 HiOverflow = ProdOV;
5394 }
5395 } else { // Divisor is < 0.
5396 if (RHSV == 0) { // (X / neg) op 0
5397 LoBound = AddOne(DivRHS);
5398 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
5399 if (HiBound == DivRHS)
5400 LoBound = 0; // - INTMIN = INTMIN
5401 } else if (RHSV.isPositive()) { // (X / neg) op pos
5402 HiOverflow = LoOverflow = ProdOV;
5403 if (!LoOverflow)
5404 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS),
5405 true);
5406 HiBound = AddOne(Prod);
5407 } else { // (X / neg) op neg
5408 LoBound = Prod;
5409 LoOverflow = HiOverflow = ProdOV;
5410 HiBound = Subtract(Prod, DivRHS);
5411 }
5412
5413 // Dividing by a negate swaps the condition.
5414 predicate = ICmpInst::getSwappedPredicate(predicate);
5415 }
5416
5417 if (LoBound) {
5418 Value *X = LHSI->getOperand(0);
5419 switch (predicate) {
5420 default: assert(0 && "Unhandled icmp opcode!");
5421 case ICmpInst::ICMP_EQ:
5422 if (LoOverflow && HiOverflow)
5423 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5424 else if (HiOverflow)
5425 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
5426 ICmpInst::ICMP_UGE, X, LoBound);
5427 else if (LoOverflow)
5428 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
5429 ICmpInst::ICMP_ULT, X, HiBound);
5430 else
5431 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned,
5432 true, ICI);
5433 case ICmpInst::ICMP_NE:
5434 if (LoOverflow && HiOverflow)
5435 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5436 else if (HiOverflow)
5437 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
5438 ICmpInst::ICMP_ULT, X, LoBound);
5439 else if (LoOverflow)
5440 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
5441 ICmpInst::ICMP_UGE, X, HiBound);
5442 else
5443 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned,
5444 false, ICI);
5445 case ICmpInst::ICMP_ULT:
5446 case ICmpInst::ICMP_SLT:
5447 if (LoOverflow)
5448 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5449 return new ICmpInst(predicate, X, LoBound);
5450 case ICmpInst::ICMP_UGT:
5451 case ICmpInst::ICMP_SGT:
5452 if (HiOverflow)
5453 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5454 if (predicate == ICmpInst::ICMP_UGT)
5455 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
5456 else
5457 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
5458 }
5459 }
5460 }
5461 break;
5462 }
5463
5464 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
5465 if (ICI.isEquality()) {
5466 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5467
5468 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
5469 // the second operand is a constant, simplify a bit.
5470 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
5471 switch (BO->getOpcode()) {
5472 case Instruction::SRem:
5473 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
5474 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
5475 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
5476 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
5477 Instruction *NewRem =
5478 BinaryOperator::createURem(BO->getOperand(0), BO->getOperand(1),
5479 BO->getName());
5480 InsertNewInstBefore(NewRem, ICI);
5481 return new ICmpInst(ICI.getPredicate(), NewRem,
5482 Constant::getNullValue(BO->getType()));
5483 }
5484 }
5485 break;
5486 case Instruction::Add:
5487 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
5488 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
5489 if (BO->hasOneUse())
5490 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
5491 Subtract(RHS, BOp1C));
5492 } else if (RHSV == 0) {
5493 // Replace ((add A, B) != 0) with (A != -B) if A or B is
5494 // efficiently invertible, or if the add has just this one use.
5495 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
5496
5497 if (Value *NegVal = dyn_castNegVal(BOp1))
5498 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
5499 else if (Value *NegVal = dyn_castNegVal(BOp0))
5500 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
5501 else if (BO->hasOneUse()) {
5502 Instruction *Neg = BinaryOperator::createNeg(BOp1);
5503 InsertNewInstBefore(Neg, ICI);
5504 Neg->takeName(BO);
5505 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
5506 }
5507 }
5508 break;
5509 case Instruction::Xor:
5510 // For the xor case, we can xor two constants together, eliminating
5511 // the explicit xor.
5512 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
5513 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
5514 ConstantExpr::getXor(RHS, BOC));
5515
5516 // FALLTHROUGH
5517 case Instruction::Sub:
5518 // Replace (([sub|xor] A, B) != 0) with (A != B)
5519 if (RHSV == 0)
5520 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
5521 BO->getOperand(1));
5522 break;
5523
5524 case Instruction::Or:
5525 // If bits are being or'd in that are not present in the constant we
5526 // are comparing against, then the comparison could never succeed!
5527 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
5528 Constant *NotCI = ConstantExpr::getNot(RHS);
5529 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
5530 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
5531 isICMP_NE));
5532 }
5533 break;
5534
5535 case Instruction::And:
5536 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
5537 // If bits are being compared against that are and'd out, then the
5538 // comparison can never succeed!
5539 if ((RHSV & ~BOC->getValue()) != 0)
5540 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
5541 isICMP_NE));
5542
5543 // If we have ((X & C) == C), turn it into ((X & C) != 0).
5544 if (RHS == BOC && RHSV.isPowerOf2())
5545 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
5546 ICmpInst::ICMP_NE, LHSI,
5547 Constant::getNullValue(RHS->getType()));
5548
5549 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
5550 if (isSignBit(BOC)) {
5551 Value *X = BO->getOperand(0);
5552 Constant *Zero = Constant::getNullValue(X->getType());
5553 ICmpInst::Predicate pred = isICMP_NE ?
5554 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
5555 return new ICmpInst(pred, X, Zero);
5556 }
5557
5558 // ((X & ~7) == 0) --> X < 8
5559 if (RHSV == 0 && isHighOnes(BOC)) {
5560 Value *X = BO->getOperand(0);
5561 Constant *NegX = ConstantExpr::getNeg(BOC);
5562 ICmpInst::Predicate pred = isICMP_NE ?
5563 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
5564 return new ICmpInst(pred, X, NegX);
5565 }
5566 }
5567 default: break;
5568 }
5569 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
5570 // Handle icmp {eq|ne} <intrinsic>, intcst.
5571 if (II->getIntrinsicID() == Intrinsic::bswap) {
5572 AddToWorkList(II);
5573 ICI.setOperand(0, II->getOperand(1));
5574 ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
5575 return &ICI;
5576 }
5577 }
5578 } else { // Not a ICMP_EQ/ICMP_NE
Chris Lattnere34e9a22007-04-14 23:32:02 +00005579 // If the LHS is a cast from an integral value of the same size,
5580 // then since we know the RHS is a constant, try to simlify.
Chris Lattner01deb9d2007-04-03 17:43:25 +00005581 if (CastInst *Cast = dyn_cast<CastInst>(LHSI)) {
5582 Value *CastOp = Cast->getOperand(0);
5583 const Type *SrcTy = CastOp->getType();
5584 uint32_t SrcTySize = SrcTy->getPrimitiveSizeInBits();
5585 if (SrcTy->isInteger() &&
5586 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
5587 // If this is an unsigned comparison, try to make the comparison use
5588 // smaller constant values.
5589 if (ICI.getPredicate() == ICmpInst::ICMP_ULT && RHSV.isSignBit()) {
5590 // X u< 128 => X s> -1
5591 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp,
5592 ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
5593 } else if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
5594 RHSV == APInt::getSignedMaxValue(SrcTySize)) {
5595 // X u> 127 => X s< 0
5596 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp,
5597 Constant::getNullValue(SrcTy));
5598 }
5599 }
5600 }
5601 }
5602 return 0;
5603}
5604
5605/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
5606/// We only handle extending casts so far.
5607///
Reid Spencere4d87aa2006-12-23 06:05:41 +00005608Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
5609 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +00005610 Value *LHSCIOp = LHSCI->getOperand(0);
5611 const Type *SrcTy = LHSCIOp->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00005612 const Type *DestTy = LHSCI->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00005613 Value *RHSCIOp;
5614
Chris Lattner8c756c12007-05-05 22:41:33 +00005615 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
5616 // integer type is the same size as the pointer type.
5617 if (LHSCI->getOpcode() == Instruction::PtrToInt &&
5618 getTargetData().getPointerSizeInBits() ==
5619 cast<IntegerType>(DestTy)->getBitWidth()) {
5620 Value *RHSOp = 0;
5621 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Chris Lattner6f6f5122007-05-06 07:24:03 +00005622 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Chris Lattner8c756c12007-05-05 22:41:33 +00005623 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
5624 RHSOp = RHSC->getOperand(0);
5625 // If the pointer types don't match, insert a bitcast.
5626 if (LHSCIOp->getType() != RHSOp->getType())
5627 RHSOp = InsertCastBefore(Instruction::BitCast, RHSOp,
5628 LHSCIOp->getType(), ICI);
5629 }
5630
5631 if (RHSOp)
5632 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
5633 }
5634
5635 // The code below only handles extension cast instructions, so far.
5636 // Enforce this.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005637 if (LHSCI->getOpcode() != Instruction::ZExt &&
5638 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattnerb352fa52005-01-17 03:20:02 +00005639 return 0;
5640
Reid Spencere4d87aa2006-12-23 06:05:41 +00005641 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
5642 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattner484d3cf2005-04-24 06:59:08 +00005643
Reid Spencere4d87aa2006-12-23 06:05:41 +00005644 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00005645 // Not an extension from the same type?
5646 RHSCIOp = CI->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005647 if (RHSCIOp->getType() != LHSCIOp->getType())
5648 return 0;
Chris Lattnera5c5e772007-01-13 23:11:38 +00005649
5650 // If the signedness of the two compares doesn't agree (i.e. one is a sext
5651 // and the other is a zext), then we can't handle this.
5652 if (CI->getOpcode() != LHSCI->getOpcode())
5653 return 0;
5654
5655 // Likewise, if the signedness of the [sz]exts and the compare don't match,
5656 // then we can't handle this.
5657 if (isSignedExt != isSignedCmp && !ICI.isEquality())
5658 return 0;
5659
5660 // Okay, just insert a compare of the reduced operands now!
5661 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer6731d5c2004-11-28 21:31:15 +00005662 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00005663
Reid Spencere4d87aa2006-12-23 06:05:41 +00005664 // If we aren't dealing with a constant on the RHS, exit early
5665 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
5666 if (!CI)
5667 return 0;
5668
5669 // Compute the constant that would happen if we truncated to SrcTy then
5670 // reextended to DestTy.
5671 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
5672 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
5673
5674 // If the re-extended constant didn't change...
5675 if (Res2 == CI) {
5676 // Make sure that sign of the Cmp and the sign of the Cast are the same.
5677 // For example, we might have:
5678 // %A = sext short %X to uint
5679 // %B = icmp ugt uint %A, 1330
5680 // It is incorrect to transform this into
5681 // %B = icmp ugt short %X, 1330
5682 // because %A may have negative value.
5683 //
5684 // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
5685 // OR operation is EQ/NE.
Reid Spencer4fe16d62007-01-11 18:21:29 +00005686 if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
Reid Spencere4d87aa2006-12-23 06:05:41 +00005687 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
5688 else
5689 return 0;
5690 }
5691
5692 // The re-extended constant changed so the constant cannot be represented
5693 // in the shorter type. Consequently, we cannot emit a simple comparison.
5694
5695 // First, handle some easy cases. We know the result cannot be equal at this
5696 // point so handle the ICI.isEquality() cases
5697 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005698 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005699 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005700 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005701
5702 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
5703 // should have been folded away previously and not enter in here.
5704 Value *Result;
5705 if (isSignedCmp) {
5706 // We're performing a signed comparison.
Reid Spencer0460fb32007-03-22 20:36:03 +00005707 if (cast<ConstantInt>(CI)->getValue().isNegative())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005708 Result = ConstantInt::getFalse(); // X < (small) --> false
Reid Spencere4d87aa2006-12-23 06:05:41 +00005709 else
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005710 Result = ConstantInt::getTrue(); // X < (large) --> true
Reid Spencere4d87aa2006-12-23 06:05:41 +00005711 } else {
5712 // We're performing an unsigned comparison.
5713 if (isSignedExt) {
5714 // We're performing an unsigned comp with a sign extended value.
5715 // This is true if the input is >= 0. [aka >s -1]
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005716 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005717 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
5718 NegOne, ICI.getName()), ICI);
5719 } else {
5720 // Unsigned extend & unsigned compare -> always true.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005721 Result = ConstantInt::getTrue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00005722 }
5723 }
5724
5725 // Finally, return the value computed.
5726 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
5727 ICI.getPredicate() == ICmpInst::ICMP_SLT) {
5728 return ReplaceInstUsesWith(ICI, Result);
5729 } else {
5730 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
5731 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
5732 "ICmp should be folded!");
5733 if (Constant *CI = dyn_cast<Constant>(Result))
5734 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
5735 else
5736 return BinaryOperator::createNot(Result);
5737 }
Chris Lattner484d3cf2005-04-24 06:59:08 +00005738}
Chris Lattner3f5b8772002-05-06 16:14:14 +00005739
Reid Spencer832254e2007-02-02 02:16:23 +00005740Instruction *InstCombiner::visitShl(BinaryOperator &I) {
5741 return commonShiftTransforms(I);
5742}
5743
5744Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
5745 return commonShiftTransforms(I);
5746}
5747
5748Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
5749 return commonShiftTransforms(I);
5750}
5751
5752Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
5753 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00005754 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005755
5756 // shl X, 0 == X and shr X, 0 == X
5757 // shl 0, X == 0 and shr 0, X == 0
Reid Spencer832254e2007-02-02 02:16:23 +00005758 if (Op1 == Constant::getNullValue(Op1->getType()) ||
Chris Lattner233f7dc2002-08-12 21:17:25 +00005759 Op0 == Constant::getNullValue(Op0->getType()))
5760 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00005761
Reid Spencere4d87aa2006-12-23 06:05:41 +00005762 if (isa<UndefValue>(Op0)) {
5763 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00005764 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005765 else // undef << X -> 0, undef >>u X -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00005766 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5767 }
5768 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005769 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
5770 return ReplaceInstUsesWith(I, Op0);
5771 else // X << undef, X >>u undef -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00005772 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00005773 }
5774
Chris Lattnerde2b6602006-11-10 23:38:52 +00005775 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
5776 if (I.getOpcode() == Instruction::AShr)
Reid Spencerb83eb642006-10-20 07:07:24 +00005777 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Chris Lattnerde2b6602006-11-10 23:38:52 +00005778 if (CSI->isAllOnesValue())
Chris Lattnerdf17af12003-08-12 21:53:41 +00005779 return ReplaceInstUsesWith(I, CSI);
5780
Chris Lattner2eefe512004-04-09 19:05:30 +00005781 // Try to fold constant and into select arguments.
5782 if (isa<Constant>(Op0))
5783 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00005784 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00005785 return R;
5786
Chris Lattner120347e2005-05-08 17:34:56 +00005787 // See if we can turn a signed shr into an unsigned shr.
Chris Lattner65b72ba2006-09-18 04:22:48 +00005788 if (I.isArithmeticShift()) {
Reid Spencerb35ae032007-03-23 18:46:34 +00005789 if (MaskedValueIsZero(Op0,
5790 APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()))) {
Reid Spencercc46cdb2007-02-02 14:08:20 +00005791 return BinaryOperator::createLShr(Op0, Op1, I.getName());
Chris Lattner120347e2005-05-08 17:34:56 +00005792 }
5793 }
Jeff Cohen00b168892005-07-27 06:12:32 +00005794
Reid Spencerb83eb642006-10-20 07:07:24 +00005795 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00005796 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
5797 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00005798 return 0;
5799}
5800
Reid Spencerb83eb642006-10-20 07:07:24 +00005801Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00005802 BinaryOperator &I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005803 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00005804
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00005805 // See if we can simplify any instructions used by the instruction whose sole
5806 // purpose is to compute bits we don't care about.
Reid Spencerb35ae032007-03-23 18:46:34 +00005807 uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
5808 APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
5809 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00005810 KnownZero, KnownOne))
5811 return &I;
5812
Chris Lattner4d5542c2006-01-06 07:12:35 +00005813 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
5814 // of a signed value.
5815 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00005816 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00005817 if (I.getOpcode() != Instruction::AShr)
Chris Lattner4d5542c2006-01-06 07:12:35 +00005818 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
5819 else {
Chris Lattner0737c242007-02-02 05:29:55 +00005820 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00005821 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00005822 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00005823 }
5824
5825 // ((X*C1) << C2) == (X * (C1 << C2))
5826 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
5827 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
5828 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
5829 return BinaryOperator::createMul(BO->getOperand(0),
5830 ConstantExpr::getShl(BOOp, Op1));
5831
5832 // Try to fold constant and into select arguments.
5833 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5834 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5835 return R;
5836 if (isa<PHINode>(Op0))
5837 if (Instruction *NV = FoldOpIntoPhi(I))
5838 return NV;
5839
5840 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00005841 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
5842 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
5843 Value *V1, *V2;
5844 ConstantInt *CC;
5845 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00005846 default: break;
5847 case Instruction::Add:
5848 case Instruction::And:
5849 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00005850 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00005851 // These operators commute.
5852 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00005853 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
5854 match(Op0BO->getOperand(1),
Chris Lattner4d5542c2006-01-06 07:12:35 +00005855 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Reid Spencercc46cdb2007-02-02 14:08:20 +00005856 Instruction *YS = BinaryOperator::createShl(
Chris Lattner4d5542c2006-01-06 07:12:35 +00005857 Op0BO->getOperand(0), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00005858 Op0BO->getName());
5859 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00005860 Instruction *X =
5861 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
5862 Op0BO->getOperand(1)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00005863 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00005864 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Zhou Sheng90b96812007-03-30 05:45:18 +00005865 return BinaryOperator::createAnd(X, ConstantInt::get(
5866 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00005867 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00005868
Chris Lattner150f12a2005-09-18 06:30:59 +00005869 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00005870 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00005871 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00005872 match(Op0BOOp1,
5873 m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
Chris Lattner3c698492007-03-05 00:11:19 +00005874 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
5875 V2 == Op1) {
Reid Spencercc46cdb2007-02-02 14:08:20 +00005876 Instruction *YS = BinaryOperator::createShl(
Reid Spencer832254e2007-02-02 02:16:23 +00005877 Op0BO->getOperand(0), Op1,
5878 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00005879 InsertNewInstBefore(YS, I); // (Y << C)
5880 Instruction *XM =
Chris Lattner4d5542c2006-01-06 07:12:35 +00005881 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00005882 V1->getName()+".mask");
5883 InsertNewInstBefore(XM, I); // X & (CC << C)
5884
5885 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
5886 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00005887 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00005888
Reid Spencera07cb7d2007-02-02 14:41:37 +00005889 // FALL THROUGH.
5890 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00005891 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00005892 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5893 match(Op0BO->getOperand(0),
Chris Lattner4d5542c2006-01-06 07:12:35 +00005894 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Reid Spencercc46cdb2007-02-02 14:08:20 +00005895 Instruction *YS = BinaryOperator::createShl(
Reid Spencer832254e2007-02-02 02:16:23 +00005896 Op0BO->getOperand(1), Op1,
5897 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00005898 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00005899 Instruction *X =
Chris Lattner13d4ab42006-05-31 21:14:00 +00005900 BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00005901 Op0BO->getOperand(0)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00005902 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00005903 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Zhou Sheng90b96812007-03-30 05:45:18 +00005904 return BinaryOperator::createAnd(X, ConstantInt::get(
5905 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00005906 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00005907
Chris Lattner13d4ab42006-05-31 21:14:00 +00005908 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00005909 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5910 match(Op0BO->getOperand(0),
5911 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner4d5542c2006-01-06 07:12:35 +00005912 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00005913 cast<BinaryOperator>(Op0BO->getOperand(0))
5914 ->getOperand(0)->hasOneUse()) {
Reid Spencercc46cdb2007-02-02 14:08:20 +00005915 Instruction *YS = BinaryOperator::createShl(
Reid Spencer832254e2007-02-02 02:16:23 +00005916 Op0BO->getOperand(1), Op1,
5917 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00005918 InsertNewInstBefore(YS, I); // (Y << C)
5919 Instruction *XM =
Chris Lattner4d5542c2006-01-06 07:12:35 +00005920 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00005921 V1->getName()+".mask");
5922 InsertNewInstBefore(XM, I); // X & (CC << C)
5923
Chris Lattner13d4ab42006-05-31 21:14:00 +00005924 return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00005925 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00005926
Chris Lattner11021cb2005-09-18 05:12:10 +00005927 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00005928 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00005929 }
5930
5931
5932 // If the operand is an bitwise operator with a constant RHS, and the
5933 // shift is the only use, we can pull it out of the shift.
5934 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
5935 bool isValid = true; // Valid only for And, Or, Xor
5936 bool highBitSet = false; // Transform if high bit of constant set?
5937
5938 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00005939 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00005940 case Instruction::Add:
5941 isValid = isLeftShift;
5942 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00005943 case Instruction::Or:
5944 case Instruction::Xor:
5945 highBitSet = false;
5946 break;
5947 case Instruction::And:
5948 highBitSet = true;
5949 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00005950 }
5951
5952 // If this is a signed shift right, and the high bit is modified
5953 // by the logical operation, do not perform the transformation.
5954 // The highBitSet boolean indicates the value of the high bit of
5955 // the constant which would cause it to be modified for this
5956 // operation.
5957 //
Chris Lattnerb87056f2007-02-05 00:57:54 +00005958 if (isValid && !isLeftShift && I.getOpcode() == Instruction::AShr) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00005959 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00005960 }
5961
5962 if (isValid) {
5963 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
5964
5965 Instruction *NewShift =
Chris Lattner6934a042007-02-11 01:23:03 +00005966 BinaryOperator::create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00005967 InsertNewInstBefore(NewShift, I);
Chris Lattner6934a042007-02-11 01:23:03 +00005968 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00005969
5970 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
5971 NewRHS);
5972 }
5973 }
5974 }
5975 }
5976
Chris Lattnerad0124c2006-01-06 07:52:12 +00005977 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00005978 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
5979 if (ShiftOp && !ShiftOp->isShift())
5980 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00005981
Reid Spencerb83eb642006-10-20 07:07:24 +00005982 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00005983 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00005984 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
5985 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00005986 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
5987 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
5988 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00005989
Zhou Sheng4351c642007-04-02 08:20:41 +00005990 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Reid Spencerb35ae032007-03-23 18:46:34 +00005991 if (AmtSum > TypeBits)
5992 AmtSum = TypeBits;
Chris Lattnerb87056f2007-02-05 00:57:54 +00005993
5994 const IntegerType *Ty = cast<IntegerType>(I.getType());
5995
5996 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00005997 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattnerb87056f2007-02-05 00:57:54 +00005998 return BinaryOperator::create(I.getOpcode(), X,
5999 ConstantInt::get(Ty, AmtSum));
6000 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
6001 I.getOpcode() == Instruction::AShr) {
6002 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
6003 return BinaryOperator::createLShr(X, ConstantInt::get(Ty, AmtSum));
6004 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
6005 I.getOpcode() == Instruction::LShr) {
6006 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
6007 Instruction *Shift =
6008 BinaryOperator::createAShr(X, ConstantInt::get(Ty, AmtSum));
6009 InsertNewInstBefore(Shift, I);
6010
Zhou Shenge9e03f62007-03-28 15:02:20 +00006011 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Reid Spencerb35ae032007-03-23 18:46:34 +00006012 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00006013 }
6014
Chris Lattnerb87056f2007-02-05 00:57:54 +00006015 // Okay, if we get here, one shift must be left, and the other shift must be
6016 // right. See if the amounts are equal.
6017 if (ShiftAmt1 == ShiftAmt2) {
6018 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
6019 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00006020 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Reid Spencerb35ae032007-03-23 18:46:34 +00006021 return BinaryOperator::createAnd(X, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006022 }
6023 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
6024 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00006025 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Reid Spencerb35ae032007-03-23 18:46:34 +00006026 return BinaryOperator::createAnd(X, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006027 }
6028 // We can simplify ((X << C) >>s C) into a trunc + sext.
6029 // NOTE: we could do this for any C, but that would make 'unusual' integer
6030 // types. For now, just stick to ones well-supported by the code
6031 // generators.
6032 const Type *SExtType = 0;
6033 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00006034 case 1 :
6035 case 8 :
6036 case 16 :
6037 case 32 :
6038 case 64 :
6039 case 128:
6040 SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
6041 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00006042 default: break;
6043 }
6044 if (SExtType) {
6045 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
6046 InsertNewInstBefore(NewTrunc, I);
6047 return new SExtInst(NewTrunc, Ty);
6048 }
6049 // Otherwise, we can't handle it yet.
6050 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00006051 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00006052
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006053 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006054 if (I.getOpcode() == Instruction::Shl) {
6055 assert(ShiftOp->getOpcode() == Instruction::LShr ||
6056 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnere8d56c52006-01-07 01:32:28 +00006057 Instruction *Shift =
Chris Lattnerb87056f2007-02-05 00:57:54 +00006058 BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00006059 InsertNewInstBefore(Shift, I);
6060
Reid Spencer55702aa2007-03-25 21:11:44 +00006061 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
6062 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00006063 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00006064
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006065 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006066 if (I.getOpcode() == Instruction::LShr) {
6067 assert(ShiftOp->getOpcode() == Instruction::Shl);
6068 Instruction *Shift =
6069 BinaryOperator::createLShr(X, ConstantInt::get(Ty, ShiftDiff));
6070 InsertNewInstBefore(Shift, I);
Chris Lattnerad0124c2006-01-06 07:52:12 +00006071
Reid Spencerd5e30f02007-03-26 17:18:58 +00006072 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Reid Spencerb35ae032007-03-23 18:46:34 +00006073 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00006074 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00006075
6076 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
6077 } else {
6078 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00006079 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00006080
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006081 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006082 if (I.getOpcode() == Instruction::Shl) {
6083 assert(ShiftOp->getOpcode() == Instruction::LShr ||
6084 ShiftOp->getOpcode() == Instruction::AShr);
6085 Instruction *Shift =
6086 BinaryOperator::create(ShiftOp->getOpcode(), X,
6087 ConstantInt::get(Ty, ShiftDiff));
6088 InsertNewInstBefore(Shift, I);
6089
Reid Spencer55702aa2007-03-25 21:11:44 +00006090 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Reid Spencerb35ae032007-03-23 18:46:34 +00006091 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006092 }
6093
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006094 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006095 if (I.getOpcode() == Instruction::LShr) {
6096 assert(ShiftOp->getOpcode() == Instruction::Shl);
6097 Instruction *Shift =
6098 BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
6099 InsertNewInstBefore(Shift, I);
6100
Reid Spencer68d27cf2007-03-26 23:45:51 +00006101 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Reid Spencerb35ae032007-03-23 18:46:34 +00006102 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006103 }
6104
6105 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00006106 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00006107 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00006108 return 0;
6109}
6110
Chris Lattnera1be5662002-05-02 17:06:02 +00006111
Chris Lattnercfd65102005-10-29 04:36:15 +00006112/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
6113/// expression. If so, decompose it, returning some value X, such that Val is
6114/// X*Scale+Offset.
6115///
6116static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Jeff Cohen86796be2007-04-04 16:58:57 +00006117 int &Offset) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00006118 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00006119 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00006120 Offset = CI->getZExtValue();
6121 Scale = 1;
6122 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattnercfd65102005-10-29 04:36:15 +00006123 } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
6124 if (I->getNumOperands() == 2) {
Reid Spencerb83eb642006-10-20 07:07:24 +00006125 if (ConstantInt *CUI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00006126 if (I->getOpcode() == Instruction::Shl) {
6127 // This is a value scaled by '1 << the shift amt'.
6128 Scale = 1U << CUI->getZExtValue();
6129 Offset = 0;
6130 return I->getOperand(0);
6131 } else if (I->getOpcode() == Instruction::Mul) {
6132 // This value is scaled by 'CUI'.
6133 Scale = CUI->getZExtValue();
6134 Offset = 0;
6135 return I->getOperand(0);
6136 } else if (I->getOpcode() == Instruction::Add) {
6137 // We have X+C. Check to see if we really have (X*C2)+C1,
6138 // where C1 is divisible by C2.
6139 unsigned SubScale;
6140 Value *SubVal =
6141 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
6142 Offset += CUI->getZExtValue();
6143 if (SubScale > 1 && (Offset % SubScale == 0)) {
6144 Scale = SubScale;
6145 return SubVal;
Chris Lattnercfd65102005-10-29 04:36:15 +00006146 }
6147 }
6148 }
6149 }
6150 }
6151
6152 // Otherwise, we can't look past this.
6153 Scale = 1;
6154 Offset = 0;
6155 return Val;
6156}
6157
6158
Chris Lattnerb3f83972005-10-24 06:03:58 +00006159/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
6160/// try to eliminate the cast by moving the type information into the alloc.
Chris Lattnerd3e28342007-04-27 17:44:50 +00006161Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Chris Lattnerb3f83972005-10-24 06:03:58 +00006162 AllocationInst &AI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00006163 const PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattnerb3f83972005-10-24 06:03:58 +00006164
Chris Lattnerb53c2382005-10-24 06:22:12 +00006165 // Remove any uses of AI that are dead.
6166 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner535014f2007-02-15 22:52:10 +00006167
Chris Lattnerb53c2382005-10-24 06:22:12 +00006168 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
6169 Instruction *User = cast<Instruction>(*UI++);
6170 if (isInstructionTriviallyDead(User)) {
6171 while (UI != E && *UI == User)
6172 ++UI; // If this instruction uses AI more than once, don't break UI.
6173
Chris Lattnerb53c2382005-10-24 06:22:12 +00006174 ++NumDeadInst;
Bill Wendlingb7427032006-11-26 09:46:52 +00006175 DOUT << "IC: DCE: " << *User;
Chris Lattnerf22a5c62007-03-02 19:59:19 +00006176 EraseInstFromFunction(*User);
Chris Lattnerb53c2382005-10-24 06:22:12 +00006177 }
6178 }
6179
Chris Lattnerb3f83972005-10-24 06:03:58 +00006180 // Get the type really allocated and the type casted to.
6181 const Type *AllocElTy = AI.getAllocatedType();
6182 const Type *CastElTy = PTy->getElementType();
6183 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00006184
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00006185 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
6186 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00006187 if (CastElTyAlign < AllocElTyAlign) return 0;
6188
Chris Lattner39387a52005-10-24 06:35:18 +00006189 // If the allocation has multiple uses, only promote it if we are strictly
6190 // increasing the alignment of the resultant allocation. If we keep it the
6191 // same, we open the door to infinite loops of various kinds.
6192 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
6193
Chris Lattnerb3f83972005-10-24 06:03:58 +00006194 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
6195 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00006196 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00006197
Chris Lattner455fcc82005-10-29 03:19:53 +00006198 // See if we can satisfy the modulus by pulling a scale out of the array
6199 // size argument.
Jeff Cohen86796be2007-04-04 16:58:57 +00006200 unsigned ArraySizeScale;
6201 int ArrayOffset;
Chris Lattnercfd65102005-10-29 04:36:15 +00006202 Value *NumElements = // See if the array size is a decomposable linear expr.
6203 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
6204
Chris Lattner455fcc82005-10-29 03:19:53 +00006205 // If we can now satisfy the modulus, by using a non-1 scale, we really can
6206 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00006207 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
6208 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00006209
Chris Lattner455fcc82005-10-29 03:19:53 +00006210 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
6211 Value *Amt = 0;
6212 if (Scale == 1) {
6213 Amt = NumElements;
6214 } else {
Reid Spencerb83eb642006-10-20 07:07:24 +00006215 // If the allocation size is constant, form a constant mul expression
Reid Spencerc5b206b2006-12-31 05:48:39 +00006216 Amt = ConstantInt::get(Type::Int32Ty, Scale);
6217 if (isa<ConstantInt>(NumElements))
Zhou Sheng4a1822a2007-04-02 13:45:30 +00006218 Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
Reid Spencerb83eb642006-10-20 07:07:24 +00006219 // otherwise multiply the amount and the number of elements
Chris Lattner455fcc82005-10-29 03:19:53 +00006220 else if (Scale != 1) {
6221 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
6222 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattner8142b0a2005-10-27 06:12:00 +00006223 }
Chris Lattner0ddac2a2005-10-27 05:53:56 +00006224 }
6225
Jeff Cohen86796be2007-04-04 16:58:57 +00006226 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
6227 Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
Chris Lattnercfd65102005-10-29 04:36:15 +00006228 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
6229 Amt = InsertNewInstBefore(Tmp, AI);
6230 }
6231
Chris Lattnerb3f83972005-10-24 06:03:58 +00006232 AllocationInst *New;
6233 if (isa<MallocInst>(AI))
Chris Lattner6934a042007-02-11 01:23:03 +00006234 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00006235 else
Chris Lattner6934a042007-02-11 01:23:03 +00006236 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00006237 InsertNewInstBefore(New, AI);
Chris Lattner6934a042007-02-11 01:23:03 +00006238 New->takeName(&AI);
Chris Lattner39387a52005-10-24 06:35:18 +00006239
6240 // If the allocation has multiple uses, insert a cast and change all things
6241 // that used it to use the new cast. This will also hack on CI, but it will
6242 // die soon.
6243 if (!AI.hasOneUse()) {
6244 AddUsesToWorkList(AI);
Reid Spencer3da59db2006-11-27 01:05:10 +00006245 // New is the allocation instruction, pointer typed. AI is the original
6246 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
6247 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner39387a52005-10-24 06:35:18 +00006248 InsertNewInstBefore(NewCast, AI);
6249 AI.replaceAllUsesWith(NewCast);
6250 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00006251 return ReplaceInstUsesWith(CI, New);
6252}
6253
Chris Lattner70074e02006-05-13 02:06:03 +00006254/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerc739cd62007-03-03 05:27:34 +00006255/// and return it as type Ty without inserting any new casts and without
6256/// changing the computed value. This is used by code that tries to decide
6257/// whether promoting or shrinking integer operations to wider or smaller types
6258/// will allow us to eliminate a truncate or extend.
6259///
6260/// This is a truncation operation if Ty is smaller than V->getType(), or an
6261/// extension operation if Ty is larger.
6262static bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
Chris Lattner70074e02006-05-13 02:06:03 +00006263 int &NumCastsRemoved) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00006264 // We can always evaluate constants in another type.
6265 if (isa<ConstantInt>(V))
6266 return true;
Chris Lattner70074e02006-05-13 02:06:03 +00006267
6268 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006269 if (!I) return false;
6270
6271 const IntegerType *OrigTy = cast<IntegerType>(V->getType());
Chris Lattner70074e02006-05-13 02:06:03 +00006272
6273 switch (I->getOpcode()) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00006274 case Instruction::Add:
6275 case Instruction::Sub:
Chris Lattner70074e02006-05-13 02:06:03 +00006276 case Instruction::And:
6277 case Instruction::Or:
6278 case Instruction::Xor:
Chris Lattnerc739cd62007-03-03 05:27:34 +00006279 if (!I->hasOneUse()) return false;
Chris Lattner70074e02006-05-13 02:06:03 +00006280 // These operators can all arbitrarily be extended or truncated.
6281 return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved) &&
6282 CanEvaluateInDifferentType(I->getOperand(1), Ty, NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006283
Chris Lattner46b96052006-11-29 07:18:39 +00006284 case Instruction::Shl:
Chris Lattnerc739cd62007-03-03 05:27:34 +00006285 if (!I->hasOneUse()) return false;
6286 // If we are truncating the result of this SHL, and if it's a shift of a
6287 // constant amount, we can always perform a SHL in a smaller type.
6288 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00006289 uint32_t BitWidth = Ty->getBitWidth();
6290 if (BitWidth < OrigTy->getBitWidth() &&
6291 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattnerc739cd62007-03-03 05:27:34 +00006292 return CanEvaluateInDifferentType(I->getOperand(0), Ty,NumCastsRemoved);
6293 }
6294 break;
6295 case Instruction::LShr:
6296 if (!I->hasOneUse()) return false;
6297 // If this is a truncate of a logical shr, we can truncate it to a smaller
6298 // lshr iff we know that the bits we would otherwise be shifting in are
6299 // already zeros.
6300 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00006301 uint32_t OrigBitWidth = OrigTy->getBitWidth();
6302 uint32_t BitWidth = Ty->getBitWidth();
6303 if (BitWidth < OrigBitWidth &&
Chris Lattnerc739cd62007-03-03 05:27:34 +00006304 MaskedValueIsZero(I->getOperand(0),
Zhou Sheng302748d2007-03-30 17:20:39 +00006305 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
6306 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattnere34e9a22007-04-14 23:32:02 +00006307 return CanEvaluateInDifferentType(I->getOperand(0), Ty,NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006308 }
6309 }
Chris Lattner46b96052006-11-29 07:18:39 +00006310 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00006311 case Instruction::Trunc:
6312 case Instruction::ZExt:
6313 case Instruction::SExt:
Chris Lattner70074e02006-05-13 02:06:03 +00006314 // If this is a cast from the destination type, we can trivially eliminate
6315 // it, and this will remove a cast overall.
6316 if (I->getOperand(0)->getType() == Ty) {
Chris Lattnerd2280182006-06-28 17:34:50 +00006317 // If the first operand is itself a cast, and is eliminable, do not count
6318 // this as an eliminable cast. We would prefer to eliminate those two
6319 // casts first.
Reid Spencer3ed469c2006-11-02 20:25:50 +00006320 if (isa<CastInst>(I->getOperand(0)))
Chris Lattnerd2280182006-06-28 17:34:50 +00006321 return true;
6322
Chris Lattner70074e02006-05-13 02:06:03 +00006323 ++NumCastsRemoved;
6324 return true;
6325 }
Reid Spencer3da59db2006-11-27 01:05:10 +00006326 break;
6327 default:
Chris Lattner70074e02006-05-13 02:06:03 +00006328 // TODO: Can handle more cases here.
6329 break;
6330 }
6331
6332 return false;
6333}
6334
6335/// EvaluateInDifferentType - Given an expression that
6336/// CanEvaluateInDifferentType returns true for, actually insert the code to
6337/// evaluate the expression.
Reid Spencerc55b2432006-12-13 18:21:21 +00006338Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerc739cd62007-03-03 05:27:34 +00006339 bool isSigned) {
Chris Lattner70074e02006-05-13 02:06:03 +00006340 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencerc55b2432006-12-13 18:21:21 +00006341 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Chris Lattner70074e02006-05-13 02:06:03 +00006342
6343 // Otherwise, it must be an instruction.
6344 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00006345 Instruction *Res = 0;
Chris Lattner70074e02006-05-13 02:06:03 +00006346 switch (I->getOpcode()) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00006347 case Instruction::Add:
6348 case Instruction::Sub:
Chris Lattner70074e02006-05-13 02:06:03 +00006349 case Instruction::And:
6350 case Instruction::Or:
Chris Lattnerc739cd62007-03-03 05:27:34 +00006351 case Instruction::Xor:
Chris Lattner46b96052006-11-29 07:18:39 +00006352 case Instruction::AShr:
6353 case Instruction::LShr:
6354 case Instruction::Shl: {
Reid Spencerc55b2432006-12-13 18:21:21 +00006355 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006356 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
6357 Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
6358 LHS, RHS, I->getName());
Chris Lattner46b96052006-11-29 07:18:39 +00006359 break;
6360 }
Reid Spencer3da59db2006-11-27 01:05:10 +00006361 case Instruction::Trunc:
6362 case Instruction::ZExt:
6363 case Instruction::SExt:
6364 case Instruction::BitCast:
6365 // If the source type of the cast is the type we're trying for then we can
6366 // just return the source. There's no need to insert it because its not new.
Chris Lattner70074e02006-05-13 02:06:03 +00006367 if (I->getOperand(0)->getType() == Ty)
6368 return I->getOperand(0);
6369
Reid Spencer3da59db2006-11-27 01:05:10 +00006370 // Some other kind of cast, which shouldn't happen, so just ..
6371 // FALL THROUGH
6372 default:
Chris Lattner70074e02006-05-13 02:06:03 +00006373 // TODO: Can handle more cases here.
6374 assert(0 && "Unreachable!");
6375 break;
6376 }
6377
6378 return InsertNewInstBefore(Res, *I);
6379}
6380
Reid Spencer3da59db2006-11-27 01:05:10 +00006381/// @brief Implement the transforms common to all CastInst visitors.
6382Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00006383 Value *Src = CI.getOperand(0);
6384
Reid Spencer3da59db2006-11-27 01:05:10 +00006385 // Casting undef to anything results in undef so might as just replace it and
6386 // get rid of the cast.
Chris Lattnere87597f2004-10-16 18:11:37 +00006387 if (isa<UndefValue>(Src)) // cast undef -> undef
6388 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
6389
Dan Gohman23d9d272007-05-11 21:10:54 +00006390 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
Reid Spencer3da59db2006-11-27 01:05:10 +00006391 // eliminate it now.
Chris Lattner6e7ba452005-01-01 16:22:27 +00006392 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00006393 if (Instruction::CastOps opc =
6394 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
6395 // The first cast (CSrc) is eliminable so we need to fix up or replace
6396 // the second cast (CI). CSrc will then have a good chance of being dead.
6397 return CastInst::create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner8fd217c2002-08-02 20:00:25 +00006398 }
6399 }
Chris Lattnera710ddc2004-05-25 04:29:21 +00006400
Reid Spencer3da59db2006-11-27 01:05:10 +00006401 // If we are casting a select then fold the cast into the select
Chris Lattner6e7ba452005-01-01 16:22:27 +00006402 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
6403 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
6404 return NV;
Reid Spencer3da59db2006-11-27 01:05:10 +00006405
6406 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner4e998b22004-09-29 05:07:12 +00006407 if (isa<PHINode>(Src))
6408 if (Instruction *NV = FoldOpIntoPhi(CI))
6409 return NV;
Chris Lattner9fb92132006-04-12 18:09:35 +00006410
Reid Spencer3da59db2006-11-27 01:05:10 +00006411 return 0;
6412}
6413
Chris Lattnerd3e28342007-04-27 17:44:50 +00006414/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
6415Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
6416 Value *Src = CI.getOperand(0);
6417
Chris Lattnerd3e28342007-04-27 17:44:50 +00006418 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner9bc14642007-04-28 00:57:34 +00006419 // If casting the result of a getelementptr instruction with no offset, turn
6420 // this into a cast of the original pointer!
Chris Lattnerd3e28342007-04-27 17:44:50 +00006421 if (GEP->hasAllZeroIndices()) {
6422 // Changing the cast operand is usually not a good idea but it is safe
6423 // here because the pointer operand is being replaced with another
6424 // pointer operand so the opcode doesn't need to change.
Chris Lattner9bc14642007-04-28 00:57:34 +00006425 AddToWorkList(GEP);
Chris Lattnerd3e28342007-04-27 17:44:50 +00006426 CI.setOperand(0, GEP->getOperand(0));
6427 return &CI;
6428 }
Chris Lattner9bc14642007-04-28 00:57:34 +00006429
6430 // If the GEP has a single use, and the base pointer is a bitcast, and the
6431 // GEP computes a constant offset, see if we can convert these three
6432 // instructions into fewer. This typically happens with unions and other
6433 // non-type-safe code.
6434 if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
6435 if (GEP->hasAllConstantIndices()) {
6436 // We are guaranteed to get a constant from EmitGEPOffset.
6437 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
6438 int64_t Offset = OffsetV->getSExtValue();
6439
6440 // Get the base pointer input of the bitcast, and the type it points to.
6441 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
6442 const Type *GEPIdxTy =
6443 cast<PointerType>(OrigBase->getType())->getElementType();
6444 if (GEPIdxTy->isSized()) {
6445 SmallVector<Value*, 8> NewIndices;
6446
Chris Lattnerc42e2262007-05-05 01:59:31 +00006447 // Start with the index over the outer type. Note that the type size
6448 // might be zero (even if the offset isn't zero) if the indexed type
6449 // is something like [0 x {int, int}]
Chris Lattner9bc14642007-04-28 00:57:34 +00006450 const Type *IntPtrTy = TD->getIntPtrType();
Chris Lattnerc42e2262007-05-05 01:59:31 +00006451 int64_t FirstIdx = 0;
6452 if (int64_t TySize = TD->getTypeSize(GEPIdxTy)) {
6453 FirstIdx = Offset/TySize;
6454 Offset %= TySize;
Chris Lattner9bc14642007-04-28 00:57:34 +00006455
Chris Lattnerc42e2262007-05-05 01:59:31 +00006456 // Handle silly modulus not returning values values [0..TySize).
6457 if (Offset < 0) {
6458 --FirstIdx;
6459 Offset += TySize;
6460 assert(Offset >= 0);
6461 }
Chris Lattnerd717c182007-05-05 22:32:24 +00006462 assert((uint64_t)Offset < (uint64_t)TySize &&"Out of range offset");
Chris Lattner9bc14642007-04-28 00:57:34 +00006463 }
6464
6465 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner9bc14642007-04-28 00:57:34 +00006466
6467 // Index into the types. If we fail, set OrigBase to null.
6468 while (Offset) {
6469 if (const StructType *STy = dyn_cast<StructType>(GEPIdxTy)) {
6470 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattner6b6aef82007-05-15 00:16:00 +00006471 if (Offset < (int64_t)SL->getSizeInBytes()) {
6472 unsigned Elt = SL->getElementContainingOffset(Offset);
6473 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
Chris Lattner9bc14642007-04-28 00:57:34 +00006474
Chris Lattner6b6aef82007-05-15 00:16:00 +00006475 Offset -= SL->getElementOffset(Elt);
6476 GEPIdxTy = STy->getElementType(Elt);
6477 } else {
6478 // Otherwise, we can't index into this, bail out.
6479 Offset = 0;
6480 OrigBase = 0;
6481 }
Chris Lattner9bc14642007-04-28 00:57:34 +00006482 } else if (isa<ArrayType>(GEPIdxTy) || isa<VectorType>(GEPIdxTy)) {
6483 const SequentialType *STy = cast<SequentialType>(GEPIdxTy);
Chris Lattner6b6aef82007-05-15 00:16:00 +00006484 if (uint64_t EltSize = TD->getTypeSize(STy->getElementType())) {
6485 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
6486 Offset %= EltSize;
6487 } else {
6488 NewIndices.push_back(ConstantInt::get(IntPtrTy, 0));
6489 }
Chris Lattner9bc14642007-04-28 00:57:34 +00006490 GEPIdxTy = STy->getElementType();
6491 } else {
6492 // Otherwise, we can't index into this, bail out.
6493 Offset = 0;
6494 OrigBase = 0;
6495 }
6496 }
6497 if (OrigBase) {
6498 // If we were able to index down into an element, create the GEP
6499 // and bitcast the result. This eliminates one bitcast, potentially
6500 // two.
6501 Instruction *NGEP = new GetElementPtrInst(OrigBase, &NewIndices[0],
6502 NewIndices.size(), "");
6503 InsertNewInstBefore(NGEP, CI);
6504 NGEP->takeName(GEP);
6505
Chris Lattner9bc14642007-04-28 00:57:34 +00006506 if (isa<BitCastInst>(CI))
6507 return new BitCastInst(NGEP, CI.getType());
6508 assert(isa<PtrToIntInst>(CI));
6509 return new PtrToIntInst(NGEP, CI.getType());
6510 }
6511 }
6512 }
6513 }
Chris Lattnerd3e28342007-04-27 17:44:50 +00006514 }
6515
6516 return commonCastTransforms(CI);
6517}
6518
6519
6520
Chris Lattnerc739cd62007-03-03 05:27:34 +00006521/// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
6522/// integer types. This function implements the common transforms for all those
Reid Spencer3da59db2006-11-27 01:05:10 +00006523/// cases.
6524/// @brief Implement the transforms common to CastInst with integer operands
6525Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
6526 if (Instruction *Result = commonCastTransforms(CI))
6527 return Result;
6528
6529 Value *Src = CI.getOperand(0);
6530 const Type *SrcTy = Src->getType();
6531 const Type *DestTy = CI.getType();
Zhou Sheng4351c642007-04-02 08:20:41 +00006532 uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
6533 uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00006534
Reid Spencer3da59db2006-11-27 01:05:10 +00006535 // See if we can simplify any instructions used by the LHS whose sole
6536 // purpose is to compute bits we don't care about.
Reid Spencerad6676e2007-03-22 20:56:53 +00006537 APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
6538 if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
Reid Spencer3da59db2006-11-27 01:05:10 +00006539 KnownZero, KnownOne))
6540 return &CI;
6541
6542 // If the source isn't an instruction or has more than one use then we
6543 // can't do anything more.
Reid Spencere4d87aa2006-12-23 06:05:41 +00006544 Instruction *SrcI = dyn_cast<Instruction>(Src);
6545 if (!SrcI || !Src->hasOneUse())
Reid Spencer3da59db2006-11-27 01:05:10 +00006546 return 0;
6547
Chris Lattnerc739cd62007-03-03 05:27:34 +00006548 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00006549 int NumCastsRemoved = 0;
Chris Lattnerc739cd62007-03-03 05:27:34 +00006550 if (!isa<BitCastInst>(CI) &&
6551 CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
6552 NumCastsRemoved)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00006553 // If this cast is a truncate, evaluting in a different type always
6554 // eliminates the cast, so it is always a win. If this is a noop-cast
6555 // this just removes a noop cast which isn't pointful, but simplifies
6556 // the code. If this is a zero-extension, we need to do an AND to
6557 // maintain the clear top-part of the computation, so we require that
6558 // the input have eliminated at least one cast. If this is a sign
6559 // extension, we insert two new casts (to do the extension) so we
6560 // require that two casts have been eliminated.
Chris Lattnerc739cd62007-03-03 05:27:34 +00006561 bool DoXForm;
6562 switch (CI.getOpcode()) {
6563 default:
6564 // All the others use floating point so we shouldn't actually
6565 // get here because of the check above.
6566 assert(0 && "Unknown cast type");
6567 case Instruction::Trunc:
6568 DoXForm = true;
6569 break;
6570 case Instruction::ZExt:
6571 DoXForm = NumCastsRemoved >= 1;
6572 break;
6573 case Instruction::SExt:
6574 DoXForm = NumCastsRemoved >= 2;
6575 break;
6576 case Instruction::BitCast:
6577 DoXForm = false;
6578 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00006579 }
6580
6581 if (DoXForm) {
Reid Spencerc55b2432006-12-13 18:21:21 +00006582 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
6583 CI.getOpcode() == Instruction::SExt);
Reid Spencer3da59db2006-11-27 01:05:10 +00006584 assert(Res->getType() == DestTy);
6585 switch (CI.getOpcode()) {
6586 default: assert(0 && "Unknown cast type!");
6587 case Instruction::Trunc:
6588 case Instruction::BitCast:
6589 // Just replace this cast with the result.
6590 return ReplaceInstUsesWith(CI, Res);
6591 case Instruction::ZExt: {
6592 // We need to emit an AND to clear the high bits.
6593 assert(SrcBitSize < DestBitSize && "Not a zext?");
Chris Lattnercd1d6d52007-04-02 05:48:58 +00006594 Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
6595 SrcBitSize));
Reid Spencer3da59db2006-11-27 01:05:10 +00006596 return BinaryOperator::createAnd(Res, C);
6597 }
6598 case Instruction::SExt:
6599 // We need to emit a cast to truncate, then a cast to sext.
6600 return CastInst::create(Instruction::SExt,
Reid Spencer17212df2006-12-12 09:18:51 +00006601 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
6602 CI), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00006603 }
6604 }
6605 }
6606
6607 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
6608 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
6609
6610 switch (SrcI->getOpcode()) {
6611 case Instruction::Add:
6612 case Instruction::Mul:
6613 case Instruction::And:
6614 case Instruction::Or:
6615 case Instruction::Xor:
Chris Lattner01deb9d2007-04-03 17:43:25 +00006616 // If we are discarding information, rewrite.
Reid Spencer3da59db2006-11-27 01:05:10 +00006617 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
6618 // Don't insert two casts if they cannot be eliminated. We allow
6619 // two casts to be inserted if the sizes are the same. This could
6620 // only be converting signedness, which is a noop.
6621 if (DestBitSize == SrcBitSize ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00006622 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
6623 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer7eb76382006-12-13 17:19:09 +00006624 Instruction::CastOps opcode = CI.getOpcode();
Reid Spencer17212df2006-12-12 09:18:51 +00006625 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
6626 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
6627 return BinaryOperator::create(
6628 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00006629 }
6630 }
6631
6632 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
6633 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
6634 SrcI->getOpcode() == Instruction::Xor &&
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006635 Op1 == ConstantInt::getTrue() &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00006636 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Reid Spencer17212df2006-12-12 09:18:51 +00006637 Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00006638 return BinaryOperator::createXor(New, ConstantInt::get(CI.getType(), 1));
6639 }
6640 break;
6641 case Instruction::SDiv:
6642 case Instruction::UDiv:
6643 case Instruction::SRem:
6644 case Instruction::URem:
6645 // If we are just changing the sign, rewrite.
6646 if (DestBitSize == SrcBitSize) {
6647 // Don't insert two casts if they cannot be eliminated. We allow
6648 // two casts to be inserted if the sizes are the same. This could
6649 // only be converting signedness, which is a noop.
Reid Spencere4d87aa2006-12-23 06:05:41 +00006650 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
6651 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer17212df2006-12-12 09:18:51 +00006652 Value *Op0c = InsertOperandCastBefore(Instruction::BitCast,
6653 Op0, DestTy, SrcI);
6654 Value *Op1c = InsertOperandCastBefore(Instruction::BitCast,
6655 Op1, DestTy, SrcI);
Reid Spencer3da59db2006-11-27 01:05:10 +00006656 return BinaryOperator::create(
6657 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
6658 }
6659 }
6660 break;
6661
6662 case Instruction::Shl:
6663 // Allow changing the sign of the source operand. Do not allow
6664 // changing the size of the shift, UNLESS the shift amount is a
6665 // constant. We must not change variable sized shifts to a smaller
6666 // size, because it is undefined to shift more bits out than exist
6667 // in the value.
6668 if (DestBitSize == SrcBitSize ||
6669 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
Reid Spencer17212df2006-12-12 09:18:51 +00006670 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
6671 Instruction::BitCast : Instruction::Trunc);
6672 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
Reid Spencer832254e2007-02-02 02:16:23 +00006673 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
Reid Spencercc46cdb2007-02-02 14:08:20 +00006674 return BinaryOperator::createShl(Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00006675 }
6676 break;
6677 case Instruction::AShr:
6678 // If this is a signed shr, and if all bits shifted in are about to be
6679 // truncated off, turn it into an unsigned shr to allow greater
6680 // simplifications.
6681 if (DestBitSize < SrcBitSize &&
6682 isa<ConstantInt>(Op1)) {
Zhou Sheng302748d2007-03-30 17:20:39 +00006683 uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
Reid Spencer3da59db2006-11-27 01:05:10 +00006684 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
6685 // Insert the new logical shift right.
Reid Spencercc46cdb2007-02-02 14:08:20 +00006686 return BinaryOperator::createLShr(Op0, Op1);
Reid Spencer3da59db2006-11-27 01:05:10 +00006687 }
6688 }
6689 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00006690 }
6691 return 0;
6692}
6693
Chris Lattner8a9f5712007-04-11 06:57:46 +00006694Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00006695 if (Instruction *Result = commonIntCastTransforms(CI))
6696 return Result;
6697
6698 Value *Src = CI.getOperand(0);
6699 const Type *Ty = CI.getType();
Zhou Sheng4351c642007-04-02 08:20:41 +00006700 uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
6701 uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
Chris Lattner6aa5eb12006-11-29 07:04:07 +00006702
6703 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
6704 switch (SrcI->getOpcode()) {
6705 default: break;
6706 case Instruction::LShr:
6707 // We can shrink lshr to something smaller if we know the bits shifted in
6708 // are already zeros.
6709 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00006710 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00006711
6712 // Get a mask for the bits shifting in.
Zhou Shenge82fca02007-03-28 09:19:01 +00006713 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
Reid Spencer17212df2006-12-12 09:18:51 +00006714 Value* SrcIOp0 = SrcI->getOperand(0);
6715 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00006716 if (ShAmt >= DestBitWidth) // All zeros.
6717 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
6718
6719 // Okay, we can shrink this. Truncate the input, then return a new
6720 // shift.
Reid Spencer832254e2007-02-02 02:16:23 +00006721 Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
6722 Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
6723 Ty, CI);
Reid Spencercc46cdb2007-02-02 14:08:20 +00006724 return BinaryOperator::createLShr(V1, V2);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00006725 }
Chris Lattnere13ab2a2006-12-05 01:26:29 +00006726 } else { // This is a variable shr.
6727
6728 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
6729 // more LLVM instructions, but allows '1 << Y' to be hoisted if
6730 // loop-invariant and CSE'd.
Reid Spencer4fe16d62007-01-11 18:21:29 +00006731 if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
Chris Lattnere13ab2a2006-12-05 01:26:29 +00006732 Value *One = ConstantInt::get(SrcI->getType(), 1);
6733
Reid Spencer832254e2007-02-02 02:16:23 +00006734 Value *V = InsertNewInstBefore(
Reid Spencercc46cdb2007-02-02 14:08:20 +00006735 BinaryOperator::createShl(One, SrcI->getOperand(1),
Reid Spencer832254e2007-02-02 02:16:23 +00006736 "tmp"), CI);
Chris Lattnere13ab2a2006-12-05 01:26:29 +00006737 V = InsertNewInstBefore(BinaryOperator::createAnd(V,
6738 SrcI->getOperand(0),
6739 "tmp"), CI);
6740 Value *Zero = Constant::getNullValue(V->getType());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006741 return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
Chris Lattnere13ab2a2006-12-05 01:26:29 +00006742 }
Chris Lattner6aa5eb12006-11-29 07:04:07 +00006743 }
6744 break;
6745 }
6746 }
6747
6748 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00006749}
6750
Chris Lattner8a9f5712007-04-11 06:57:46 +00006751Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00006752 // If one of the common conversion will work ..
6753 if (Instruction *Result = commonIntCastTransforms(CI))
6754 return Result;
6755
6756 Value *Src = CI.getOperand(0);
6757
6758 // If this is a cast of a cast
6759 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00006760 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
6761 // types and if the sizes are just right we can convert this into a logical
6762 // 'and' which will be much cheaper than the pair of casts.
6763 if (isa<TruncInst>(CSrc)) {
6764 // Get the sizes of the types involved
6765 Value *A = CSrc->getOperand(0);
Zhou Sheng4351c642007-04-02 08:20:41 +00006766 uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
6767 uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
6768 uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00006769 // If we're actually extending zero bits and the trunc is a no-op
6770 if (MidSize < DstSize && SrcSize == DstSize) {
6771 // Replace both of the casts with an And of the type mask.
Zhou Shenge82fca02007-03-28 09:19:01 +00006772 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Reid Spencerad6676e2007-03-22 20:56:53 +00006773 Constant *AndConst = ConstantInt::get(AndValue);
Reid Spencer3da59db2006-11-27 01:05:10 +00006774 Instruction *And =
6775 BinaryOperator::createAnd(CSrc->getOperand(0), AndConst);
6776 // Unfortunately, if the type changed, we need to cast it back.
6777 if (And->getType() != CI.getType()) {
6778 And->setName(CSrc->getName()+".mask");
6779 InsertNewInstBefore(And, CI);
Reid Spencerd977d862006-12-12 23:36:14 +00006780 And = CastInst::createIntegerCast(And, CI.getType(), false/*ZExt*/);
Reid Spencer3da59db2006-11-27 01:05:10 +00006781 }
6782 return And;
6783 }
6784 }
6785 }
6786
Chris Lattner66bc3252007-04-11 05:45:39 +00006787 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
6788 // If we are just checking for a icmp eq of a single bit and zext'ing it
6789 // to an integer, then shift the bit to the appropriate place and then
6790 // cast to integer to avoid the comparison.
6791 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
Chris Lattnerba417832007-04-11 06:12:58 +00006792 const APInt &Op1CV = Op1C->getValue();
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00006793
6794 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
6795 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
6796 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
6797 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
6798 Value *In = ICI->getOperand(0);
6799 Value *Sh = ConstantInt::get(In->getType(),
6800 In->getType()->getPrimitiveSizeInBits()-1);
6801 In = InsertNewInstBefore(BinaryOperator::createLShr(In, Sh,
Chris Lattnere34e9a22007-04-14 23:32:02 +00006802 In->getName()+".lobit"),
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00006803 CI);
6804 if (In->getType() != CI.getType())
6805 In = CastInst::createIntegerCast(In, CI.getType(),
6806 false/*ZExt*/, "tmp", &CI);
6807
6808 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
6809 Constant *One = ConstantInt::get(In->getType(), 1);
6810 In = InsertNewInstBefore(BinaryOperator::createXor(In, One,
Chris Lattnere34e9a22007-04-14 23:32:02 +00006811 In->getName()+".not"),
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00006812 CI);
6813 }
6814
6815 return ReplaceInstUsesWith(CI, In);
6816 }
6817
6818
6819
Chris Lattnerba417832007-04-11 06:12:58 +00006820 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
6821 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
6822 // zext (X == 1) to i32 --> X iff X has only the low bit set.
6823 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
6824 // zext (X != 0) to i32 --> X iff X has only the low bit set.
6825 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
6826 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
6827 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
Chris Lattner66bc3252007-04-11 05:45:39 +00006828 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
6829 // This only works for EQ and NE
6830 ICI->isEquality()) {
6831 // If Op1C some other power of two, convert:
6832 uint32_t BitWidth = Op1C->getType()->getBitWidth();
6833 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
6834 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
6835 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
6836
6837 APInt KnownZeroMask(~KnownZero);
6838 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
6839 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
6840 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
6841 // (X&4) == 2 --> false
6842 // (X&4) != 2 --> true
6843 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
6844 Res = ConstantExpr::getZExt(Res, CI.getType());
6845 return ReplaceInstUsesWith(CI, Res);
6846 }
6847
6848 uint32_t ShiftAmt = KnownZeroMask.logBase2();
6849 Value *In = ICI->getOperand(0);
6850 if (ShiftAmt) {
6851 // Perform a logical shr by shiftamt.
6852 // Insert the shift to put the result in the low bit.
6853 In = InsertNewInstBefore(
6854 BinaryOperator::createLShr(In,
6855 ConstantInt::get(In->getType(), ShiftAmt),
6856 In->getName()+".lobit"), CI);
6857 }
6858
6859 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
6860 Constant *One = ConstantInt::get(In->getType(), 1);
6861 In = BinaryOperator::createXor(In, One, "tmp");
6862 InsertNewInstBefore(cast<Instruction>(In), CI);
6863 }
6864
6865 if (CI.getType() == In->getType())
6866 return ReplaceInstUsesWith(CI, In);
6867 else
6868 return CastInst::createIntegerCast(In, CI.getType(), false/*ZExt*/);
6869 }
6870 }
6871 }
6872 }
Reid Spencer3da59db2006-11-27 01:05:10 +00006873 return 0;
6874}
6875
Chris Lattner8a9f5712007-04-11 06:57:46 +00006876Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattnerba417832007-04-11 06:12:58 +00006877 if (Instruction *I = commonIntCastTransforms(CI))
6878 return I;
6879
Chris Lattner8a9f5712007-04-11 06:57:46 +00006880 Value *Src = CI.getOperand(0);
6881
6882 // sext (x <s 0) -> ashr x, 31 -> all ones if signed
6883 // sext (x >s -1) -> ashr x, 31 -> all ones if not signed
6884 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
6885 // If we are just checking for a icmp eq of a single bit and zext'ing it
6886 // to an integer, then shift the bit to the appropriate place and then
6887 // cast to integer to avoid the comparison.
6888 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
6889 const APInt &Op1CV = Op1C->getValue();
6890
6891 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
6892 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
6893 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
6894 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
6895 Value *In = ICI->getOperand(0);
6896 Value *Sh = ConstantInt::get(In->getType(),
6897 In->getType()->getPrimitiveSizeInBits()-1);
6898 In = InsertNewInstBefore(BinaryOperator::createAShr(In, Sh,
Chris Lattnere34e9a22007-04-14 23:32:02 +00006899 In->getName()+".lobit"),
Chris Lattner8a9f5712007-04-11 06:57:46 +00006900 CI);
6901 if (In->getType() != CI.getType())
6902 In = CastInst::createIntegerCast(In, CI.getType(),
6903 true/*SExt*/, "tmp", &CI);
6904
6905 if (ICI->getPredicate() == ICmpInst::ICMP_SGT)
6906 In = InsertNewInstBefore(BinaryOperator::createNot(In,
6907 In->getName()+".not"), CI);
6908
6909 return ReplaceInstUsesWith(CI, In);
6910 }
6911 }
6912 }
6913
Chris Lattnerba417832007-04-11 06:12:58 +00006914 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00006915}
6916
6917Instruction *InstCombiner::visitFPTrunc(CastInst &CI) {
6918 return commonCastTransforms(CI);
6919}
6920
6921Instruction *InstCombiner::visitFPExt(CastInst &CI) {
6922 return commonCastTransforms(CI);
6923}
6924
6925Instruction *InstCombiner::visitFPToUI(CastInst &CI) {
Reid Spencer44c030a2006-11-30 23:13:36 +00006926 return commonCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00006927}
6928
6929Instruction *InstCombiner::visitFPToSI(CastInst &CI) {
Reid Spencer44c030a2006-11-30 23:13:36 +00006930 return commonCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00006931}
6932
6933Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
6934 return commonCastTransforms(CI);
6935}
6936
6937Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
6938 return commonCastTransforms(CI);
6939}
6940
6941Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00006942 return commonPointerCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00006943}
6944
6945Instruction *InstCombiner::visitIntToPtr(CastInst &CI) {
6946 return commonCastTransforms(CI);
6947}
6948
Chris Lattnerd3e28342007-04-27 17:44:50 +00006949Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00006950 // If the operands are integer typed then apply the integer transforms,
6951 // otherwise just apply the common ones.
6952 Value *Src = CI.getOperand(0);
6953 const Type *SrcTy = Src->getType();
6954 const Type *DestTy = CI.getType();
6955
Chris Lattner42a75512007-01-15 02:27:26 +00006956 if (SrcTy->isInteger() && DestTy->isInteger()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00006957 if (Instruction *Result = commonIntCastTransforms(CI))
6958 return Result;
Chris Lattnerd3e28342007-04-27 17:44:50 +00006959 } else if (isa<PointerType>(SrcTy)) {
6960 if (Instruction *I = commonPointerCastTransforms(CI))
6961 return I;
Reid Spencer3da59db2006-11-27 01:05:10 +00006962 } else {
6963 if (Instruction *Result = commonCastTransforms(CI))
6964 return Result;
6965 }
6966
6967
6968 // Get rid of casts from one type to the same type. These are useless and can
6969 // be replaced by the operand.
6970 if (DestTy == Src->getType())
6971 return ReplaceInstUsesWith(CI, Src);
6972
Reid Spencer3da59db2006-11-27 01:05:10 +00006973 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00006974 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
6975 const Type *DstElTy = DstPTy->getElementType();
6976 const Type *SrcElTy = SrcPTy->getElementType();
6977
6978 // If we are casting a malloc or alloca to a pointer to a type of the same
6979 // size, rewrite the allocation instruction to allocate the "right" type.
6980 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
6981 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
6982 return V;
6983
Chris Lattnerd717c182007-05-05 22:32:24 +00006984 // If the source and destination are pointers, and this cast is equivalent
6985 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
Chris Lattnerd3e28342007-04-27 17:44:50 +00006986 // This can enhance SROA and other transforms that want type-safe pointers.
6987 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
6988 unsigned NumZeros = 0;
6989 while (SrcElTy != DstElTy &&
6990 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
6991 SrcElTy->getNumContainedTypes() /* not "{}" */) {
6992 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
6993 ++NumZeros;
6994 }
Chris Lattner4e998b22004-09-29 05:07:12 +00006995
Chris Lattnerd3e28342007-04-27 17:44:50 +00006996 // If we found a path from the src to dest, create the getelementptr now.
6997 if (SrcElTy == DstElTy) {
6998 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
6999 return new GetElementPtrInst(Src, &Idxs[0], Idxs.size());
Chris Lattner9fb92132006-04-12 18:09:35 +00007000 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007001 }
Chris Lattner24c8e382003-07-24 17:35:25 +00007002
Reid Spencer3da59db2006-11-27 01:05:10 +00007003 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
7004 if (SVI->hasOneUse()) {
7005 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
7006 // a bitconvert to a vector with the same # elts.
Reid Spencer9d6565a2007-02-15 02:26:10 +00007007 if (isa<VectorType>(DestTy) &&
7008 cast<VectorType>(DestTy)->getNumElements() ==
Reid Spencer3da59db2006-11-27 01:05:10 +00007009 SVI->getType()->getNumElements()) {
7010 CastInst *Tmp;
7011 // If either of the operands is a cast from CI.getType(), then
7012 // evaluating the shuffle in the casted destination's type will allow
7013 // us to eliminate at least one cast.
7014 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
7015 Tmp->getOperand(0)->getType() == DestTy) ||
7016 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
7017 Tmp->getOperand(0)->getType() == DestTy)) {
Reid Spencer17212df2006-12-12 09:18:51 +00007018 Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
7019 SVI->getOperand(0), DestTy, &CI);
7020 Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
7021 SVI->getOperand(1), DestTy, &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007022 // Return a new shuffle vector. Use the same element ID's, as we
7023 // know the vector types match #elts.
7024 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner01575b72006-05-25 23:24:33 +00007025 }
7026 }
7027 }
7028 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00007029 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00007030}
7031
Chris Lattnere576b912004-04-09 23:46:01 +00007032/// GetSelectFoldableOperands - We want to turn code that looks like this:
7033/// %C = or %A, %B
7034/// %D = select %cond, %C, %A
7035/// into:
7036/// %C = select %cond, %B, 0
7037/// %D = or %A, %C
7038///
7039/// Assuming that the specified instruction is an operand to the select, return
7040/// a bitmask indicating which operands of this instruction are foldable if they
7041/// equal the other incoming value of the select.
7042///
7043static unsigned GetSelectFoldableOperands(Instruction *I) {
7044 switch (I->getOpcode()) {
7045 case Instruction::Add:
7046 case Instruction::Mul:
7047 case Instruction::And:
7048 case Instruction::Or:
7049 case Instruction::Xor:
7050 return 3; // Can fold through either operand.
7051 case Instruction::Sub: // Can only fold on the amount subtracted.
7052 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencer3822ff52006-11-08 06:47:33 +00007053 case Instruction::LShr:
7054 case Instruction::AShr:
Misha Brukmanfd939082005-04-21 23:48:37 +00007055 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00007056 default:
7057 return 0; // Cannot fold
7058 }
7059}
7060
7061/// GetSelectFoldableConstant - For the same transformation as the previous
7062/// function, return the identity constant that goes into the select.
7063static Constant *GetSelectFoldableConstant(Instruction *I) {
7064 switch (I->getOpcode()) {
7065 default: assert(0 && "This cannot happen!"); abort();
7066 case Instruction::Add:
7067 case Instruction::Sub:
7068 case Instruction::Or:
7069 case Instruction::Xor:
Chris Lattnere576b912004-04-09 23:46:01 +00007070 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00007071 case Instruction::LShr:
7072 case Instruction::AShr:
Reid Spencer832254e2007-02-02 02:16:23 +00007073 return Constant::getNullValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00007074 case Instruction::And:
7075 return ConstantInt::getAllOnesValue(I->getType());
7076 case Instruction::Mul:
7077 return ConstantInt::get(I->getType(), 1);
7078 }
7079}
7080
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007081/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
7082/// have the same opcode and only one use each. Try to simplify this.
7083Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
7084 Instruction *FI) {
7085 if (TI->getNumOperands() == 1) {
7086 // If this is a non-volatile load or a cast from the same type,
7087 // merge.
Reid Spencer3da59db2006-11-27 01:05:10 +00007088 if (TI->isCast()) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007089 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
7090 return 0;
7091 } else {
7092 return 0; // unknown unary op.
7093 }
Misha Brukmanfd939082005-04-21 23:48:37 +00007094
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007095 // Fold this by inserting a select from the input values.
7096 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
7097 FI->getOperand(0), SI.getName()+".v");
7098 InsertNewInstBefore(NewSI, SI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007099 return CastInst::create(Instruction::CastOps(TI->getOpcode()), NewSI,
7100 TI->getType());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007101 }
7102
Reid Spencer832254e2007-02-02 02:16:23 +00007103 // Only handle binary operators here.
7104 if (!isa<BinaryOperator>(TI))
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007105 return 0;
7106
7107 // Figure out if the operations have any operands in common.
7108 Value *MatchOp, *OtherOpT, *OtherOpF;
7109 bool MatchIsOpZero;
7110 if (TI->getOperand(0) == FI->getOperand(0)) {
7111 MatchOp = TI->getOperand(0);
7112 OtherOpT = TI->getOperand(1);
7113 OtherOpF = FI->getOperand(1);
7114 MatchIsOpZero = true;
7115 } else if (TI->getOperand(1) == FI->getOperand(1)) {
7116 MatchOp = TI->getOperand(1);
7117 OtherOpT = TI->getOperand(0);
7118 OtherOpF = FI->getOperand(0);
7119 MatchIsOpZero = false;
7120 } else if (!TI->isCommutative()) {
7121 return 0;
7122 } else if (TI->getOperand(0) == FI->getOperand(1)) {
7123 MatchOp = TI->getOperand(0);
7124 OtherOpT = TI->getOperand(1);
7125 OtherOpF = FI->getOperand(0);
7126 MatchIsOpZero = true;
7127 } else if (TI->getOperand(1) == FI->getOperand(0)) {
7128 MatchOp = TI->getOperand(1);
7129 OtherOpT = TI->getOperand(0);
7130 OtherOpF = FI->getOperand(1);
7131 MatchIsOpZero = true;
7132 } else {
7133 return 0;
7134 }
7135
7136 // If we reach here, they do have operations in common.
7137 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
7138 OtherOpF, SI.getName()+".v");
7139 InsertNewInstBefore(NewSI, SI);
7140
7141 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
7142 if (MatchIsOpZero)
7143 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
7144 else
7145 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007146 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00007147 assert(0 && "Shouldn't get here");
7148 return 0;
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007149}
7150
Chris Lattner3d69f462004-03-12 05:52:32 +00007151Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00007152 Value *CondVal = SI.getCondition();
7153 Value *TrueVal = SI.getTrueValue();
7154 Value *FalseVal = SI.getFalseValue();
7155
7156 // select true, X, Y -> X
7157 // select false, X, Y -> Y
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007158 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencer579dca12007-01-12 04:24:46 +00007159 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00007160
7161 // select C, X, X -> X
7162 if (TrueVal == FalseVal)
7163 return ReplaceInstUsesWith(SI, TrueVal);
7164
Chris Lattnere87597f2004-10-16 18:11:37 +00007165 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
7166 return ReplaceInstUsesWith(SI, FalseVal);
7167 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
7168 return ReplaceInstUsesWith(SI, TrueVal);
7169 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
7170 if (isa<Constant>(TrueVal))
7171 return ReplaceInstUsesWith(SI, TrueVal);
7172 else
7173 return ReplaceInstUsesWith(SI, FalseVal);
7174 }
7175
Reid Spencer4fe16d62007-01-11 18:21:29 +00007176 if (SI.getType() == Type::Int1Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00007177 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00007178 if (C->getZExtValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00007179 // Change: A = select B, true, C --> A = or B, C
Chris Lattner48595f12004-06-10 02:07:29 +00007180 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00007181 } else {
7182 // Change: A = select B, false, C --> A = and !B, C
7183 Value *NotCond =
7184 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
7185 "not."+CondVal->getName()), SI);
Chris Lattner48595f12004-06-10 02:07:29 +00007186 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00007187 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00007188 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00007189 if (C->getZExtValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00007190 // Change: A = select B, C, false --> A = and B, C
Chris Lattner48595f12004-06-10 02:07:29 +00007191 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00007192 } else {
7193 // Change: A = select B, C, true --> A = or !B, C
7194 Value *NotCond =
7195 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
7196 "not."+CondVal->getName()), SI);
Chris Lattner48595f12004-06-10 02:07:29 +00007197 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00007198 }
7199 }
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007200 }
Chris Lattner0c199a72004-04-08 04:43:23 +00007201
Chris Lattner2eefe512004-04-09 19:05:30 +00007202 // Selecting between two integer constants?
7203 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
7204 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattnerba417832007-04-11 06:12:58 +00007205 // select C, 1, 0 -> zext C to int
Reid Spencer2ec619a2007-03-23 21:24:59 +00007206 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007207 return CastInst::create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer2ec619a2007-03-23 21:24:59 +00007208 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattnerba417832007-04-11 06:12:58 +00007209 // select C, 0, 1 -> zext !C to int
Chris Lattner2eefe512004-04-09 19:05:30 +00007210 Value *NotCond =
7211 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00007212 "not."+CondVal->getName()), SI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007213 return CastInst::create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00007214 }
Chris Lattnerba417832007-04-11 06:12:58 +00007215
7216 // FIXME: Turn select 0/-1 and -1/0 into sext from condition!
Chris Lattner457dd822004-06-09 07:59:58 +00007217
Reid Spencere4d87aa2006-12-23 06:05:41 +00007218 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattnerb8456462006-09-20 04:44:59 +00007219
Reid Spencere4d87aa2006-12-23 06:05:41 +00007220 // (x <s 0) ? -1 : 0 -> ashr x, 31
Reid Spencer2ec619a2007-03-23 21:24:59 +00007221 if (TrueValC->isAllOnesValue() && FalseValC->isZero())
Chris Lattnerb8456462006-09-20 04:44:59 +00007222 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
Chris Lattnerba417832007-04-11 06:12:58 +00007223 if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
Chris Lattnerb8456462006-09-20 04:44:59 +00007224 // The comparison constant and the result are not neccessarily the
Reid Spencer3da59db2006-11-27 01:05:10 +00007225 // same width. Make an all-ones value by inserting a AShr.
Chris Lattnerb8456462006-09-20 04:44:59 +00007226 Value *X = IC->getOperand(0);
Zhou Sheng4351c642007-04-02 08:20:41 +00007227 uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
Reid Spencer832254e2007-02-02 02:16:23 +00007228 Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
7229 Instruction *SRA = BinaryOperator::create(Instruction::AShr, X,
7230 ShAmt, "ones");
Chris Lattnerb8456462006-09-20 04:44:59 +00007231 InsertNewInstBefore(SRA, SI);
7232
Reid Spencer3da59db2006-11-27 01:05:10 +00007233 // Finally, convert to the type of the select RHS. We figure out
7234 // if this requires a SExt, Trunc or BitCast based on the sizes.
7235 Instruction::CastOps opc = Instruction::BitCast;
Zhou Sheng4351c642007-04-02 08:20:41 +00007236 uint32_t SRASize = SRA->getType()->getPrimitiveSizeInBits();
7237 uint32_t SISize = SI.getType()->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00007238 if (SRASize < SISize)
7239 opc = Instruction::SExt;
7240 else if (SRASize > SISize)
7241 opc = Instruction::Trunc;
7242 return CastInst::create(opc, SRA, SI.getType());
Chris Lattnerb8456462006-09-20 04:44:59 +00007243 }
7244 }
7245
7246
7247 // If one of the constants is zero (we know they can't both be) and we
Chris Lattnerba417832007-04-11 06:12:58 +00007248 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattnerb8456462006-09-20 04:44:59 +00007249 // non-constant value, eliminate this whole mess. This corresponds to
7250 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer2ec619a2007-03-23 21:24:59 +00007251 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattner65b72ba2006-09-18 04:22:48 +00007252 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00007253 cast<Constant>(IC->getOperand(1))->isNullValue())
7254 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
7255 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00007256 isa<ConstantInt>(ICA->getOperand(1)) &&
7257 (ICA->getOperand(1) == TrueValC ||
7258 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00007259 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
7260 // Okay, now we know that everything is set up, we just don't
Reid Spencere4d87aa2006-12-23 06:05:41 +00007261 // know whether we have a icmp_ne or icmp_eq and whether the
7262 // true or false val is the zero.
Reid Spencer2ec619a2007-03-23 21:24:59 +00007263 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencere4d87aa2006-12-23 06:05:41 +00007264 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner457dd822004-06-09 07:59:58 +00007265 Value *V = ICA;
7266 if (ShouldNotVal)
7267 V = InsertNewInstBefore(BinaryOperator::create(
7268 Instruction::Xor, V, ICA->getOperand(1)), SI);
7269 return ReplaceInstUsesWith(SI, V);
7270 }
Chris Lattnerb8456462006-09-20 04:44:59 +00007271 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00007272 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00007273
7274 // See if we are selecting two values based on a comparison of the two values.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007275 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
7276 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattnerd76956d2004-04-10 22:21:27 +00007277 // Transform (X == Y) ? X : Y -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00007278 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ)
Chris Lattnerd76956d2004-04-10 22:21:27 +00007279 return ReplaceInstUsesWith(SI, FalseVal);
7280 // Transform (X != Y) ? X : Y -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00007281 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattnerd76956d2004-04-10 22:21:27 +00007282 return ReplaceInstUsesWith(SI, TrueVal);
7283 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7284
Reid Spencere4d87aa2006-12-23 06:05:41 +00007285 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattnerd76956d2004-04-10 22:21:27 +00007286 // Transform (X == Y) ? Y : X -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00007287 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ)
Chris Lattnerfbede522004-04-11 01:39:19 +00007288 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattnerd76956d2004-04-10 22:21:27 +00007289 // Transform (X != Y) ? Y : X -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00007290 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
7291 return ReplaceInstUsesWith(SI, TrueVal);
7292 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7293 }
7294 }
7295
7296 // See if we are selecting two values based on a comparison of the two values.
7297 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
7298 if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
7299 // Transform (X == Y) ? X : Y -> Y
7300 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
7301 return ReplaceInstUsesWith(SI, FalseVal);
7302 // Transform (X != Y) ? X : Y -> X
7303 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
7304 return ReplaceInstUsesWith(SI, TrueVal);
7305 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7306
7307 } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
7308 // Transform (X == Y) ? Y : X -> X
7309 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
7310 return ReplaceInstUsesWith(SI, FalseVal);
7311 // Transform (X != Y) ? Y : X -> Y
7312 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
Chris Lattnerfbede522004-04-11 01:39:19 +00007313 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerd76956d2004-04-10 22:21:27 +00007314 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7315 }
7316 }
Misha Brukmanfd939082005-04-21 23:48:37 +00007317
Chris Lattner87875da2005-01-13 22:52:24 +00007318 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
7319 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
7320 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattner87875da2005-01-13 22:52:24 +00007321 Instruction *AddOp = 0, *SubOp = 0;
7322
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007323 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
7324 if (TI->getOpcode() == FI->getOpcode())
7325 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
7326 return IV;
7327
7328 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
7329 // even legal for FP.
Chris Lattner87875da2005-01-13 22:52:24 +00007330 if (TI->getOpcode() == Instruction::Sub &&
7331 FI->getOpcode() == Instruction::Add) {
7332 AddOp = FI; SubOp = TI;
7333 } else if (FI->getOpcode() == Instruction::Sub &&
7334 TI->getOpcode() == Instruction::Add) {
7335 AddOp = TI; SubOp = FI;
7336 }
7337
7338 if (AddOp) {
7339 Value *OtherAddOp = 0;
7340 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
7341 OtherAddOp = AddOp->getOperand(1);
7342 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
7343 OtherAddOp = AddOp->getOperand(0);
7344 }
7345
7346 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00007347 // So at this point we know we have (Y -> OtherAddOp):
7348 // select C, (add X, Y), (sub X, Z)
7349 Value *NegVal; // Compute -Z
7350 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
7351 NegVal = ConstantExpr::getNeg(C);
7352 } else {
7353 NegVal = InsertNewInstBefore(
7354 BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00007355 }
Chris Lattner97f37a42006-02-24 18:05:58 +00007356
7357 Value *NewTrueOp = OtherAddOp;
7358 Value *NewFalseOp = NegVal;
7359 if (AddOp != TI)
7360 std::swap(NewTrueOp, NewFalseOp);
7361 Instruction *NewSel =
7362 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
7363
7364 NewSel = InsertNewInstBefore(NewSel, SI);
7365 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00007366 }
7367 }
7368 }
Misha Brukmanfd939082005-04-21 23:48:37 +00007369
Chris Lattnere576b912004-04-09 23:46:01 +00007370 // See if we can fold the select into one of our operands.
Chris Lattner42a75512007-01-15 02:27:26 +00007371 if (SI.getType()->isInteger()) {
Chris Lattnere576b912004-04-09 23:46:01 +00007372 // See the comment above GetSelectFoldableOperands for a description of the
7373 // transformation we are doing here.
7374 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
7375 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
7376 !isa<Constant>(FalseVal))
7377 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
7378 unsigned OpToFold = 0;
7379 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
7380 OpToFold = 1;
7381 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
7382 OpToFold = 2;
7383 }
7384
7385 if (OpToFold) {
7386 Constant *C = GetSelectFoldableConstant(TVI);
Chris Lattnere576b912004-04-09 23:46:01 +00007387 Instruction *NewSel =
Chris Lattner6934a042007-02-11 01:23:03 +00007388 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C);
Chris Lattnere576b912004-04-09 23:46:01 +00007389 InsertNewInstBefore(NewSel, SI);
Chris Lattner6934a042007-02-11 01:23:03 +00007390 NewSel->takeName(TVI);
Chris Lattnere576b912004-04-09 23:46:01 +00007391 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
7392 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
Chris Lattnere576b912004-04-09 23:46:01 +00007393 else {
7394 assert(0 && "Unknown instruction!!");
7395 }
7396 }
7397 }
Chris Lattnera96879a2004-09-29 17:40:11 +00007398
Chris Lattnere576b912004-04-09 23:46:01 +00007399 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
7400 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
7401 !isa<Constant>(TrueVal))
7402 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
7403 unsigned OpToFold = 0;
7404 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
7405 OpToFold = 1;
7406 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
7407 OpToFold = 2;
7408 }
7409
7410 if (OpToFold) {
7411 Constant *C = GetSelectFoldableConstant(FVI);
Chris Lattnere576b912004-04-09 23:46:01 +00007412 Instruction *NewSel =
Chris Lattner6934a042007-02-11 01:23:03 +00007413 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold));
Chris Lattnere576b912004-04-09 23:46:01 +00007414 InsertNewInstBefore(NewSel, SI);
Chris Lattner6934a042007-02-11 01:23:03 +00007415 NewSel->takeName(FVI);
Chris Lattnere576b912004-04-09 23:46:01 +00007416 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
7417 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
Reid Spencer832254e2007-02-02 02:16:23 +00007418 else
Chris Lattnere576b912004-04-09 23:46:01 +00007419 assert(0 && "Unknown instruction!!");
Chris Lattnere576b912004-04-09 23:46:01 +00007420 }
7421 }
7422 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00007423
7424 if (BinaryOperator::isNot(CondVal)) {
7425 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
7426 SI.setOperand(1, FalseVal);
7427 SI.setOperand(2, TrueVal);
7428 return &SI;
7429 }
7430
Chris Lattner3d69f462004-03-12 05:52:32 +00007431 return 0;
7432}
7433
Chris Lattner95a959d2006-03-06 20:18:44 +00007434/// GetKnownAlignment - If the specified pointer has an alignment that we can
7435/// determine, return it, otherwise return 0.
7436static unsigned GetKnownAlignment(Value *V, TargetData *TD) {
7437 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
7438 unsigned Align = GV->getAlignment();
7439 if (Align == 0 && TD)
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007440 Align = TD->getPrefTypeAlignment(GV->getType()->getElementType());
Chris Lattner95a959d2006-03-06 20:18:44 +00007441 return Align;
7442 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
7443 unsigned Align = AI->getAlignment();
7444 if (Align == 0 && TD) {
7445 if (isa<AllocaInst>(AI))
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007446 Align = TD->getPrefTypeAlignment(AI->getType()->getElementType());
Chris Lattner95a959d2006-03-06 20:18:44 +00007447 else if (isa<MallocInst>(AI)) {
7448 // Malloc returns maximally aligned memory.
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007449 Align = TD->getABITypeAlignment(AI->getType()->getElementType());
Chris Lattner58092e32007-01-20 22:35:55 +00007450 Align =
7451 std::max(Align,
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007452 (unsigned)TD->getABITypeAlignment(Type::DoubleTy));
Chris Lattner58092e32007-01-20 22:35:55 +00007453 Align =
7454 std::max(Align,
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007455 (unsigned)TD->getABITypeAlignment(Type::Int64Ty));
Chris Lattner95a959d2006-03-06 20:18:44 +00007456 }
7457 }
7458 return Align;
Reid Spencer3da59db2006-11-27 01:05:10 +00007459 } else if (isa<BitCastInst>(V) ||
Chris Lattner51c26e92006-03-07 01:28:57 +00007460 (isa<ConstantExpr>(V) &&
Reid Spencer3da59db2006-11-27 01:05:10 +00007461 cast<ConstantExpr>(V)->getOpcode() == Instruction::BitCast)) {
Chris Lattner51c26e92006-03-07 01:28:57 +00007462 User *CI = cast<User>(V);
Chris Lattner95a959d2006-03-06 20:18:44 +00007463 if (isa<PointerType>(CI->getOperand(0)->getType()))
7464 return GetKnownAlignment(CI->getOperand(0), TD);
7465 return 0;
Chris Lattner9bc14642007-04-28 00:57:34 +00007466 } else if (User *GEPI = dyn_castGetElementPtr(V)) {
Chris Lattner95a959d2006-03-06 20:18:44 +00007467 unsigned BaseAlignment = GetKnownAlignment(GEPI->getOperand(0), TD);
7468 if (BaseAlignment == 0) return 0;
7469
7470 // If all indexes are zero, it is just the alignment of the base pointer.
7471 bool AllZeroOperands = true;
7472 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
7473 if (!isa<Constant>(GEPI->getOperand(i)) ||
7474 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
7475 AllZeroOperands = false;
7476 break;
7477 }
7478 if (AllZeroOperands)
7479 return BaseAlignment;
7480
7481 // Otherwise, if the base alignment is >= the alignment we expect for the
7482 // base pointer type, then we know that the resultant pointer is aligned at
7483 // least as much as its type requires.
7484 if (!TD) return 0;
7485
7486 const Type *BasePtrTy = GEPI->getOperand(0)->getType();
Chris Lattner58092e32007-01-20 22:35:55 +00007487 const PointerType *PtrTy = cast<PointerType>(BasePtrTy);
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007488 if (TD->getABITypeAlignment(PtrTy->getElementType())
Chris Lattner51c26e92006-03-07 01:28:57 +00007489 <= BaseAlignment) {
7490 const Type *GEPTy = GEPI->getType();
Chris Lattner58092e32007-01-20 22:35:55 +00007491 const PointerType *GEPPtrTy = cast<PointerType>(GEPTy);
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007492 return TD->getABITypeAlignment(GEPPtrTy->getElementType());
Chris Lattner51c26e92006-03-07 01:28:57 +00007493 }
Chris Lattner95a959d2006-03-06 20:18:44 +00007494 return 0;
7495 }
7496 return 0;
7497}
7498
Chris Lattner3d69f462004-03-12 05:52:32 +00007499
Chris Lattner8b0ea312006-01-13 20:11:04 +00007500/// visitCallInst - CallInst simplification. This mostly only handles folding
7501/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
7502/// the heavy lifting.
7503///
Chris Lattner9fe38862003-06-19 17:00:31 +00007504Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattner8b0ea312006-01-13 20:11:04 +00007505 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
7506 if (!II) return visitCallSite(&CI);
7507
Chris Lattner7bcc0e72004-02-28 05:22:00 +00007508 // Intrinsics cannot occur in an invoke, so handle them here instead of in
7509 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00007510 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00007511 bool Changed = false;
7512
7513 // memmove/cpy/set of zero bytes is a noop.
7514 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
7515 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
7516
Chris Lattner35b9e482004-10-12 04:52:52 +00007517 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +00007518 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +00007519 // Replace the instruction with just byte operations. We would
7520 // transform other cases to loads/stores, but we don't know if
7521 // alignment is sufficient.
7522 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00007523 }
7524
Chris Lattner35b9e482004-10-12 04:52:52 +00007525 // If we have a memmove and the source operation is a constant global,
7526 // then the source and dest pointers can't alias, so we can change this
7527 // into a call to memcpy.
Chris Lattner95a959d2006-03-06 20:18:44 +00007528 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00007529 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
7530 if (GVSrc->isConstant()) {
7531 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner21959392006-03-03 01:34:17 +00007532 const char *Name;
Andrew Lenharth8ed4c472006-11-03 22:45:50 +00007533 if (CI.getCalledFunction()->getFunctionType()->getParamType(2) ==
Reid Spencerc5b206b2006-12-31 05:48:39 +00007534 Type::Int32Ty)
Chris Lattner21959392006-03-03 01:34:17 +00007535 Name = "llvm.memcpy.i32";
7536 else
7537 Name = "llvm.memcpy.i64";
Chris Lattner92141962007-01-07 06:58:05 +00007538 Constant *MemCpy = M->getOrInsertFunction(Name,
Chris Lattner35b9e482004-10-12 04:52:52 +00007539 CI.getCalledFunction()->getFunctionType());
7540 CI.setOperand(0, MemCpy);
7541 Changed = true;
7542 }
Chris Lattner95a959d2006-03-06 20:18:44 +00007543 }
Chris Lattner35b9e482004-10-12 04:52:52 +00007544
Chris Lattner95a959d2006-03-06 20:18:44 +00007545 // If we can determine a pointer alignment that is bigger than currently
7546 // set, update the alignment.
7547 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
7548 unsigned Alignment1 = GetKnownAlignment(MI->getOperand(1), TD);
7549 unsigned Alignment2 = GetKnownAlignment(MI->getOperand(2), TD);
7550 unsigned Align = std::min(Alignment1, Alignment2);
Reid Spencerb83eb642006-10-20 07:07:24 +00007551 if (MI->getAlignment()->getZExtValue() < Align) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007552 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Align));
Chris Lattner95a959d2006-03-06 20:18:44 +00007553 Changed = true;
7554 }
7555 } else if (isa<MemSetInst>(MI)) {
7556 unsigned Alignment = GetKnownAlignment(MI->getDest(), TD);
Reid Spencerb83eb642006-10-20 07:07:24 +00007557 if (MI->getAlignment()->getZExtValue() < Alignment) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007558 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
Chris Lattner95a959d2006-03-06 20:18:44 +00007559 Changed = true;
7560 }
7561 }
7562
Chris Lattner8b0ea312006-01-13 20:11:04 +00007563 if (Changed) return II;
Chris Lattnera728ddc2006-01-13 21:28:09 +00007564 } else {
7565 switch (II->getIntrinsicID()) {
7566 default: break;
Chris Lattner82ed58f2006-04-02 05:30:25 +00007567 case Intrinsic::ppc_altivec_lvx:
7568 case Intrinsic::ppc_altivec_lvxl:
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00007569 case Intrinsic::x86_sse_loadu_ps:
7570 case Intrinsic::x86_sse2_loadu_pd:
7571 case Intrinsic::x86_sse2_loadu_dq:
7572 // Turn PPC lvx -> load if the pointer is known aligned.
7573 // Turn X86 loadups -> load if the pointer is known aligned.
Chris Lattner82ed58f2006-04-02 05:30:25 +00007574 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
Reid Spencer17212df2006-12-12 09:18:51 +00007575 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
Chris Lattnere2ed0572006-04-06 19:19:17 +00007576 PointerType::get(II->getType()), CI);
Chris Lattner82ed58f2006-04-02 05:30:25 +00007577 return new LoadInst(Ptr);
7578 }
7579 break;
7580 case Intrinsic::ppc_altivec_stvx:
7581 case Intrinsic::ppc_altivec_stvxl:
7582 // Turn stvx -> store if the pointer is known aligned.
7583 if (GetKnownAlignment(II->getOperand(2), TD) >= 16) {
Chris Lattnere2ed0572006-04-06 19:19:17 +00007584 const Type *OpPtrTy = PointerType::get(II->getOperand(1)->getType());
Reid Spencer17212df2006-12-12 09:18:51 +00007585 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(2),
7586 OpPtrTy, CI);
Chris Lattner82ed58f2006-04-02 05:30:25 +00007587 return new StoreInst(II->getOperand(1), Ptr);
7588 }
7589 break;
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00007590 case Intrinsic::x86_sse_storeu_ps:
7591 case Intrinsic::x86_sse2_storeu_pd:
7592 case Intrinsic::x86_sse2_storeu_dq:
7593 case Intrinsic::x86_sse2_storel_dq:
7594 // Turn X86 storeu -> store if the pointer is known aligned.
7595 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
7596 const Type *OpPtrTy = PointerType::get(II->getOperand(2)->getType());
Reid Spencer17212df2006-12-12 09:18:51 +00007597 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
7598 OpPtrTy, CI);
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00007599 return new StoreInst(II->getOperand(2), Ptr);
7600 }
7601 break;
Chris Lattner867b99f2006-10-05 06:55:50 +00007602
7603 case Intrinsic::x86_sse_cvttss2si: {
7604 // These intrinsics only demands the 0th element of its input vector. If
7605 // we can simplify the input based on that, do so now.
7606 uint64_t UndefElts;
7607 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
7608 UndefElts)) {
7609 II->setOperand(1, V);
7610 return II;
7611 }
7612 break;
7613 }
7614
Chris Lattnere2ed0572006-04-06 19:19:17 +00007615 case Intrinsic::ppc_altivec_vperm:
7616 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
Reid Spencer9d6565a2007-02-15 02:26:10 +00007617 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
Chris Lattnere2ed0572006-04-06 19:19:17 +00007618 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
7619
7620 // Check that all of the elements are integer constants or undefs.
7621 bool AllEltsOk = true;
7622 for (unsigned i = 0; i != 16; ++i) {
7623 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
7624 !isa<UndefValue>(Mask->getOperand(i))) {
7625 AllEltsOk = false;
7626 break;
7627 }
7628 }
7629
7630 if (AllEltsOk) {
7631 // Cast the input vectors to byte vectors.
Reid Spencer17212df2006-12-12 09:18:51 +00007632 Value *Op0 = InsertCastBefore(Instruction::BitCast,
7633 II->getOperand(1), Mask->getType(), CI);
7634 Value *Op1 = InsertCastBefore(Instruction::BitCast,
7635 II->getOperand(2), Mask->getType(), CI);
Chris Lattnere2ed0572006-04-06 19:19:17 +00007636 Value *Result = UndefValue::get(Op0->getType());
7637
7638 // Only extract each element once.
7639 Value *ExtractedElts[32];
7640 memset(ExtractedElts, 0, sizeof(ExtractedElts));
7641
7642 for (unsigned i = 0; i != 16; ++i) {
7643 if (isa<UndefValue>(Mask->getOperand(i)))
7644 continue;
Chris Lattnere34e9a22007-04-14 23:32:02 +00007645 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
Chris Lattnere2ed0572006-04-06 19:19:17 +00007646 Idx &= 31; // Match the hardware behavior.
7647
7648 if (ExtractedElts[Idx] == 0) {
7649 Instruction *Elt =
Chris Lattner867b99f2006-10-05 06:55:50 +00007650 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00007651 InsertNewInstBefore(Elt, CI);
7652 ExtractedElts[Idx] = Elt;
7653 }
7654
7655 // Insert this value into the result vector.
Chris Lattner867b99f2006-10-05 06:55:50 +00007656 Result = new InsertElementInst(Result, ExtractedElts[Idx], i,"tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00007657 InsertNewInstBefore(cast<Instruction>(Result), CI);
7658 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007659 return CastInst::create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00007660 }
7661 }
7662 break;
7663
Chris Lattnera728ddc2006-01-13 21:28:09 +00007664 case Intrinsic::stackrestore: {
7665 // If the save is right next to the restore, remove the restore. This can
7666 // happen when variable allocas are DCE'd.
7667 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
7668 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
7669 BasicBlock::iterator BI = SS;
7670 if (&*++BI == II)
7671 return EraseInstFromFunction(CI);
7672 }
7673 }
7674
7675 // If the stack restore is in a return/unwind block and if there are no
7676 // allocas or calls between the restore and the return, nuke the restore.
7677 TerminatorInst *TI = II->getParent()->getTerminator();
7678 if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
7679 BasicBlock::iterator BI = II;
7680 bool CannotRemove = false;
7681 for (++BI; &*BI != TI; ++BI) {
7682 if (isa<AllocaInst>(BI) ||
7683 (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
7684 CannotRemove = true;
7685 break;
7686 }
7687 }
7688 if (!CannotRemove)
7689 return EraseInstFromFunction(CI);
7690 }
7691 break;
7692 }
7693 }
Chris Lattner35b9e482004-10-12 04:52:52 +00007694 }
7695
Chris Lattner8b0ea312006-01-13 20:11:04 +00007696 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +00007697}
7698
7699// InvokeInst simplification
7700//
7701Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +00007702 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +00007703}
7704
Chris Lattnera44d8a22003-10-07 22:32:43 +00007705// visitCallSite - Improvements for call and invoke instructions.
7706//
7707Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +00007708 bool Changed = false;
7709
7710 // If the callee is a constexpr cast of a function, attempt to move the cast
7711 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +00007712 if (transformConstExprCastCall(CS)) return 0;
7713
Chris Lattner6c266db2003-10-07 22:54:13 +00007714 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +00007715
Chris Lattner08b22ec2005-05-13 07:09:09 +00007716 if (Function *CalleeF = dyn_cast<Function>(Callee))
7717 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
7718 Instruction *OldCall = CS.getInstruction();
7719 // If the call and callee calling conventions don't match, this call must
7720 // be unreachable, as the call is undefined.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007721 new StoreInst(ConstantInt::getTrue(),
Reid Spencer4fe16d62007-01-11 18:21:29 +00007722 UndefValue::get(PointerType::get(Type::Int1Ty)), OldCall);
Chris Lattner08b22ec2005-05-13 07:09:09 +00007723 if (!OldCall->use_empty())
7724 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
7725 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
7726 return EraseInstFromFunction(*OldCall);
7727 return 0;
7728 }
7729
Chris Lattner17be6352004-10-18 02:59:09 +00007730 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
7731 // This instruction is not reachable, just remove it. We insert a store to
7732 // undef so that we know that this code is not reachable, despite the fact
7733 // that we can't modify the CFG here.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007734 new StoreInst(ConstantInt::getTrue(),
Reid Spencer4fe16d62007-01-11 18:21:29 +00007735 UndefValue::get(PointerType::get(Type::Int1Ty)),
Chris Lattner17be6352004-10-18 02:59:09 +00007736 CS.getInstruction());
7737
7738 if (!CS.getInstruction()->use_empty())
7739 CS.getInstruction()->
7740 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
7741
7742 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
7743 // Don't break the CFG, insert a dummy cond branch.
7744 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007745 ConstantInt::getTrue(), II);
Chris Lattnere87597f2004-10-16 18:11:37 +00007746 }
Chris Lattner17be6352004-10-18 02:59:09 +00007747 return EraseInstFromFunction(*CS.getInstruction());
7748 }
Chris Lattnere87597f2004-10-16 18:11:37 +00007749
Chris Lattner6c266db2003-10-07 22:54:13 +00007750 const PointerType *PTy = cast<PointerType>(Callee->getType());
7751 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
7752 if (FTy->isVarArg()) {
7753 // See if we can optimize any arguments passed through the varargs area of
7754 // the call.
7755 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
7756 E = CS.arg_end(); I != E; ++I)
7757 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
7758 // If this cast does not effect the value passed through the varargs
7759 // area, we can eliminate the use of the cast.
7760 Value *Op = CI->getOperand(0);
Reid Spencer3da59db2006-11-27 01:05:10 +00007761 if (CI->isLosslessCast()) {
Chris Lattner6c266db2003-10-07 22:54:13 +00007762 *I = Op;
7763 Changed = true;
7764 }
7765 }
7766 }
Misha Brukmanfd939082005-04-21 23:48:37 +00007767
Chris Lattner6c266db2003-10-07 22:54:13 +00007768 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +00007769}
7770
Chris Lattner9fe38862003-06-19 17:00:31 +00007771// transformConstExprCastCall - If the callee is a constexpr cast of a function,
7772// attempt to move the cast to the arguments of the call/invoke.
7773//
7774bool InstCombiner::transformConstExprCastCall(CallSite CS) {
7775 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
7776 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +00007777 if (CE->getOpcode() != Instruction::BitCast ||
7778 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +00007779 return false;
Reid Spencer8863f182004-07-18 00:38:32 +00007780 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +00007781 Instruction *Caller = CS.getInstruction();
7782
7783 // Okay, this is a cast from a function to a different type. Unless doing so
7784 // would cause a type conversion of one of our arguments, change this call to
7785 // be a direct call with arguments casted to the appropriate types.
7786 //
7787 const FunctionType *FT = Callee->getFunctionType();
7788 const Type *OldRetTy = Caller->getType();
7789
Chris Lattnera2b18de2007-05-19 06:51:32 +00007790 const FunctionType *ActualFT =
7791 cast<FunctionType>(cast<PointerType>(CE->getType())->getElementType());
7792
7793 // If the parameter attributes don't match up, don't do the xform. We don't
7794 // want to lose an sret attribute or something.
7795 if (FT->getParamAttrs() != ActualFT->getParamAttrs())
7796 return false;
7797
Chris Lattnerf78616b2004-01-14 06:06:08 +00007798 // Check to see if we are changing the return type...
7799 if (OldRetTy != FT->getReturnType()) {
Reid Spencer5cbf9852007-01-30 20:08:39 +00007800 if (Callee->isDeclaration() && !Caller->use_empty() &&
Chris Lattner46013f42007-01-06 19:53:32 +00007801 // Conversion is ok if changing from pointer to int of same size.
7802 !(isa<PointerType>(FT->getReturnType()) &&
7803 TD->getIntPtrType() == OldRetTy))
Chris Lattnerec479922007-01-06 02:09:32 +00007804 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +00007805
7806 // If the callsite is an invoke instruction, and the return value is used by
7807 // a PHI node in a successor, we cannot change the return type of the call
7808 // because there is no place to put the cast instruction (without breaking
7809 // the critical edge). Bail out in this case.
7810 if (!Caller->use_empty())
7811 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
7812 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
7813 UI != E; ++UI)
7814 if (PHINode *PN = dyn_cast<PHINode>(*UI))
7815 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00007816 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +00007817 return false;
7818 }
Chris Lattner9fe38862003-06-19 17:00:31 +00007819
7820 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
7821 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +00007822
Chris Lattner9fe38862003-06-19 17:00:31 +00007823 CallSite::arg_iterator AI = CS.arg_begin();
7824 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
7825 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +00007826 const Type *ActTy = (*AI)->getType();
Reid Spencer3da59db2006-11-27 01:05:10 +00007827 ConstantInt *c = dyn_cast<ConstantInt>(*AI);
Dale Johannesen16ff3042007-04-04 19:16:42 +00007828 //Some conversions are safe even if we do not have a body.
Andrew Lenharthb8e604c2006-06-28 01:01:52 +00007829 //Either we can cast directly, or we can upconvert the argument
Chris Lattnerec479922007-01-06 02:09:32 +00007830 bool isConvertible = ActTy == ParamTy ||
Chris Lattner46013f42007-01-06 19:53:32 +00007831 (isa<PointerType>(ParamTy) && isa<PointerType>(ActTy)) ||
Chris Lattner42a75512007-01-15 02:27:26 +00007832 (ParamTy->isInteger() && ActTy->isInteger() &&
Reid Spencerabaa8ca2007-01-08 16:32:00 +00007833 ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()) ||
7834 (c && ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()
Zhou Sheng0fc50952007-03-25 05:01:29 +00007835 && c->getValue().isStrictlyPositive());
Reid Spencer5cbf9852007-01-30 20:08:39 +00007836 if (Callee->isDeclaration() && !isConvertible) return false;
Dale Johannesen16ff3042007-04-04 19:16:42 +00007837
7838 // Most other conversions can be done if we have a body, even if these
7839 // lose information, e.g. int->short.
7840 // Some conversions cannot be done at all, e.g. float to pointer.
7841 // Logic here parallels CastInst::getCastOpcode (the design there
7842 // requires legality checks like this be done before calling it).
7843 if (ParamTy->isInteger()) {
7844 if (const VectorType *VActTy = dyn_cast<VectorType>(ActTy)) {
7845 if (VActTy->getBitWidth() != ParamTy->getPrimitiveSizeInBits())
7846 return false;
7847 }
7848 if (!ActTy->isInteger() && !ActTy->isFloatingPoint() &&
7849 !isa<PointerType>(ActTy))
7850 return false;
7851 } else if (ParamTy->isFloatingPoint()) {
7852 if (const VectorType *VActTy = dyn_cast<VectorType>(ActTy)) {
7853 if (VActTy->getBitWidth() != ParamTy->getPrimitiveSizeInBits())
7854 return false;
7855 }
7856 if (!ActTy->isInteger() && !ActTy->isFloatingPoint())
7857 return false;
7858 } else if (const VectorType *VParamTy = dyn_cast<VectorType>(ParamTy)) {
7859 if (const VectorType *VActTy = dyn_cast<VectorType>(ActTy)) {
7860 if (VActTy->getBitWidth() != VParamTy->getBitWidth())
7861 return false;
7862 }
7863 if (VParamTy->getBitWidth() != ActTy->getPrimitiveSizeInBits())
7864 return false;
7865 } else if (isa<PointerType>(ParamTy)) {
7866 if (!ActTy->isInteger() && !isa<PointerType>(ActTy))
7867 return false;
7868 } else {
7869 return false;
7870 }
Chris Lattner9fe38862003-06-19 17:00:31 +00007871 }
7872
7873 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +00007874 Callee->isDeclaration())
Chris Lattner9fe38862003-06-19 17:00:31 +00007875 return false; // Do not delete arguments unless we have a function body...
7876
7877 // Okay, we decided that this is a safe thing to do: go ahead and start
7878 // inserting cast instructions as necessary...
7879 std::vector<Value*> Args;
7880 Args.reserve(NumActualArgs);
7881
7882 AI = CS.arg_begin();
7883 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
7884 const Type *ParamTy = FT->getParamType(i);
7885 if ((*AI)->getType() == ParamTy) {
7886 Args.push_back(*AI);
7887 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +00007888 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +00007889 false, ParamTy, false);
Reid Spencer8a903db2006-12-18 08:47:13 +00007890 CastInst *NewCast = CastInst::create(opcode, *AI, ParamTy, "tmp");
Reid Spencer3da59db2006-11-27 01:05:10 +00007891 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner9fe38862003-06-19 17:00:31 +00007892 }
7893 }
7894
7895 // If the function takes more arguments than the call was taking, add them
7896 // now...
7897 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
7898 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
7899
7900 // If we are removing arguments to the function, emit an obnoxious warning...
7901 if (FT->getNumParams() < NumActualArgs)
7902 if (!FT->isVarArg()) {
Bill Wendlinge8156192006-12-07 01:30:32 +00007903 cerr << "WARNING: While resolving call to function '"
7904 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +00007905 } else {
7906 // Add all of the arguments in their promoted form to the arg list...
7907 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
7908 const Type *PTy = getPromotedType((*AI)->getType());
7909 if (PTy != (*AI)->getType()) {
7910 // Must promote to pass through va_arg area!
Reid Spencerc5b206b2006-12-31 05:48:39 +00007911 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
7912 PTy, false);
Reid Spencer8a903db2006-12-18 08:47:13 +00007913 Instruction *Cast = CastInst::create(opcode, *AI, PTy, "tmp");
Chris Lattner9fe38862003-06-19 17:00:31 +00007914 InsertNewInstBefore(Cast, *Caller);
7915 Args.push_back(Cast);
7916 } else {
7917 Args.push_back(*AI);
7918 }
7919 }
7920 }
7921
7922 if (FT->getReturnType() == Type::VoidTy)
Chris Lattner6934a042007-02-11 01:23:03 +00007923 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +00007924
7925 Instruction *NC;
7926 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00007927 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattner93e985f2007-02-13 02:10:56 +00007928 &Args[0], Args.size(), Caller->getName(), Caller);
Chris Lattnere4370262005-05-14 12:25:32 +00007929 cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
Chris Lattner9fe38862003-06-19 17:00:31 +00007930 } else {
Chris Lattner93e985f2007-02-13 02:10:56 +00007931 NC = new CallInst(Callee, &Args[0], Args.size(), Caller->getName(), Caller);
Chris Lattnera9e92112005-05-06 06:48:21 +00007932 if (cast<CallInst>(Caller)->isTailCall())
7933 cast<CallInst>(NC)->setTailCall();
Chris Lattnere4370262005-05-14 12:25:32 +00007934 cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Chris Lattner9fe38862003-06-19 17:00:31 +00007935 }
7936
Chris Lattner6934a042007-02-11 01:23:03 +00007937 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +00007938 Value *NV = NC;
7939 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
7940 if (NV->getType() != Type::VoidTy) {
Reid Spencer8a903db2006-12-18 08:47:13 +00007941 const Type *CallerTy = Caller->getType();
Reid Spencerc5b206b2006-12-31 05:48:39 +00007942 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
7943 CallerTy, false);
Reid Spencer8a903db2006-12-18 08:47:13 +00007944 NV = NC = CastInst::create(opcode, NC, CallerTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +00007945
7946 // If this is an invoke instruction, we should insert it after the first
7947 // non-phi, instruction in the normal successor block.
7948 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
7949 BasicBlock::iterator I = II->getNormalDest()->begin();
7950 while (isa<PHINode>(I)) ++I;
7951 InsertNewInstBefore(NC, *I);
7952 } else {
7953 // Otherwise, it's a call, just insert cast right after the call instr
7954 InsertNewInstBefore(NC, *Caller);
7955 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00007956 AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00007957 } else {
Chris Lattnerc30bda72004-10-17 21:22:38 +00007958 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +00007959 }
7960 }
7961
7962 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
7963 Caller->replaceAllUsesWith(NV);
Chris Lattnerf22a5c62007-03-02 19:59:19 +00007964 Caller->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +00007965 RemoveFromWorkList(Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00007966 return true;
7967}
7968
Chris Lattner7da52b22006-11-01 04:51:18 +00007969/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
7970/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
7971/// and a single binop.
7972Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
7973 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Reid Spencer832254e2007-02-02 02:16:23 +00007974 assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
7975 isa<CmpInst>(FirstInst));
Chris Lattner7da52b22006-11-01 04:51:18 +00007976 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00007977 Value *LHSVal = FirstInst->getOperand(0);
7978 Value *RHSVal = FirstInst->getOperand(1);
7979
7980 const Type *LHSType = LHSVal->getType();
7981 const Type *RHSType = RHSVal->getType();
Chris Lattner7da52b22006-11-01 04:51:18 +00007982
7983 // Scan to see if all operands are the same opcode, all have one use, and all
7984 // kill their operands (i.e. the operands have one use).
Chris Lattnera90a24c2006-11-01 04:55:47 +00007985 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
Chris Lattner7da52b22006-11-01 04:51:18 +00007986 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnera90a24c2006-11-01 04:55:47 +00007987 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00007988 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattner9c080502006-11-01 07:43:41 +00007989 // types or GEP's with different index types.
7990 I->getOperand(0)->getType() != LHSType ||
7991 I->getOperand(1)->getType() != RHSType)
Chris Lattner7da52b22006-11-01 04:51:18 +00007992 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +00007993
7994 // If they are CmpInst instructions, check their predicates
7995 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
7996 if (cast<CmpInst>(I)->getPredicate() !=
7997 cast<CmpInst>(FirstInst)->getPredicate())
7998 return 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00007999
8000 // Keep track of which operand needs a phi node.
8001 if (I->getOperand(0) != LHSVal) LHSVal = 0;
8002 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattner7da52b22006-11-01 04:51:18 +00008003 }
8004
Chris Lattner53738a42006-11-08 19:42:28 +00008005 // Otherwise, this is safe to transform, determine if it is profitable.
8006
8007 // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
8008 // Indexes are often folded into load/store instructions, so we don't want to
8009 // hide them behind a phi.
8010 if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
8011 return 0;
8012
Chris Lattner7da52b22006-11-01 04:51:18 +00008013 Value *InLHS = FirstInst->getOperand(0);
Chris Lattner7da52b22006-11-01 04:51:18 +00008014 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner53738a42006-11-08 19:42:28 +00008015 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00008016 if (LHSVal == 0) {
8017 NewLHS = new PHINode(LHSType, FirstInst->getOperand(0)->getName()+".pn");
8018 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
8019 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +00008020 InsertNewInstBefore(NewLHS, PN);
8021 LHSVal = NewLHS;
8022 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00008023
8024 if (RHSVal == 0) {
8025 NewRHS = new PHINode(RHSType, FirstInst->getOperand(1)->getName()+".pn");
8026 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
8027 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +00008028 InsertNewInstBefore(NewRHS, PN);
8029 RHSVal = NewRHS;
8030 }
8031
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00008032 // Add all operands to the new PHIs.
8033 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
8034 if (NewLHS) {
8035 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
8036 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
8037 }
8038 if (NewRHS) {
8039 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
8040 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
8041 }
8042 }
8043
Chris Lattner7da52b22006-11-01 04:51:18 +00008044 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattner9c080502006-11-01 07:43:41 +00008045 return BinaryOperator::create(BinOp->getOpcode(), LHSVal, RHSVal);
Reid Spencere4d87aa2006-12-23 06:05:41 +00008046 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
8047 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
8048 RHSVal);
Chris Lattner9c080502006-11-01 07:43:41 +00008049 else {
8050 assert(isa<GetElementPtrInst>(FirstInst));
8051 return new GetElementPtrInst(LHSVal, RHSVal);
8052 }
Chris Lattner7da52b22006-11-01 04:51:18 +00008053}
8054
Chris Lattner76c73142006-11-01 07:13:54 +00008055/// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
8056/// of the block that defines it. This means that it must be obvious the value
8057/// of the load is not changed from the point of the load to the end of the
8058/// block it is in.
Chris Lattnerfd905ca2007-02-01 22:30:07 +00008059///
8060/// Finally, it is safe, but not profitable, to sink a load targetting a
8061/// non-address-taken alloca. Doing so will cause us to not promote the alloca
8062/// to a register.
Chris Lattner76c73142006-11-01 07:13:54 +00008063static bool isSafeToSinkLoad(LoadInst *L) {
8064 BasicBlock::iterator BBI = L, E = L->getParent()->end();
8065
8066 for (++BBI; BBI != E; ++BBI)
8067 if (BBI->mayWriteToMemory())
8068 return false;
Chris Lattnerfd905ca2007-02-01 22:30:07 +00008069
8070 // Check for non-address taken alloca. If not address-taken already, it isn't
8071 // profitable to do this xform.
8072 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
8073 bool isAddressTaken = false;
8074 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
8075 UI != E; ++UI) {
8076 if (isa<LoadInst>(UI)) continue;
8077 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
8078 // If storing TO the alloca, then the address isn't taken.
8079 if (SI->getOperand(1) == AI) continue;
8080 }
8081 isAddressTaken = true;
8082 break;
8083 }
8084
8085 if (!isAddressTaken)
8086 return false;
8087 }
8088
Chris Lattner76c73142006-11-01 07:13:54 +00008089 return true;
8090}
8091
Chris Lattner9fe38862003-06-19 17:00:31 +00008092
Chris Lattnerbac32862004-11-14 19:13:23 +00008093// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
8094// operator and they all are only used by the PHI, PHI together their
8095// inputs, and do the operation once, to the result of the PHI.
8096Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
8097 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
8098
8099 // Scan the instruction, looking for input operations that can be folded away.
8100 // If all input operands to the phi are the same instruction (e.g. a cast from
8101 // the same type or "+42") we can pull the operation through the PHI, reducing
8102 // code size and simplifying code.
8103 Constant *ConstantOp = 0;
8104 const Type *CastSrcTy = 0;
Chris Lattner76c73142006-11-01 07:13:54 +00008105 bool isVolatile = false;
Chris Lattnerbac32862004-11-14 19:13:23 +00008106 if (isa<CastInst>(FirstInst)) {
8107 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer832254e2007-02-02 02:16:23 +00008108 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00008109 // Can fold binop, compare or shift here if the RHS is a constant,
8110 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattnerbac32862004-11-14 19:13:23 +00008111 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattner7da52b22006-11-01 04:51:18 +00008112 if (ConstantOp == 0)
8113 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner76c73142006-11-01 07:13:54 +00008114 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
8115 isVolatile = LI->isVolatile();
8116 // We can't sink the load if the loaded value could be modified between the
8117 // load and the PHI.
8118 if (LI->getParent() != PN.getIncomingBlock(0) ||
8119 !isSafeToSinkLoad(LI))
8120 return 0;
Chris Lattner9c080502006-11-01 07:43:41 +00008121 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner53738a42006-11-08 19:42:28 +00008122 if (FirstInst->getNumOperands() == 2)
Chris Lattner9c080502006-11-01 07:43:41 +00008123 return FoldPHIArgBinOpIntoPHI(PN);
8124 // Can't handle general GEPs yet.
8125 return 0;
Chris Lattnerbac32862004-11-14 19:13:23 +00008126 } else {
8127 return 0; // Cannot fold this operation.
8128 }
8129
8130 // Check to see if all arguments are the same operation.
8131 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
8132 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
8133 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencere4d87aa2006-12-23 06:05:41 +00008134 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattnerbac32862004-11-14 19:13:23 +00008135 return 0;
8136 if (CastSrcTy) {
8137 if (I->getOperand(0)->getType() != CastSrcTy)
8138 return 0; // Cast operation must match.
Chris Lattner76c73142006-11-01 07:13:54 +00008139 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00008140 // We can't sink the load if the loaded value could be modified between
8141 // the load and the PHI.
Chris Lattner76c73142006-11-01 07:13:54 +00008142 if (LI->isVolatile() != isVolatile ||
8143 LI->getParent() != PN.getIncomingBlock(i) ||
8144 !isSafeToSinkLoad(LI))
8145 return 0;
Chris Lattnerbac32862004-11-14 19:13:23 +00008146 } else if (I->getOperand(1) != ConstantOp) {
8147 return 0;
8148 }
8149 }
8150
8151 // Okay, they are all the same operation. Create a new PHI node of the
8152 // correct type, and PHI together all of the LHS's of the instructions.
8153 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
8154 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +00008155 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +00008156
8157 Value *InVal = FirstInst->getOperand(0);
8158 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00008159
8160 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +00008161 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
8162 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
8163 if (NewInVal != InVal)
8164 InVal = 0;
8165 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
8166 }
8167
8168 Value *PhiVal;
8169 if (InVal) {
8170 // The new PHI unions all of the same values together. This is really
8171 // common, so we handle it intelligently here for compile-time speed.
8172 PhiVal = InVal;
8173 delete NewPN;
8174 } else {
8175 InsertNewInstBefore(NewPN, PN);
8176 PhiVal = NewPN;
8177 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008178
Chris Lattnerbac32862004-11-14 19:13:23 +00008179 // Insert and return the new operation.
Reid Spencer3da59db2006-11-27 01:05:10 +00008180 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
8181 return CastInst::create(FirstCI->getOpcode(), PhiVal, PN.getType());
Reid Spencer3ed469c2006-11-02 20:25:50 +00008182 else if (isa<LoadInst>(FirstInst))
Chris Lattner76c73142006-11-01 07:13:54 +00008183 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattnerbac32862004-11-14 19:13:23 +00008184 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattnerb5893442004-11-14 19:29:34 +00008185 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Reid Spencere4d87aa2006-12-23 06:05:41 +00008186 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
8187 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(),
8188 PhiVal, ConstantOp);
Chris Lattnerbac32862004-11-14 19:13:23 +00008189 else
Reid Spencer832254e2007-02-02 02:16:23 +00008190 assert(0 && "Unknown operation");
Jeff Cohenca5183d2007-03-05 00:00:42 +00008191 return 0;
Chris Lattnerbac32862004-11-14 19:13:23 +00008192}
Chris Lattnera1be5662002-05-02 17:06:02 +00008193
Chris Lattnera3fd1c52005-01-17 05:10:15 +00008194/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
8195/// that is dead.
Chris Lattner0e5444b2007-03-26 20:40:50 +00008196static bool DeadPHICycle(PHINode *PN,
8197 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattnera3fd1c52005-01-17 05:10:15 +00008198 if (PN->use_empty()) return true;
8199 if (!PN->hasOneUse()) return false;
8200
8201 // Remember this node, and if we find the cycle, return.
Chris Lattner0e5444b2007-03-26 20:40:50 +00008202 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattnera3fd1c52005-01-17 05:10:15 +00008203 return true;
8204
8205 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
8206 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +00008207
Chris Lattnera3fd1c52005-01-17 05:10:15 +00008208 return false;
8209}
8210
Chris Lattner473945d2002-05-06 18:06:38 +00008211// PHINode simplification
8212//
Chris Lattner7e708292002-06-25 16:13:24 +00008213Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +00008214 // If LCSSA is around, don't mess with Phi nodes
Chris Lattnerf964f322007-03-04 04:27:24 +00008215 if (MustPreserveLCSSA) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +00008216
Owen Anderson7e057142006-07-10 22:03:18 +00008217 if (Value *V = PN.hasConstantValue())
8218 return ReplaceInstUsesWith(PN, V);
8219
Owen Anderson7e057142006-07-10 22:03:18 +00008220 // If all PHI operands are the same operation, pull them through the PHI,
8221 // reducing code size.
8222 if (isa<Instruction>(PN.getIncomingValue(0)) &&
8223 PN.getIncomingValue(0)->hasOneUse())
8224 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
8225 return Result;
8226
8227 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
8228 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
8229 // PHI)... break the cycle.
Chris Lattnerff9f13a2007-01-15 07:30:06 +00008230 if (PN.hasOneUse()) {
8231 Instruction *PHIUser = cast<Instruction>(PN.use_back());
8232 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattner0e5444b2007-03-26 20:40:50 +00008233 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Anderson7e057142006-07-10 22:03:18 +00008234 PotentiallyDeadPHIs.insert(&PN);
8235 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
8236 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
8237 }
Chris Lattnerff9f13a2007-01-15 07:30:06 +00008238
8239 // If this phi has a single use, and if that use just computes a value for
8240 // the next iteration of a loop, delete the phi. This occurs with unused
8241 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
8242 // common case here is good because the only other things that catch this
8243 // are induction variable analysis (sometimes) and ADCE, which is only run
8244 // late.
8245 if (PHIUser->hasOneUse() &&
8246 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
8247 PHIUser->use_back() == &PN) {
8248 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
8249 }
8250 }
Owen Anderson7e057142006-07-10 22:03:18 +00008251
Chris Lattner60921c92003-12-19 05:58:40 +00008252 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +00008253}
8254
Reid Spencer17212df2006-12-12 09:18:51 +00008255static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
8256 Instruction *InsertPoint,
8257 InstCombiner *IC) {
Reid Spencerabaa8ca2007-01-08 16:32:00 +00008258 unsigned PtrSize = DTy->getPrimitiveSizeInBits();
8259 unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +00008260 // We must cast correctly to the pointer type. Ensure that we
8261 // sign extend the integer value if it is smaller as this is
8262 // used for address computation.
8263 Instruction::CastOps opcode =
8264 (VTySize < PtrSize ? Instruction::SExt :
8265 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
8266 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
Chris Lattner28977af2004-04-05 01:30:19 +00008267}
8268
Chris Lattnera1be5662002-05-02 17:06:02 +00008269
Chris Lattner7e708292002-06-25 16:13:24 +00008270Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +00008271 Value *PtrOp = GEP.getOperand(0);
Chris Lattner9bc14642007-04-28 00:57:34 +00008272 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
Chris Lattner7e708292002-06-25 16:13:24 +00008273 // If so, eliminate the noop.
Chris Lattnerc6bd1952004-02-22 05:25:17 +00008274 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +00008275 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +00008276
Chris Lattnere87597f2004-10-16 18:11:37 +00008277 if (isa<UndefValue>(GEP.getOperand(0)))
8278 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
8279
Chris Lattnerc6bd1952004-02-22 05:25:17 +00008280 bool HasZeroPointerIndex = false;
8281 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
8282 HasZeroPointerIndex = C->isNullValue();
8283
8284 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +00008285 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +00008286
Chris Lattner28977af2004-04-05 01:30:19 +00008287 // Eliminate unneeded casts for indices.
8288 bool MadeChange = false;
Chris Lattnerdb9654e2007-03-25 20:43:09 +00008289
Chris Lattnercb69a4e2004-04-07 18:38:20 +00008290 gep_type_iterator GTI = gep_type_begin(GEP);
Chris Lattnerdb9654e2007-03-25 20:43:09 +00008291 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattnercb69a4e2004-04-07 18:38:20 +00008292 if (isa<SequentialType>(*GTI)) {
8293 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
Chris Lattner76b7a062007-01-15 07:02:54 +00008294 if (CI->getOpcode() == Instruction::ZExt ||
8295 CI->getOpcode() == Instruction::SExt) {
8296 const Type *SrcTy = CI->getOperand(0)->getType();
8297 // We can eliminate a cast from i32 to i64 iff the target
8298 // is a 32-bit pointer target.
8299 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
8300 MadeChange = true;
8301 GEP.setOperand(i, CI->getOperand(0));
Chris Lattner28977af2004-04-05 01:30:19 +00008302 }
8303 }
8304 }
Chris Lattnercb69a4e2004-04-07 18:38:20 +00008305 // If we are using a wider index than needed for this platform, shrink it
8306 // to what we need. If the incoming value needs a cast instruction,
8307 // insert it. This explicit cast can make subsequent optimizations more
8308 // obvious.
8309 Value *Op = GEP.getOperand(i);
Reid Spencera54b7cb2007-01-12 07:05:14 +00008310 if (TD->getTypeSize(Op->getType()) > TD->getPointerSize())
Chris Lattner4f1134e2004-04-17 18:16:10 +00008311 if (Constant *C = dyn_cast<Constant>(Op)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00008312 GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
Chris Lattner4f1134e2004-04-17 18:16:10 +00008313 MadeChange = true;
8314 } else {
Reid Spencer17212df2006-12-12 09:18:51 +00008315 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
8316 GEP);
Chris Lattnercb69a4e2004-04-07 18:38:20 +00008317 GEP.setOperand(i, Op);
8318 MadeChange = true;
8319 }
Chris Lattner28977af2004-04-05 01:30:19 +00008320 }
Chris Lattnerdb9654e2007-03-25 20:43:09 +00008321 }
Chris Lattner28977af2004-04-05 01:30:19 +00008322 if (MadeChange) return &GEP;
8323
Chris Lattnerdb9654e2007-03-25 20:43:09 +00008324 // If this GEP instruction doesn't move the pointer, and if the input operand
8325 // is a bitcast of another pointer, just replace the GEP with a bitcast of the
8326 // real input to the dest type.
Chris Lattner9bc14642007-04-28 00:57:34 +00008327 if (GEP.hasAllZeroIndices() && isa<BitCastInst>(GEP.getOperand(0)))
Chris Lattnerdb9654e2007-03-25 20:43:09 +00008328 return new BitCastInst(cast<BitCastInst>(GEP.getOperand(0))->getOperand(0),
8329 GEP.getType());
8330
Chris Lattner90ac28c2002-08-02 19:29:35 +00008331 // Combine Indices - If the source pointer to this getelementptr instruction
8332 // is a getelementptr instruction, combine the indices of the two
8333 // getelementptr instructions into a single instruction.
8334 //
Chris Lattner72588fc2007-02-15 22:48:32 +00008335 SmallVector<Value*, 8> SrcGEPOperands;
Chris Lattner574da9b2005-01-13 20:14:25 +00008336 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner72588fc2007-02-15 22:48:32 +00008337 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
Chris Lattnerebd985c2004-03-25 22:59:29 +00008338
8339 if (!SrcGEPOperands.empty()) {
Chris Lattner620ce142004-05-07 22:09:22 +00008340 // Note that if our source is a gep chain itself that we wait for that
8341 // chain to be resolved before we perform this transformation. This
8342 // avoids us creating a TON of code in some cases.
8343 //
8344 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
8345 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
8346 return 0; // Wait until our source is folded to completion.
8347
Chris Lattner72588fc2007-02-15 22:48:32 +00008348 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +00008349
8350 // Find out whether the last index in the source GEP is a sequential idx.
8351 bool EndsWithSequential = false;
8352 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
8353 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +00008354 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +00008355
Chris Lattner90ac28c2002-08-02 19:29:35 +00008356 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +00008357 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +00008358 // Replace: gep (gep %P, long B), long A, ...
8359 // With: T = long A+B; gep %P, T, ...
8360 //
Chris Lattner620ce142004-05-07 22:09:22 +00008361 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner28977af2004-04-05 01:30:19 +00008362 if (SO1 == Constant::getNullValue(SO1->getType())) {
8363 Sum = GO1;
8364 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
8365 Sum = SO1;
8366 } else {
8367 // If they aren't the same type, convert both to an integer of the
8368 // target's pointer size.
8369 if (SO1->getType() != GO1->getType()) {
8370 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +00008371 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +00008372 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +00008373 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +00008374 } else {
8375 unsigned PS = TD->getPointerSize();
Reid Spencera54b7cb2007-01-12 07:05:14 +00008376 if (TD->getTypeSize(SO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +00008377 // Convert GO1 to SO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +00008378 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +00008379
Reid Spencera54b7cb2007-01-12 07:05:14 +00008380 } else if (TD->getTypeSize(GO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +00008381 // Convert SO1 to GO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +00008382 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +00008383 } else {
8384 const Type *PT = TD->getIntPtrType();
Reid Spencer17212df2006-12-12 09:18:51 +00008385 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
8386 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +00008387 }
8388 }
8389 }
Chris Lattner620ce142004-05-07 22:09:22 +00008390 if (isa<Constant>(SO1) && isa<Constant>(GO1))
8391 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
8392 else {
Chris Lattner48595f12004-06-10 02:07:29 +00008393 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
8394 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner620ce142004-05-07 22:09:22 +00008395 }
Chris Lattner28977af2004-04-05 01:30:19 +00008396 }
Chris Lattner620ce142004-05-07 22:09:22 +00008397
8398 // Recycle the GEP we already have if possible.
8399 if (SrcGEPOperands.size() == 2) {
8400 GEP.setOperand(0, SrcGEPOperands[0]);
8401 GEP.setOperand(1, Sum);
8402 return &GEP;
8403 } else {
8404 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
8405 SrcGEPOperands.end()-1);
8406 Indices.push_back(Sum);
8407 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
8408 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008409 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +00008410 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanfd939082005-04-21 23:48:37 +00008411 SrcGEPOperands.size() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +00008412 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerebd985c2004-03-25 22:59:29 +00008413 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
8414 SrcGEPOperands.end());
Chris Lattner90ac28c2002-08-02 19:29:35 +00008415 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
8416 }
8417
8418 if (!Indices.empty())
Chris Lattner1ccd1852007-02-12 22:56:41 +00008419 return new GetElementPtrInst(SrcGEPOperands[0], &Indices[0],
8420 Indices.size(), GEP.getName());
Chris Lattner9b761232002-08-17 22:21:59 +00008421
Chris Lattner620ce142004-05-07 22:09:22 +00008422 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattner9b761232002-08-17 22:21:59 +00008423 // GEP of global variable. If all of the indices for this GEP are
8424 // constants, we can promote this to a constexpr instead of an instruction.
8425
8426 // Scan for nonconstants...
Chris Lattner55eb1c42007-01-31 04:40:53 +00008427 SmallVector<Constant*, 8> Indices;
Chris Lattner9b761232002-08-17 22:21:59 +00008428 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
8429 for (; I != E && isa<Constant>(*I); ++I)
8430 Indices.push_back(cast<Constant>(*I));
8431
8432 if (I == E) { // If they are all constants...
Chris Lattner55eb1c42007-01-31 04:40:53 +00008433 Constant *CE = ConstantExpr::getGetElementPtr(GV,
8434 &Indices[0],Indices.size());
Chris Lattner9b761232002-08-17 22:21:59 +00008435
8436 // Replace all uses of the GEP with the new constexpr...
8437 return ReplaceInstUsesWith(GEP, CE);
8438 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008439 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
Chris Lattnereed48272005-09-13 00:40:14 +00008440 if (!isa<PointerType>(X->getType())) {
8441 // Not interesting. Source pointer must be a cast from pointer.
8442 } else if (HasZeroPointerIndex) {
8443 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
8444 // into : GEP [10 x ubyte]* X, long 0, ...
8445 //
8446 // This occurs when the program declares an array extern like "int X[];"
8447 //
8448 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
8449 const PointerType *XTy = cast<PointerType>(X->getType());
8450 if (const ArrayType *XATy =
8451 dyn_cast<ArrayType>(XTy->getElementType()))
8452 if (const ArrayType *CATy =
8453 dyn_cast<ArrayType>(CPTy->getElementType()))
8454 if (CATy->getElementType() == XATy->getElementType()) {
8455 // At this point, we know that the cast source type is a pointer
8456 // to an array of the same type as the destination pointer
8457 // array. Because the array type is never stepped over (there
8458 // is a leading zero) we can fold the cast into this GEP.
8459 GEP.setOperand(0, X);
8460 return &GEP;
8461 }
8462 } else if (GEP.getNumOperands() == 2) {
8463 // Transform things like:
Chris Lattner7835cdd2005-09-13 18:36:04 +00008464 // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
8465 // into: %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
Chris Lattnereed48272005-09-13 00:40:14 +00008466 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
8467 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
8468 if (isa<ArrayType>(SrcElTy) &&
8469 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
8470 TD->getTypeSize(ResElTy)) {
8471 Value *V = InsertNewInstBefore(
Reid Spencerc5b206b2006-12-31 05:48:39 +00008472 new GetElementPtrInst(X, Constant::getNullValue(Type::Int32Ty),
Chris Lattnereed48272005-09-13 00:40:14 +00008473 GEP.getOperand(1), GEP.getName()), GEP);
Reid Spencer3da59db2006-11-27 01:05:10 +00008474 // V and GEP are both pointer types --> BitCast
8475 return new BitCastInst(V, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +00008476 }
Chris Lattner7835cdd2005-09-13 18:36:04 +00008477
8478 // Transform things like:
8479 // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
8480 // (where tmp = 8*tmp2) into:
8481 // getelementptr [100 x double]* %arr, int 0, int %tmp.2
8482
8483 if (isa<ArrayType>(SrcElTy) &&
Reid Spencerc5b206b2006-12-31 05:48:39 +00008484 (ResElTy == Type::Int8Ty || ResElTy == Type::Int8Ty)) {
Chris Lattner7835cdd2005-09-13 18:36:04 +00008485 uint64_t ArrayEltSize =
8486 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
8487
8488 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
8489 // allow either a mul, shift, or constant here.
8490 Value *NewIdx = 0;
8491 ConstantInt *Scale = 0;
8492 if (ArrayEltSize == 1) {
8493 NewIdx = GEP.getOperand(1);
8494 Scale = ConstantInt::get(NewIdx->getType(), 1);
8495 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattner6e2f8432005-09-14 17:32:56 +00008496 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +00008497 Scale = CI;
8498 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
8499 if (Inst->getOpcode() == Instruction::Shl &&
8500 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00008501 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
8502 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
8503 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +00008504 NewIdx = Inst->getOperand(0);
8505 } else if (Inst->getOpcode() == Instruction::Mul &&
8506 isa<ConstantInt>(Inst->getOperand(1))) {
8507 Scale = cast<ConstantInt>(Inst->getOperand(1));
8508 NewIdx = Inst->getOperand(0);
8509 }
8510 }
8511
8512 // If the index will be to exactly the right offset with the scale taken
8513 // out, perform the transformation.
Reid Spencerb83eb642006-10-20 07:07:24 +00008514 if (Scale && Scale->getZExtValue() % ArrayEltSize == 0) {
Reid Spencer3ed469c2006-11-02 20:25:50 +00008515 if (isa<ConstantInt>(Scale))
Reid Spencerb83eb642006-10-20 07:07:24 +00008516 Scale = ConstantInt::get(Scale->getType(),
8517 Scale->getZExtValue() / ArrayEltSize);
8518 if (Scale->getZExtValue() != 1) {
Reid Spencer17212df2006-12-12 09:18:51 +00008519 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
8520 true /*SExt*/);
Chris Lattner7835cdd2005-09-13 18:36:04 +00008521 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
8522 NewIdx = InsertNewInstBefore(Sc, GEP);
8523 }
8524
8525 // Insert the new GEP instruction.
Reid Spencer3da59db2006-11-27 01:05:10 +00008526 Instruction *NewGEP =
Reid Spencerc5b206b2006-12-31 05:48:39 +00008527 new GetElementPtrInst(X, Constant::getNullValue(Type::Int32Ty),
Chris Lattner7835cdd2005-09-13 18:36:04 +00008528 NewIdx, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +00008529 NewGEP = InsertNewInstBefore(NewGEP, GEP);
8530 // The NewGEP must be pointer typed, so must the old one -> BitCast
8531 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +00008532 }
8533 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +00008534 }
Chris Lattner8a2a3112001-12-14 16:52:21 +00008535 }
8536
Chris Lattner8a2a3112001-12-14 16:52:21 +00008537 return 0;
8538}
8539
Chris Lattner0864acf2002-11-04 16:18:53 +00008540Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
8541 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
8542 if (AI.isArrayAllocation()) // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +00008543 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
8544 const Type *NewTy =
8545 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattner0006bd72002-11-09 00:49:43 +00008546 AllocationInst *New = 0;
Chris Lattner0864acf2002-11-04 16:18:53 +00008547
8548 // Create and insert the replacement instruction...
8549 if (isa<MallocInst>(AI))
Nate Begeman14b05292005-11-05 09:21:28 +00008550 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +00008551 else {
8552 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman14b05292005-11-05 09:21:28 +00008553 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +00008554 }
Chris Lattner7c881df2004-03-19 06:08:10 +00008555
8556 InsertNewInstBefore(New, AI);
Misha Brukmanfd939082005-04-21 23:48:37 +00008557
Chris Lattner0864acf2002-11-04 16:18:53 +00008558 // Scan to the end of the allocation instructions, to skip over a block of
8559 // allocas if possible...
8560 //
8561 BasicBlock::iterator It = New;
8562 while (isa<AllocationInst>(*It)) ++It;
8563
8564 // Now that I is pointing to the first non-allocation-inst in the block,
8565 // insert our getelementptr instruction...
8566 //
Reid Spencerc5b206b2006-12-31 05:48:39 +00008567 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
Chris Lattner693787a2005-05-04 19:10:26 +00008568 Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
8569 New->getName()+".sub", It);
Chris Lattner0864acf2002-11-04 16:18:53 +00008570
8571 // Now make everything use the getelementptr instead of the original
8572 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +00008573 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +00008574 } else if (isa<UndefValue>(AI.getArraySize())) {
8575 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +00008576 }
Chris Lattner7c881df2004-03-19 06:08:10 +00008577
8578 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
8579 // Note that we only do this for alloca's, because malloc should allocate and
8580 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanfd939082005-04-21 23:48:37 +00008581 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Chris Lattnercf27afb2004-07-02 22:55:47 +00008582 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattner7c881df2004-03-19 06:08:10 +00008583 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
8584
Chris Lattner0864acf2002-11-04 16:18:53 +00008585 return 0;
8586}
8587
Chris Lattner67b1e1b2003-12-07 01:24:23 +00008588Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
8589 Value *Op = FI.getOperand(0);
8590
Chris Lattner17be6352004-10-18 02:59:09 +00008591 // free undef -> unreachable.
8592 if (isa<UndefValue>(Op)) {
8593 // Insert a new store to null because we cannot modify the CFG here.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008594 new StoreInst(ConstantInt::getTrue(),
Reid Spencer4fe16d62007-01-11 18:21:29 +00008595 UndefValue::get(PointerType::get(Type::Int1Ty)), &FI);
Chris Lattner17be6352004-10-18 02:59:09 +00008596 return EraseInstFromFunction(FI);
8597 }
Chris Lattner6fe55412007-04-14 00:20:02 +00008598
Chris Lattner6160e852004-02-28 04:57:37 +00008599 // If we have 'free null' delete the instruction. This can happen in stl code
8600 // when lots of inlining happens.
Chris Lattner17be6352004-10-18 02:59:09 +00008601 if (isa<ConstantPointerNull>(Op))
Chris Lattner7bcc0e72004-02-28 05:22:00 +00008602 return EraseInstFromFunction(FI);
Chris Lattner6fe55412007-04-14 00:20:02 +00008603
8604 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
8605 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
8606 FI.setOperand(0, CI->getOperand(0));
8607 return &FI;
8608 }
8609
8610 // Change free (gep X, 0,0,0,0) into free(X)
8611 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
8612 if (GEPI->hasAllZeroIndices()) {
8613 AddToWorkList(GEPI);
8614 FI.setOperand(0, GEPI->getOperand(0));
8615 return &FI;
8616 }
8617 }
8618
8619 // Change free(malloc) into nothing, if the malloc has a single use.
8620 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
8621 if (MI->hasOneUse()) {
8622 EraseInstFromFunction(FI);
8623 return EraseInstFromFunction(*MI);
8624 }
Chris Lattner6160e852004-02-28 04:57:37 +00008625
Chris Lattner67b1e1b2003-12-07 01:24:23 +00008626 return 0;
8627}
8628
8629
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00008630/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Chris Lattnerb89e0712004-07-13 01:49:43 +00008631static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
8632 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +00008633 Value *CastOp = CI->getOperand(0);
Chris Lattnerb89e0712004-07-13 01:49:43 +00008634
8635 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +00008636 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattnerb89e0712004-07-13 01:49:43 +00008637 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +00008638
Reid Spencer42230162007-01-22 05:51:25 +00008639 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +00008640 isa<VectorType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +00008641 // If the source is an array, the code below will not succeed. Check to
8642 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
8643 // constants.
8644 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
8645 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
8646 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +00008647 Value *Idxs[2];
8648 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
8649 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerf9527852005-01-31 04:50:46 +00008650 SrcTy = cast<PointerType>(CastOp->getType());
8651 SrcPTy = SrcTy->getElementType();
8652 }
8653
Reid Spencer42230162007-01-22 05:51:25 +00008654 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +00008655 isa<VectorType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +00008656 // Do not allow turning this into a load of an integer, which is then
8657 // casted to a pointer, this pessimizes pointer analysis a lot.
8658 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Reid Spencer42230162007-01-22 05:51:25 +00008659 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
8660 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +00008661
Chris Lattnerf9527852005-01-31 04:50:46 +00008662 // Okay, we are casting from one integer or pointer type to another of
8663 // the same size. Instead of casting the pointer before the load, cast
8664 // the result of the loaded value.
8665 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
8666 CI->getName(),
8667 LI.isVolatile()),LI);
8668 // Now cast the result of the load.
Reid Spencerd977d862006-12-12 23:36:14 +00008669 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerf9527852005-01-31 04:50:46 +00008670 }
Chris Lattnerb89e0712004-07-13 01:49:43 +00008671 }
8672 }
8673 return 0;
8674}
8675
Chris Lattnerc10aced2004-09-19 18:43:46 +00008676/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattner8a375202004-09-19 19:18:10 +00008677/// from this value cannot trap. If it is not obviously safe to load from the
8678/// specified pointer, we do a quick local scan of the basic block containing
8679/// ScanFrom, to determine if the address is already accessed.
8680static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
8681 // If it is an alloca or global variable, it is always safe to load from.
8682 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
8683
8684 // Otherwise, be a little bit agressive by scanning the local block where we
8685 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00008686 // from/to. If so, the previous load or store would have already trapped,
8687 // so there is no harm doing an extra load (also, CSE will later eliminate
8688 // the load entirely).
Chris Lattner8a375202004-09-19 19:18:10 +00008689 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
8690
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00008691 while (BBI != E) {
Chris Lattner8a375202004-09-19 19:18:10 +00008692 --BBI;
8693
8694 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
8695 if (LI->getOperand(0) == V) return true;
8696 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
8697 if (SI->getOperand(1) == V) return true;
Misha Brukmanfd939082005-04-21 23:48:37 +00008698
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00008699 }
Chris Lattner8a375202004-09-19 19:18:10 +00008700 return false;
Chris Lattnerc10aced2004-09-19 18:43:46 +00008701}
8702
Chris Lattner833b8a42003-06-26 05:06:25 +00008703Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
8704 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +00008705
Chris Lattner37366c12005-05-01 04:24:53 +00008706 // load (cast X) --> cast (load X) iff safe
Reid Spencer3ed469c2006-11-02 20:25:50 +00008707 if (isa<CastInst>(Op))
Chris Lattner37366c12005-05-01 04:24:53 +00008708 if (Instruction *Res = InstCombineLoadCast(*this, LI))
8709 return Res;
8710
8711 // None of the following transforms are legal for volatile loads.
8712 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +00008713
Chris Lattner62f254d2005-09-12 22:00:15 +00008714 if (&LI.getParent()->front() != &LI) {
8715 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattner9c1f0fd2005-09-12 22:21:03 +00008716 // If the instruction immediately before this is a store to the same
8717 // address, do a simple form of store->load forwarding.
Chris Lattner62f254d2005-09-12 22:00:15 +00008718 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
8719 if (SI->getOperand(1) == LI.getOperand(0))
8720 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattner9c1f0fd2005-09-12 22:21:03 +00008721 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
8722 if (LIB->getOperand(0) == LI.getOperand(0))
8723 return ReplaceInstUsesWith(LI, LIB);
Chris Lattner62f254d2005-09-12 22:00:15 +00008724 }
Chris Lattner37366c12005-05-01 04:24:53 +00008725
8726 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
Chris Lattner9bc14642007-04-28 00:57:34 +00008727 if (isa<ConstantPointerNull>(GEPI->getOperand(0))) {
Chris Lattner37366c12005-05-01 04:24:53 +00008728 // Insert a new store to null instruction before the load to indicate
8729 // that this code is not reachable. We do this instead of inserting
8730 // an unreachable instruction directly because we cannot modify the
8731 // CFG.
8732 new StoreInst(UndefValue::get(LI.getType()),
8733 Constant::getNullValue(Op->getType()), &LI);
8734 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8735 }
8736
Chris Lattnere87597f2004-10-16 18:11:37 +00008737 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner37366c12005-05-01 04:24:53 +00008738 // load null/undef -> undef
8739 if ((C->isNullValue() || isa<UndefValue>(C))) {
Chris Lattner17be6352004-10-18 02:59:09 +00008740 // Insert a new store to null instruction before the load to indicate that
8741 // this code is not reachable. We do this instead of inserting an
8742 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattner37366c12005-05-01 04:24:53 +00008743 new StoreInst(UndefValue::get(LI.getType()),
8744 Constant::getNullValue(Op->getType()), &LI);
Chris Lattnere87597f2004-10-16 18:11:37 +00008745 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner17be6352004-10-18 02:59:09 +00008746 }
Chris Lattner833b8a42003-06-26 05:06:25 +00008747
Chris Lattnere87597f2004-10-16 18:11:37 +00008748 // Instcombine load (constant global) into the value loaded.
8749 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Reid Spencer5cbf9852007-01-30 20:08:39 +00008750 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattnere87597f2004-10-16 18:11:37 +00008751 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +00008752
Chris Lattnere87597f2004-10-16 18:11:37 +00008753 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
8754 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
8755 if (CE->getOpcode() == Instruction::GetElementPtr) {
8756 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Reid Spencer5cbf9852007-01-30 20:08:39 +00008757 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattner363f2a22005-09-26 05:28:06 +00008758 if (Constant *V =
8759 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattnere87597f2004-10-16 18:11:37 +00008760 return ReplaceInstUsesWith(LI, V);
Chris Lattner37366c12005-05-01 04:24:53 +00008761 if (CE->getOperand(0)->isNullValue()) {
8762 // Insert a new store to null instruction before the load to indicate
8763 // that this code is not reachable. We do this instead of inserting
8764 // an unreachable instruction directly because we cannot modify the
8765 // CFG.
8766 new StoreInst(UndefValue::get(LI.getType()),
8767 Constant::getNullValue(Op->getType()), &LI);
8768 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8769 }
8770
Reid Spencer3da59db2006-11-27 01:05:10 +00008771 } else if (CE->isCast()) {
Chris Lattnere87597f2004-10-16 18:11:37 +00008772 if (Instruction *Res = InstCombineLoadCast(*this, LI))
8773 return Res;
8774 }
8775 }
Chris Lattnerf499eac2004-04-08 20:39:49 +00008776
Chris Lattner37366c12005-05-01 04:24:53 +00008777 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +00008778 // Change select and PHI nodes to select values instead of addresses: this
8779 // helps alias analysis out a lot, allows many others simplifications, and
8780 // exposes redundancy in the code.
8781 //
8782 // Note that we cannot do the transformation unless we know that the
8783 // introduced loads cannot trap! Something like this is valid as long as
8784 // the condition is always false: load (select bool %C, int* null, int* %G),
8785 // but it would not be valid if we transformed it to load from null
8786 // unconditionally.
8787 //
8788 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
8789 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +00008790 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
8791 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerc10aced2004-09-19 18:43:46 +00008792 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner79f0c8e2004-09-20 10:15:10 +00008793 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +00008794 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner79f0c8e2004-09-20 10:15:10 +00008795 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +00008796 return new SelectInst(SI->getCondition(), V1, V2);
8797 }
8798
Chris Lattner684fe212004-09-23 15:46:00 +00008799 // load (select (cond, null, P)) -> load P
8800 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
8801 if (C->isNullValue()) {
8802 LI.setOperand(0, SI->getOperand(2));
8803 return &LI;
8804 }
8805
8806 // load (select (cond, P, null)) -> load P
8807 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
8808 if (C->isNullValue()) {
8809 LI.setOperand(0, SI->getOperand(1));
8810 return &LI;
8811 }
Chris Lattnerc10aced2004-09-19 18:43:46 +00008812 }
8813 }
Chris Lattner833b8a42003-06-26 05:06:25 +00008814 return 0;
8815}
8816
Reid Spencer55af2b52007-01-19 21:20:31 +00008817/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00008818/// when possible.
8819static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
8820 User *CI = cast<User>(SI.getOperand(1));
8821 Value *CastOp = CI->getOperand(0);
8822
8823 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
8824 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
8825 const Type *SrcPTy = SrcTy->getElementType();
8826
Reid Spencer42230162007-01-22 05:51:25 +00008827 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00008828 // If the source is an array, the code below will not succeed. Check to
8829 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
8830 // constants.
8831 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
8832 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
8833 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +00008834 Value* Idxs[2];
8835 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
8836 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00008837 SrcTy = cast<PointerType>(CastOp->getType());
8838 SrcPTy = SrcTy->getElementType();
8839 }
8840
Reid Spencer67f827c2007-01-20 23:35:48 +00008841 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
8842 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
8843 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00008844
8845 // Okay, we are casting from one integer or pointer type to another of
Reid Spencer75153962007-01-18 18:54:33 +00008846 // the same size. Instead of casting the pointer before
8847 // the store, cast the value to be stored.
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00008848 Value *NewCast;
Reid Spencerd977d862006-12-12 23:36:14 +00008849 Value *SIOp0 = SI.getOperand(0);
Reid Spencer75153962007-01-18 18:54:33 +00008850 Instruction::CastOps opcode = Instruction::BitCast;
8851 const Type* CastSrcTy = SIOp0->getType();
8852 const Type* CastDstTy = SrcPTy;
8853 if (isa<PointerType>(CastDstTy)) {
8854 if (CastSrcTy->isInteger())
Reid Spencerd977d862006-12-12 23:36:14 +00008855 opcode = Instruction::IntToPtr;
Reid Spencer67f827c2007-01-20 23:35:48 +00008856 } else if (isa<IntegerType>(CastDstTy)) {
Reid Spencerc55b2432006-12-13 18:21:21 +00008857 if (isa<PointerType>(SIOp0->getType()))
Reid Spencerd977d862006-12-12 23:36:14 +00008858 opcode = Instruction::PtrToInt;
8859 }
8860 if (Constant *C = dyn_cast<Constant>(SIOp0))
Reid Spencer75153962007-01-18 18:54:33 +00008861 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00008862 else
Reid Spencer3da59db2006-11-27 01:05:10 +00008863 NewCast = IC.InsertNewInstBefore(
Reid Spencer75153962007-01-18 18:54:33 +00008864 CastInst::create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
8865 SI);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00008866 return new StoreInst(NewCast, CastOp);
8867 }
8868 }
8869 }
8870 return 0;
8871}
8872
Chris Lattner2f503e62005-01-31 05:36:43 +00008873Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
8874 Value *Val = SI.getOperand(0);
8875 Value *Ptr = SI.getOperand(1);
8876
8877 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner9ca96412006-02-08 03:25:32 +00008878 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +00008879 ++NumCombined;
8880 return 0;
8881 }
Chris Lattner836692d2007-01-15 06:51:56 +00008882
8883 // If the RHS is an alloca with a single use, zapify the store, making the
8884 // alloca dead.
8885 if (Ptr->hasOneUse()) {
8886 if (isa<AllocaInst>(Ptr)) {
8887 EraseInstFromFunction(SI);
8888 ++NumCombined;
8889 return 0;
8890 }
8891
8892 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
8893 if (isa<AllocaInst>(GEP->getOperand(0)) &&
8894 GEP->getOperand(0)->hasOneUse()) {
8895 EraseInstFromFunction(SI);
8896 ++NumCombined;
8897 return 0;
8898 }
8899 }
Chris Lattner2f503e62005-01-31 05:36:43 +00008900
Chris Lattner9ca96412006-02-08 03:25:32 +00008901 // Do really simple DSE, to catch cases where there are several consequtive
8902 // stores to the same location, separated by a few arithmetic operations. This
8903 // situation often occurs with bitfield accesses.
8904 BasicBlock::iterator BBI = &SI;
8905 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
8906 --ScanInsts) {
8907 --BBI;
8908
8909 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
8910 // Prev store isn't volatile, and stores to the same location?
8911 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
8912 ++NumDeadStore;
8913 ++BBI;
8914 EraseInstFromFunction(*PrevSI);
8915 continue;
8916 }
8917 break;
8918 }
8919
Chris Lattnerb4db97f2006-05-26 19:19:20 +00008920 // If this is a load, we have to stop. However, if the loaded value is from
8921 // the pointer we're loading and is producing the pointer we're storing,
8922 // then *this* store is dead (X = load P; store X -> P).
8923 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
8924 if (LI == Val && LI->getOperand(0) == Ptr) {
8925 EraseInstFromFunction(SI);
8926 ++NumCombined;
8927 return 0;
8928 }
8929 // Otherwise, this is a load from some other location. Stores before it
8930 // may not be dead.
8931 break;
8932 }
8933
Chris Lattner9ca96412006-02-08 03:25:32 +00008934 // Don't skip over loads or things that can modify memory.
Chris Lattnerb4db97f2006-05-26 19:19:20 +00008935 if (BBI->mayWriteToMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +00008936 break;
8937 }
8938
8939
8940 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +00008941
8942 // store X, null -> turns into 'unreachable' in SimplifyCFG
8943 if (isa<ConstantPointerNull>(Ptr)) {
8944 if (!isa<UndefValue>(Val)) {
8945 SI.setOperand(0, UndefValue::get(Val->getType()));
8946 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattnerdbab3862007-03-02 21:28:56 +00008947 AddToWorkList(U); // Dropped a use.
Chris Lattner2f503e62005-01-31 05:36:43 +00008948 ++NumCombined;
8949 }
8950 return 0; // Do not modify these!
8951 }
8952
8953 // store undef, Ptr -> noop
8954 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +00008955 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +00008956 ++NumCombined;
8957 return 0;
8958 }
8959
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00008960 // If the pointer destination is a cast, see if we can fold the cast into the
8961 // source instead.
Reid Spencer3ed469c2006-11-02 20:25:50 +00008962 if (isa<CastInst>(Ptr))
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00008963 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
8964 return Res;
8965 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer3da59db2006-11-27 01:05:10 +00008966 if (CE->isCast())
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00008967 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
8968 return Res;
8969
Chris Lattner408902b2005-09-12 23:23:25 +00008970
8971 // If this store is the last instruction in the basic block, and if the block
8972 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner9ca96412006-02-08 03:25:32 +00008973 BBI = &SI; ++BBI;
Chris Lattner408902b2005-09-12 23:23:25 +00008974 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
Chris Lattner3284d1f2007-04-15 00:07:55 +00008975 if (BI->isUnconditional())
8976 if (SimplifyStoreAtEndOfBlock(SI))
8977 return 0; // xform done!
Chris Lattner408902b2005-09-12 23:23:25 +00008978
Chris Lattner2f503e62005-01-31 05:36:43 +00008979 return 0;
8980}
8981
Chris Lattner3284d1f2007-04-15 00:07:55 +00008982/// SimplifyStoreAtEndOfBlock - Turn things like:
8983/// if () { *P = v1; } else { *P = v2 }
8984/// into a phi node with a store in the successor.
8985///
Chris Lattner31755a02007-04-15 01:02:18 +00008986/// Simplify things like:
8987/// *P = v1; if () { *P = v2; }
8988/// into a phi node with a store in the successor.
8989///
Chris Lattner3284d1f2007-04-15 00:07:55 +00008990bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
8991 BasicBlock *StoreBB = SI.getParent();
8992
8993 // Check to see if the successor block has exactly two incoming edges. If
8994 // so, see if the other predecessor contains a store to the same location.
8995 // if so, insert a PHI node (if needed) and move the stores down.
Chris Lattner31755a02007-04-15 01:02:18 +00008996 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Chris Lattner3284d1f2007-04-15 00:07:55 +00008997
8998 // Determine whether Dest has exactly two predecessors and, if so, compute
8999 // the other predecessor.
Chris Lattner31755a02007-04-15 01:02:18 +00009000 pred_iterator PI = pred_begin(DestBB);
9001 BasicBlock *OtherBB = 0;
Chris Lattner3284d1f2007-04-15 00:07:55 +00009002 if (*PI != StoreBB)
Chris Lattner31755a02007-04-15 01:02:18 +00009003 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +00009004 ++PI;
Chris Lattner31755a02007-04-15 01:02:18 +00009005 if (PI == pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +00009006 return false;
9007
9008 if (*PI != StoreBB) {
Chris Lattner31755a02007-04-15 01:02:18 +00009009 if (OtherBB)
Chris Lattner3284d1f2007-04-15 00:07:55 +00009010 return false;
Chris Lattner31755a02007-04-15 01:02:18 +00009011 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +00009012 }
Chris Lattner31755a02007-04-15 01:02:18 +00009013 if (++PI != pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +00009014 return false;
9015
9016
Chris Lattner31755a02007-04-15 01:02:18 +00009017 // Verify that the other block ends in a branch and is not otherwise empty.
9018 BasicBlock::iterator BBI = OtherBB->getTerminator();
Chris Lattner3284d1f2007-04-15 00:07:55 +00009019 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
Chris Lattner31755a02007-04-15 01:02:18 +00009020 if (!OtherBr || BBI == OtherBB->begin())
Chris Lattner3284d1f2007-04-15 00:07:55 +00009021 return false;
9022
Chris Lattner31755a02007-04-15 01:02:18 +00009023 // If the other block ends in an unconditional branch, check for the 'if then
9024 // else' case. there is an instruction before the branch.
9025 StoreInst *OtherStore = 0;
9026 if (OtherBr->isUnconditional()) {
9027 // If this isn't a store, or isn't a store to the same location, bail out.
9028 --BBI;
9029 OtherStore = dyn_cast<StoreInst>(BBI);
9030 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
9031 return false;
9032 } else {
Chris Lattnerd717c182007-05-05 22:32:24 +00009033 // Otherwise, the other block ended with a conditional branch. If one of the
Chris Lattner31755a02007-04-15 01:02:18 +00009034 // destinations is StoreBB, then we have the if/then case.
9035 if (OtherBr->getSuccessor(0) != StoreBB &&
9036 OtherBr->getSuccessor(1) != StoreBB)
9037 return false;
9038
9039 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
Chris Lattnerd717c182007-05-05 22:32:24 +00009040 // if/then triangle. See if there is a store to the same ptr as SI that
9041 // lives in OtherBB.
Chris Lattner31755a02007-04-15 01:02:18 +00009042 for (;; --BBI) {
9043 // Check to see if we find the matching store.
9044 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
9045 if (OtherStore->getOperand(1) != SI.getOperand(1))
9046 return false;
9047 break;
9048 }
Chris Lattnerd717c182007-05-05 22:32:24 +00009049 // If we find something that may be using the stored value, or if we run
9050 // out of instructions, we can't do the xform.
Chris Lattner31755a02007-04-15 01:02:18 +00009051 if (isa<LoadInst>(BBI) || BBI->mayWriteToMemory() ||
9052 BBI == OtherBB->begin())
9053 return false;
9054 }
9055
9056 // In order to eliminate the store in OtherBr, we have to
9057 // make sure nothing reads the stored value in StoreBB.
9058 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
9059 // FIXME: This should really be AA driven.
9060 if (isa<LoadInst>(I) || I->mayWriteToMemory())
9061 return false;
9062 }
9063 }
Chris Lattner3284d1f2007-04-15 00:07:55 +00009064
Chris Lattner31755a02007-04-15 01:02:18 +00009065 // Insert a PHI node now if we need it.
Chris Lattner3284d1f2007-04-15 00:07:55 +00009066 Value *MergedVal = OtherStore->getOperand(0);
9067 if (MergedVal != SI.getOperand(0)) {
9068 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
9069 PN->reserveOperandSpace(2);
9070 PN->addIncoming(SI.getOperand(0), SI.getParent());
Chris Lattner31755a02007-04-15 01:02:18 +00009071 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
9072 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Chris Lattner3284d1f2007-04-15 00:07:55 +00009073 }
9074
9075 // Advance to a place where it is safe to insert the new store and
9076 // insert it.
Chris Lattner31755a02007-04-15 01:02:18 +00009077 BBI = DestBB->begin();
Chris Lattner3284d1f2007-04-15 00:07:55 +00009078 while (isa<PHINode>(BBI)) ++BBI;
9079 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
9080 OtherStore->isVolatile()), *BBI);
9081
9082 // Nuke the old stores.
9083 EraseInstFromFunction(SI);
9084 EraseInstFromFunction(*OtherStore);
9085 ++NumCombined;
9086 return true;
9087}
9088
Chris Lattner2f503e62005-01-31 05:36:43 +00009089
Chris Lattnerc4d10eb2003-06-04 04:46:00 +00009090Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
9091 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +00009092 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00009093 BasicBlock *TrueDest;
9094 BasicBlock *FalseDest;
9095 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
9096 !isa<Constant>(X)) {
9097 // Swap Destinations and condition...
9098 BI.setCondition(X);
9099 BI.setSuccessor(0, FalseDest);
9100 BI.setSuccessor(1, TrueDest);
9101 return &BI;
9102 }
9103
Reid Spencere4d87aa2006-12-23 06:05:41 +00009104 // Cannonicalize fcmp_one -> fcmp_oeq
9105 FCmpInst::Predicate FPred; Value *Y;
9106 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
9107 TrueDest, FalseDest)))
9108 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
9109 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
9110 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +00009111 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
Chris Lattner6934a042007-02-11 01:23:03 +00009112 Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
9113 NewSCC->takeName(I);
Reid Spencere4d87aa2006-12-23 06:05:41 +00009114 // Swap Destinations and condition...
9115 BI.setCondition(NewSCC);
9116 BI.setSuccessor(0, FalseDest);
9117 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +00009118 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +00009119 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +00009120 AddToWorkList(NewSCC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00009121 return &BI;
9122 }
9123
9124 // Cannonicalize icmp_ne -> icmp_eq
9125 ICmpInst::Predicate IPred;
9126 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
9127 TrueDest, FalseDest)))
9128 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
9129 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
9130 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
9131 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +00009132 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
Chris Lattner6934a042007-02-11 01:23:03 +00009133 Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
9134 NewSCC->takeName(I);
Chris Lattner40f5d702003-06-04 05:10:11 +00009135 // Swap Destinations and condition...
Chris Lattneracd1f0f2004-07-30 07:50:03 +00009136 BI.setCondition(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +00009137 BI.setSuccessor(0, FalseDest);
9138 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +00009139 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +00009140 I->eraseFromParent();;
Chris Lattnerdbab3862007-03-02 21:28:56 +00009141 AddToWorkList(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +00009142 return &BI;
9143 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009144
Chris Lattnerc4d10eb2003-06-04 04:46:00 +00009145 return 0;
9146}
Chris Lattner0864acf2002-11-04 16:18:53 +00009147
Chris Lattner46238a62004-07-03 00:26:11 +00009148Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
9149 Value *Cond = SI.getCondition();
9150 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
9151 if (I->getOpcode() == Instruction::Add)
9152 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
9153 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
9154 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattnere87597f2004-10-16 18:11:37 +00009155 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +00009156 AddRHS));
9157 SI.setOperand(0, I->getOperand(0));
Chris Lattnerdbab3862007-03-02 21:28:56 +00009158 AddToWorkList(I);
Chris Lattner46238a62004-07-03 00:26:11 +00009159 return &SI;
9160 }
9161 }
9162 return 0;
9163}
9164
Chris Lattner220b0cf2006-03-05 00:22:33 +00009165/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
9166/// is to leave as a vector operation.
9167static bool CheapToScalarize(Value *V, bool isConstant) {
9168 if (isa<ConstantAggregateZero>(V))
9169 return true;
Reid Spencer9d6565a2007-02-15 02:26:10 +00009170 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +00009171 if (isConstant) return true;
9172 // If all elts are the same, we can extract.
9173 Constant *Op0 = C->getOperand(0);
9174 for (unsigned i = 1; i < C->getNumOperands(); ++i)
9175 if (C->getOperand(i) != Op0)
9176 return false;
9177 return true;
9178 }
9179 Instruction *I = dyn_cast<Instruction>(V);
9180 if (!I) return false;
9181
9182 // Insert element gets simplified to the inserted element or is deleted if
9183 // this is constant idx extract element and its a constant idx insertelt.
9184 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
9185 isa<ConstantInt>(I->getOperand(2)))
9186 return true;
9187 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
9188 return true;
9189 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
9190 if (BO->hasOneUse() &&
9191 (CheapToScalarize(BO->getOperand(0), isConstant) ||
9192 CheapToScalarize(BO->getOperand(1), isConstant)))
9193 return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +00009194 if (CmpInst *CI = dyn_cast<CmpInst>(I))
9195 if (CI->hasOneUse() &&
9196 (CheapToScalarize(CI->getOperand(0), isConstant) ||
9197 CheapToScalarize(CI->getOperand(1), isConstant)))
9198 return true;
Chris Lattner220b0cf2006-03-05 00:22:33 +00009199
9200 return false;
9201}
9202
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00009203/// Read and decode a shufflevector mask.
9204///
9205/// It turns undef elements into values that are larger than the number of
9206/// elements in the input.
Chris Lattner863bcff2006-05-25 23:48:38 +00009207static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
9208 unsigned NElts = SVI->getType()->getNumElements();
9209 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
9210 return std::vector<unsigned>(NElts, 0);
9211 if (isa<UndefValue>(SVI->getOperand(2)))
9212 return std::vector<unsigned>(NElts, 2*NElts);
9213
9214 std::vector<unsigned> Result;
Reid Spencer9d6565a2007-02-15 02:26:10 +00009215 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Chris Lattner863bcff2006-05-25 23:48:38 +00009216 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
9217 if (isa<UndefValue>(CP->getOperand(i)))
9218 Result.push_back(NElts*2); // undef -> 8
9219 else
Reid Spencerb83eb642006-10-20 07:07:24 +00009220 Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
Chris Lattner863bcff2006-05-25 23:48:38 +00009221 return Result;
9222}
9223
Chris Lattner6e6b0da2006-03-31 23:01:56 +00009224/// FindScalarElement - Given a vector and an element number, see if the scalar
9225/// value is already around as a register, for example if it were inserted then
9226/// extracted from the vector.
9227static Value *FindScalarElement(Value *V, unsigned EltNo) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00009228 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
9229 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +00009230 unsigned Width = PTy->getNumElements();
9231 if (EltNo >= Width) // Out of range access.
Chris Lattner6e6b0da2006-03-31 23:01:56 +00009232 return UndefValue::get(PTy->getElementType());
9233
9234 if (isa<UndefValue>(V))
9235 return UndefValue::get(PTy->getElementType());
9236 else if (isa<ConstantAggregateZero>(V))
9237 return Constant::getNullValue(PTy->getElementType());
Reid Spencer9d6565a2007-02-15 02:26:10 +00009238 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner6e6b0da2006-03-31 23:01:56 +00009239 return CP->getOperand(EltNo);
9240 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
9241 // If this is an insert to a variable element, we don't know what it is.
Reid Spencerb83eb642006-10-20 07:07:24 +00009242 if (!isa<ConstantInt>(III->getOperand(2)))
9243 return 0;
9244 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner6e6b0da2006-03-31 23:01:56 +00009245
9246 // If this is an insert to the element we are looking for, return the
9247 // inserted value.
Reid Spencerb83eb642006-10-20 07:07:24 +00009248 if (EltNo == IIElt)
9249 return III->getOperand(1);
Chris Lattner6e6b0da2006-03-31 23:01:56 +00009250
9251 // Otherwise, the insertelement doesn't modify the value, recurse on its
9252 // vector input.
9253 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner389a6f52006-04-10 23:06:36 +00009254 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Chris Lattner863bcff2006-05-25 23:48:38 +00009255 unsigned InEl = getShuffleMask(SVI)[EltNo];
9256 if (InEl < Width)
9257 return FindScalarElement(SVI->getOperand(0), InEl);
9258 else if (InEl < Width*2)
9259 return FindScalarElement(SVI->getOperand(1), InEl - Width);
9260 else
9261 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +00009262 }
9263
9264 // Otherwise, we don't know.
9265 return 0;
9266}
9267
Robert Bocchino1d7456d2006-01-13 22:48:06 +00009268Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Chris Lattner6e6b0da2006-03-31 23:01:56 +00009269
Chris Lattner1f13c882006-03-31 18:25:14 +00009270 // If packed val is undef, replace extract with scalar undef.
9271 if (isa<UndefValue>(EI.getOperand(0)))
9272 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
9273
9274 // If packed val is constant 0, replace extract with scalar 0.
9275 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
9276 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
9277
Reid Spencer9d6565a2007-02-15 02:26:10 +00009278 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Robert Bocchino1d7456d2006-01-13 22:48:06 +00009279 // If packed val is constant with uniform operands, replace EI
9280 // with that operand
Chris Lattner220b0cf2006-03-05 00:22:33 +00009281 Constant *op0 = C->getOperand(0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +00009282 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +00009283 if (C->getOperand(i) != op0) {
9284 op0 = 0;
9285 break;
9286 }
9287 if (op0)
9288 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +00009289 }
Chris Lattner220b0cf2006-03-05 00:22:33 +00009290
Chris Lattner6e6b0da2006-03-31 23:01:56 +00009291 // If extracting a specified index from the vector, see if we can recursively
9292 // find a previously computed scalar that was inserted into the vector.
Reid Spencerb83eb642006-10-20 07:07:24 +00009293 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner85464092007-04-09 01:37:55 +00009294 unsigned IndexVal = IdxC->getZExtValue();
9295 unsigned VectorWidth =
9296 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
9297
9298 // If this is extracting an invalid index, turn this into undef, to avoid
9299 // crashing the code below.
9300 if (IndexVal >= VectorWidth)
9301 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
9302
Chris Lattner867b99f2006-10-05 06:55:50 +00009303 // This instruction only demands the single element from the input vector.
9304 // If the input vector has a single use, simplify it based on this use
9305 // property.
Chris Lattner85464092007-04-09 01:37:55 +00009306 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Chris Lattner867b99f2006-10-05 06:55:50 +00009307 uint64_t UndefElts;
9308 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Reid Spencerb83eb642006-10-20 07:07:24 +00009309 1 << IndexVal,
Chris Lattner867b99f2006-10-05 06:55:50 +00009310 UndefElts)) {
9311 EI.setOperand(0, V);
9312 return &EI;
9313 }
9314 }
9315
Reid Spencerb83eb642006-10-20 07:07:24 +00009316 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
Chris Lattner6e6b0da2006-03-31 23:01:56 +00009317 return ReplaceInstUsesWith(EI, Elt);
Chris Lattnerb7300fa2007-04-14 23:02:14 +00009318
9319 // If the this extractelement is directly using a bitcast from a vector of
9320 // the same number of elements, see if we can find the source element from
9321 // it. In this case, we will end up needing to bitcast the scalars.
9322 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
9323 if (const VectorType *VT =
9324 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
9325 if (VT->getNumElements() == VectorWidth)
9326 if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
9327 return new BitCastInst(Elt, EI.getType());
9328 }
Chris Lattner389a6f52006-04-10 23:06:36 +00009329 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +00009330
Chris Lattner73fa49d2006-05-25 22:53:38 +00009331 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchino1d7456d2006-01-13 22:48:06 +00009332 if (I->hasOneUse()) {
9333 // Push extractelement into predecessor operation if legal and
9334 // profitable to do so
9335 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +00009336 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
9337 if (CheapToScalarize(BO, isConstantElt)) {
9338 ExtractElementInst *newEI0 =
9339 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
9340 EI.getName()+".lhs");
9341 ExtractElementInst *newEI1 =
9342 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
9343 EI.getName()+".rhs");
9344 InsertNewInstBefore(newEI0, EI);
9345 InsertNewInstBefore(newEI1, EI);
9346 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
9347 }
Reid Spencer3ed469c2006-11-02 20:25:50 +00009348 } else if (isa<LoadInst>(I)) {
Reid Spencer17212df2006-12-12 09:18:51 +00009349 Value *Ptr = InsertCastBefore(Instruction::BitCast, I->getOperand(0),
Robert Bocchino1d7456d2006-01-13 22:48:06 +00009350 PointerType::get(EI.getType()), EI);
9351 GetElementPtrInst *GEP =
Reid Spencerde331242006-11-29 01:11:01 +00009352 new GetElementPtrInst(Ptr, EI.getOperand(1), I->getName() + ".gep");
Robert Bocchino1d7456d2006-01-13 22:48:06 +00009353 InsertNewInstBefore(GEP, EI);
9354 return new LoadInst(GEP);
Chris Lattner73fa49d2006-05-25 22:53:38 +00009355 }
9356 }
9357 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
9358 // Extracting the inserted element?
9359 if (IE->getOperand(2) == EI.getOperand(1))
9360 return ReplaceInstUsesWith(EI, IE->getOperand(1));
9361 // If the inserted and extracted elements are constants, they must not
9362 // be the same value, extract from the pre-inserted value instead.
9363 if (isa<Constant>(IE->getOperand(2)) &&
9364 isa<Constant>(EI.getOperand(1))) {
9365 AddUsesToWorkList(EI);
9366 EI.setOperand(0, IE->getOperand(0));
9367 return &EI;
9368 }
9369 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
9370 // If this is extracting an element from a shufflevector, figure out where
9371 // it came from and extract from the appropriate input element instead.
Reid Spencerb83eb642006-10-20 07:07:24 +00009372 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
9373 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner863bcff2006-05-25 23:48:38 +00009374 Value *Src;
9375 if (SrcIdx < SVI->getType()->getNumElements())
9376 Src = SVI->getOperand(0);
9377 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
9378 SrcIdx -= SVI->getType()->getNumElements();
9379 Src = SVI->getOperand(1);
9380 } else {
9381 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +00009382 }
Chris Lattner867b99f2006-10-05 06:55:50 +00009383 return new ExtractElementInst(Src, SrcIdx);
Robert Bocchino1d7456d2006-01-13 22:48:06 +00009384 }
9385 }
Chris Lattner73fa49d2006-05-25 22:53:38 +00009386 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +00009387 return 0;
9388}
9389
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00009390/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
9391/// elements from either LHS or RHS, return the shuffle mask and true.
9392/// Otherwise, return false.
9393static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
9394 std::vector<Constant*> &Mask) {
9395 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
9396 "Invalid CollectSingleShuffleElements");
Reid Spencer9d6565a2007-02-15 02:26:10 +00009397 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00009398
9399 if (isa<UndefValue>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00009400 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00009401 return true;
9402 } else if (V == LHS) {
9403 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +00009404 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00009405 return true;
9406 } else if (V == RHS) {
9407 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +00009408 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00009409 return true;
9410 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
9411 // If this is an insert of an extract from some other vector, include it.
9412 Value *VecOp = IEI->getOperand(0);
9413 Value *ScalarOp = IEI->getOperand(1);
9414 Value *IdxOp = IEI->getOperand(2);
9415
Chris Lattnerd929f062006-04-27 21:14:21 +00009416 if (!isa<ConstantInt>(IdxOp))
9417 return false;
Reid Spencerb83eb642006-10-20 07:07:24 +00009418 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerd929f062006-04-27 21:14:21 +00009419
9420 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
9421 // Okay, we can handle this if the vector we are insertinting into is
9422 // transitively ok.
9423 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
9424 // If so, update the mask to reflect the inserted undef.
Reid Spencerc5b206b2006-12-31 05:48:39 +00009425 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
Chris Lattnerd929f062006-04-27 21:14:21 +00009426 return true;
9427 }
9428 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
9429 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00009430 EI->getOperand(0)->getType() == V->getType()) {
9431 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +00009432 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00009433
9434 // This must be extracting from either LHS or RHS.
9435 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
9436 // Okay, we can handle this if the vector we are insertinting into is
9437 // transitively ok.
9438 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
9439 // If so, update the mask to reflect the inserted value.
9440 if (EI->getOperand(0) == LHS) {
9441 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +00009442 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00009443 } else {
9444 assert(EI->getOperand(0) == RHS);
9445 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +00009446 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00009447
9448 }
9449 return true;
9450 }
9451 }
9452 }
9453 }
9454 }
9455 // TODO: Handle shufflevector here!
9456
9457 return false;
9458}
9459
9460/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
9461/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
9462/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +00009463static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00009464 Value *&RHS) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00009465 assert(isa<VectorType>(V->getType()) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00009466 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +00009467 "Invalid shuffle!");
Reid Spencer9d6565a2007-02-15 02:26:10 +00009468 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattnerefb47352006-04-15 01:39:45 +00009469
9470 if (isa<UndefValue>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00009471 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +00009472 return V;
9473 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00009474 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
Chris Lattnerefb47352006-04-15 01:39:45 +00009475 return V;
9476 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
9477 // If this is an insert of an extract from some other vector, include it.
9478 Value *VecOp = IEI->getOperand(0);
9479 Value *ScalarOp = IEI->getOperand(1);
9480 Value *IdxOp = IEI->getOperand(2);
9481
9482 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
9483 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
9484 EI->getOperand(0)->getType() == V->getType()) {
9485 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +00009486 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
9487 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +00009488
9489 // Either the extracted from or inserted into vector must be RHSVec,
9490 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00009491 if (EI->getOperand(0) == RHS || RHS == 0) {
9492 RHS = EI->getOperand(0);
9493 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +00009494 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +00009495 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +00009496 return V;
9497 }
9498
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00009499 if (VecOp == RHS) {
9500 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +00009501 // Everything but the extracted element is replaced with the RHS.
9502 for (unsigned i = 0; i != NumElts; ++i) {
9503 if (i != InsertedIdx)
Reid Spencerc5b206b2006-12-31 05:48:39 +00009504 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
Chris Lattnerefb47352006-04-15 01:39:45 +00009505 }
9506 return V;
9507 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00009508
9509 // If this insertelement is a chain that comes from exactly these two
9510 // vectors, return the vector and the effective shuffle.
9511 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
9512 return EI->getOperand(0);
9513
Chris Lattnerefb47352006-04-15 01:39:45 +00009514 }
9515 }
9516 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00009517 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +00009518
9519 // Otherwise, can't do anything fancy. Return an identity vector.
9520 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +00009521 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattnerefb47352006-04-15 01:39:45 +00009522 return V;
9523}
9524
9525Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
9526 Value *VecOp = IE.getOperand(0);
9527 Value *ScalarOp = IE.getOperand(1);
9528 Value *IdxOp = IE.getOperand(2);
9529
Chris Lattner599ded12007-04-09 01:11:16 +00009530 // Inserting an undef or into an undefined place, remove this.
9531 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
9532 ReplaceInstUsesWith(IE, VecOp);
9533
Chris Lattnerefb47352006-04-15 01:39:45 +00009534 // If the inserted element was extracted from some other vector, and if the
9535 // indexes are constant, try to turn this into a shufflevector operation.
9536 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
9537 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
9538 EI->getOperand(0)->getType() == IE.getType()) {
9539 unsigned NumVectorElts = IE.getType()->getNumElements();
Chris Lattnere34e9a22007-04-14 23:32:02 +00009540 unsigned ExtractedIdx =
9541 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Reid Spencerb83eb642006-10-20 07:07:24 +00009542 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +00009543
9544 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
9545 return ReplaceInstUsesWith(IE, VecOp);
9546
9547 if (InsertedIdx >= NumVectorElts) // Out of range insert.
9548 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
9549
9550 // If we are extracting a value from a vector, then inserting it right
9551 // back into the same place, just use the input vector.
9552 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
9553 return ReplaceInstUsesWith(IE, VecOp);
9554
9555 // We could theoretically do this for ANY input. However, doing so could
9556 // turn chains of insertelement instructions into a chain of shufflevector
9557 // instructions, and right now we do not merge shufflevectors. As such,
9558 // only do this in a situation where it is clear that there is benefit.
9559 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
9560 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
9561 // the values of VecOp, except then one read from EIOp0.
9562 // Build a new shuffle mask.
9563 std::vector<Constant*> Mask;
9564 if (isa<UndefValue>(VecOp))
Reid Spencerc5b206b2006-12-31 05:48:39 +00009565 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +00009566 else {
9567 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Reid Spencerc5b206b2006-12-31 05:48:39 +00009568 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
Chris Lattnerefb47352006-04-15 01:39:45 +00009569 NumVectorElts));
9570 }
Reid Spencerc5b206b2006-12-31 05:48:39 +00009571 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +00009572 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Reid Spencer9d6565a2007-02-15 02:26:10 +00009573 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +00009574 }
9575
9576 // If this insertelement isn't used by some other insertelement, turn it
9577 // (and any insertelements it points to), into one big shuffle.
9578 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
9579 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00009580 Value *RHS = 0;
9581 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
9582 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
9583 // We now have a shuffle of LHS, RHS, Mask.
Reid Spencer9d6565a2007-02-15 02:26:10 +00009584 return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +00009585 }
9586 }
9587 }
9588
9589 return 0;
9590}
9591
9592
Chris Lattnera844fc4c2006-04-10 22:45:52 +00009593Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
9594 Value *LHS = SVI.getOperand(0);
9595 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +00009596 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +00009597
9598 bool MadeChange = false;
9599
Chris Lattner867b99f2006-10-05 06:55:50 +00009600 // Undefined shuffle mask -> undefined value.
Chris Lattner863bcff2006-05-25 23:48:38 +00009601 if (isa<UndefValue>(SVI.getOperand(2)))
Chris Lattnera844fc4c2006-04-10 22:45:52 +00009602 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
9603
Chris Lattnere4929dd2007-01-05 07:36:08 +00009604 // If we have shuffle(x, undef, mask) and any elements of mask refer to
Chris Lattnerefb47352006-04-15 01:39:45 +00009605 // the undef, change them to undefs.
Chris Lattnere4929dd2007-01-05 07:36:08 +00009606 if (isa<UndefValue>(SVI.getOperand(1))) {
9607 // Scan to see if there are any references to the RHS. If so, replace them
9608 // with undef element refs and set MadeChange to true.
9609 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
9610 if (Mask[i] >= e && Mask[i] != 2*e) {
9611 Mask[i] = 2*e;
9612 MadeChange = true;
9613 }
9614 }
9615
9616 if (MadeChange) {
9617 // Remap any references to RHS to use LHS.
9618 std::vector<Constant*> Elts;
9619 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
9620 if (Mask[i] == 2*e)
9621 Elts.push_back(UndefValue::get(Type::Int32Ty));
9622 else
9623 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
9624 }
Reid Spencer9d6565a2007-02-15 02:26:10 +00009625 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattnere4929dd2007-01-05 07:36:08 +00009626 }
9627 }
Chris Lattnerefb47352006-04-15 01:39:45 +00009628
Chris Lattner863bcff2006-05-25 23:48:38 +00009629 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
9630 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
9631 if (LHS == RHS || isa<UndefValue>(LHS)) {
9632 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +00009633 // shuffle(undef,undef,mask) -> undef.
9634 return ReplaceInstUsesWith(SVI, LHS);
9635 }
9636
Chris Lattner863bcff2006-05-25 23:48:38 +00009637 // Remap any references to RHS to use LHS.
9638 std::vector<Constant*> Elts;
9639 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +00009640 if (Mask[i] >= 2*e)
Reid Spencerc5b206b2006-12-31 05:48:39 +00009641 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +00009642 else {
9643 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
9644 (Mask[i] < e && isa<UndefValue>(LHS)))
9645 Mask[i] = 2*e; // Turn into undef.
9646 else
9647 Mask[i] &= (e-1); // Force to LHS.
Reid Spencerc5b206b2006-12-31 05:48:39 +00009648 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +00009649 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +00009650 }
Chris Lattner863bcff2006-05-25 23:48:38 +00009651 SVI.setOperand(0, SVI.getOperand(1));
Chris Lattnera844fc4c2006-04-10 22:45:52 +00009652 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Reid Spencer9d6565a2007-02-15 02:26:10 +00009653 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +00009654 LHS = SVI.getOperand(0);
9655 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +00009656 MadeChange = true;
9657 }
9658
Chris Lattner7b2e27922006-05-26 00:29:06 +00009659 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +00009660 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +00009661
Chris Lattner863bcff2006-05-25 23:48:38 +00009662 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
9663 if (Mask[i] >= e*2) continue; // Ignore undef values.
9664 // Is this an identity shuffle of the LHS value?
9665 isLHSID &= (Mask[i] == i);
9666
9667 // Is this an identity shuffle of the RHS value?
9668 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +00009669 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +00009670
Chris Lattner863bcff2006-05-25 23:48:38 +00009671 // Eliminate identity shuffles.
9672 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
9673 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +00009674
Chris Lattner7b2e27922006-05-26 00:29:06 +00009675 // If the LHS is a shufflevector itself, see if we can combine it with this
9676 // one without producing an unusual shuffle. Here we are really conservative:
9677 // we are absolutely afraid of producing a shuffle mask not in the input
9678 // program, because the code gen may not be smart enough to turn a merged
9679 // shuffle into two specific shuffles: it may produce worse code. As such,
9680 // we only merge two shuffles if the result is one of the two input shuffle
9681 // masks. In this case, merging the shuffles just removes one instruction,
9682 // which we know is safe. This is good for things like turning:
9683 // (splat(splat)) -> splat.
9684 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
9685 if (isa<UndefValue>(RHS)) {
9686 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
9687
9688 std::vector<unsigned> NewMask;
9689 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
9690 if (Mask[i] >= 2*e)
9691 NewMask.push_back(2*e);
9692 else
9693 NewMask.push_back(LHSMask[Mask[i]]);
9694
9695 // If the result mask is equal to the src shuffle or this shuffle mask, do
9696 // the replacement.
9697 if (NewMask == LHSMask || NewMask == Mask) {
9698 std::vector<Constant*> Elts;
9699 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
9700 if (NewMask[i] >= e*2) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00009701 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +00009702 } else {
Reid Spencerc5b206b2006-12-31 05:48:39 +00009703 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +00009704 }
9705 }
9706 return new ShuffleVectorInst(LHSSVI->getOperand(0),
9707 LHSSVI->getOperand(1),
Reid Spencer9d6565a2007-02-15 02:26:10 +00009708 ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +00009709 }
9710 }
9711 }
Chris Lattnerc5eff442007-01-30 22:32:46 +00009712
Chris Lattnera844fc4c2006-04-10 22:45:52 +00009713 return MadeChange ? &SVI : 0;
9714}
9715
9716
Robert Bocchino1d7456d2006-01-13 22:48:06 +00009717
Chris Lattnerea1c4542004-12-08 23:43:58 +00009718
9719/// TryToSinkInstruction - Try to move the specified instruction from its
9720/// current block into the beginning of DestBlock, which can only happen if it's
9721/// safe to move the instruction past all of the instructions between it and the
9722/// end of its block.
9723static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
9724 assert(I->hasOneUse() && "Invariants didn't hold!");
9725
Chris Lattner108e9022005-10-27 17:13:11 +00009726 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
9727 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
Misha Brukmanfd939082005-04-21 23:48:37 +00009728
Chris Lattnerea1c4542004-12-08 23:43:58 +00009729 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +00009730 if (isa<AllocaInst>(I) && I->getParent() ==
9731 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +00009732 return false;
9733
Chris Lattner96a52a62004-12-09 07:14:34 +00009734 // We can only sink load instructions if there is nothing between the load and
9735 // the end of block that could change the value.
9736 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattner96a52a62004-12-09 07:14:34 +00009737 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
9738 Scan != E; ++Scan)
9739 if (Scan->mayWriteToMemory())
9740 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +00009741 }
Chris Lattnerea1c4542004-12-08 23:43:58 +00009742
9743 BasicBlock::iterator InsertPos = DestBlock->begin();
9744 while (isa<PHINode>(InsertPos)) ++InsertPos;
9745
Chris Lattner4bc5f802005-08-08 19:11:57 +00009746 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +00009747 ++NumSunkInst;
9748 return true;
9749}
9750
Chris Lattnerf4f5a772006-05-10 19:00:36 +00009751
9752/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
9753/// all reachable code to the worklist.
9754///
9755/// This has a couple of tricks to make the code faster and more powerful. In
9756/// particular, we constant fold and DCE instructions as we go, to avoid adding
9757/// them to the worklist (this significantly speeds up instcombine on code where
9758/// many instructions are dead or constant). Additionally, if we find a branch
9759/// whose condition is a known constant, we only visit the reachable successors.
9760///
9761static void AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +00009762 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +00009763 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +00009764 const TargetData *TD) {
Chris Lattner2c7718a2007-03-23 19:17:18 +00009765 std::vector<BasicBlock*> Worklist;
9766 Worklist.push_back(BB);
Chris Lattnerf4f5a772006-05-10 19:00:36 +00009767
Chris Lattner2c7718a2007-03-23 19:17:18 +00009768 while (!Worklist.empty()) {
9769 BB = Worklist.back();
9770 Worklist.pop_back();
9771
9772 // We have now visited this block! If we've already been here, ignore it.
9773 if (!Visited.insert(BB)) continue;
9774
9775 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
9776 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +00009777
Chris Lattner2c7718a2007-03-23 19:17:18 +00009778 // DCE instruction if trivially dead.
9779 if (isInstructionTriviallyDead(Inst)) {
9780 ++NumDeadInst;
9781 DOUT << "IC: DCE: " << *Inst;
9782 Inst->eraseFromParent();
9783 continue;
9784 }
9785
9786 // ConstantProp instruction if trivially constant.
9787 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
9788 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
9789 Inst->replaceAllUsesWith(C);
9790 ++NumConstProp;
9791 Inst->eraseFromParent();
9792 continue;
9793 }
9794
9795 IC.AddToWorkList(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +00009796 }
Chris Lattner2c7718a2007-03-23 19:17:18 +00009797
9798 // Recursively visit successors. If this is a branch or switch on a
9799 // constant, only visit the reachable successor.
9800 TerminatorInst *TI = BB->getTerminator();
9801 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
9802 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
9803 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
9804 Worklist.push_back(BI->getSuccessor(!CondVal));
9805 continue;
9806 }
9807 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
9808 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
9809 // See if this is an explicit destination.
9810 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
9811 if (SI->getCaseValue(i) == Cond) {
9812 Worklist.push_back(SI->getSuccessor(i));
9813 continue;
9814 }
9815
9816 // Otherwise it is the default destination.
9817 Worklist.push_back(SI->getSuccessor(0));
9818 continue;
9819 }
9820 }
9821
9822 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
9823 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +00009824 }
Chris Lattnerf4f5a772006-05-10 19:00:36 +00009825}
9826
Chris Lattnerec9c3582007-03-03 02:04:50 +00009827bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerdd841ae2002-04-18 17:39:14 +00009828 bool Changed = false;
Chris Lattnerbc61e662003-11-02 05:57:39 +00009829 TD = &getAnalysis<TargetData>();
Chris Lattnerec9c3582007-03-03 02:04:50 +00009830
9831 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
9832 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +00009833
Chris Lattnerb3d59702005-07-07 20:40:38 +00009834 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +00009835 // Do a depth-first traversal of the function, populate the worklist with
9836 // the reachable instructions. Ignore blocks that are not reachable. Keep
9837 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +00009838 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerdbab3862007-03-02 21:28:56 +00009839 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +00009840
Chris Lattnerb3d59702005-07-07 20:40:38 +00009841 // Do a quick scan over the function. If we find any blocks that are
9842 // unreachable, remove any instructions inside of them. This prevents
9843 // the instcombine code from having to deal with some bad special cases.
9844 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
9845 if (!Visited.count(BB)) {
9846 Instruction *Term = BB->getTerminator();
9847 while (Term != BB->begin()) { // Remove instrs bottom-up
9848 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +00009849
Bill Wendlingb7427032006-11-26 09:46:52 +00009850 DOUT << "IC: DCE: " << *I;
Chris Lattnerb3d59702005-07-07 20:40:38 +00009851 ++NumDeadInst;
9852
9853 if (!I->use_empty())
9854 I->replaceAllUsesWith(UndefValue::get(I->getType()));
9855 I->eraseFromParent();
9856 }
9857 }
9858 }
Chris Lattner8a2a3112001-12-14 16:52:21 +00009859
Chris Lattnerdbab3862007-03-02 21:28:56 +00009860 while (!Worklist.empty()) {
9861 Instruction *I = RemoveOneFromWorkList();
9862 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +00009863
Chris Lattner8c8c66a2006-05-11 17:11:52 +00009864 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +00009865 if (isInstructionTriviallyDead(I)) {
Chris Lattner8c8c66a2006-05-11 17:11:52 +00009866 // Add operands to the worklist.
Chris Lattner4bb7c022003-10-06 17:11:01 +00009867 if (I->getNumOperands() < 4)
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009868 AddUsesToWorkList(*I);
Chris Lattner62b14df2002-09-02 04:59:56 +00009869 ++NumDeadInst;
Chris Lattner4bb7c022003-10-06 17:11:01 +00009870
Bill Wendlingb7427032006-11-26 09:46:52 +00009871 DOUT << "IC: DCE: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +00009872
9873 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +00009874 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +00009875 continue;
9876 }
Chris Lattner62b14df2002-09-02 04:59:56 +00009877
Chris Lattner8c8c66a2006-05-11 17:11:52 +00009878 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattner0a19ffa2007-01-30 23:16:15 +00009879 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Bill Wendlingb7427032006-11-26 09:46:52 +00009880 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +00009881
Chris Lattner8c8c66a2006-05-11 17:11:52 +00009882 // Add operands to the worklist.
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009883 AddUsesToWorkList(*I);
Chris Lattnerc736d562002-12-05 22:41:53 +00009884 ReplaceInstUsesWith(*I, C);
9885
Chris Lattner62b14df2002-09-02 04:59:56 +00009886 ++NumConstProp;
Chris Lattnerf4f5a772006-05-10 19:00:36 +00009887 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +00009888 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +00009889 continue;
Chris Lattner62b14df2002-09-02 04:59:56 +00009890 }
Chris Lattner4bb7c022003-10-06 17:11:01 +00009891
Chris Lattnerea1c4542004-12-08 23:43:58 +00009892 // See if we can trivially sink this instruction to a successor basic block.
9893 if (I->hasOneUse()) {
9894 BasicBlock *BB = I->getParent();
9895 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
9896 if (UserParent != BB) {
9897 bool UserIsSuccessor = false;
9898 // See if the user is one of our successors.
9899 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
9900 if (*SI == UserParent) {
9901 UserIsSuccessor = true;
9902 break;
9903 }
9904
9905 // If the user is one of our immediate successors, and if that successor
9906 // only has us as a predecessors (we'd have to split the critical edge
9907 // otherwise), we can keep going.
9908 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
9909 next(pred_begin(UserParent)) == pred_end(UserParent))
9910 // Okay, the CFG is simple enough, try to sink this instruction.
9911 Changed |= TryToSinkInstruction(I, UserParent);
9912 }
9913 }
9914
Chris Lattner8a2a3112001-12-14 16:52:21 +00009915 // Now that we have an instruction, try combining it to simplify it...
Reid Spencera9b81012007-03-26 17:44:01 +00009916#ifndef NDEBUG
9917 std::string OrigI;
9918#endif
9919 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
Chris Lattner90ac28c2002-08-02 19:29:35 +00009920 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +00009921 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00009922 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +00009923 if (Result != I) {
Bill Wendlingb7427032006-11-26 09:46:52 +00009924 DOUT << "IC: Old = " << *I
9925 << " New = " << *Result;
Chris Lattner0cea42a2004-03-13 23:54:27 +00009926
Chris Lattnerf523d062004-06-09 05:08:07 +00009927 // Everything uses the new instruction now.
9928 I->replaceAllUsesWith(Result);
9929
9930 // Push the new instruction and any users onto the worklist.
Chris Lattnerdbab3862007-03-02 21:28:56 +00009931 AddToWorkList(Result);
Chris Lattnerf523d062004-06-09 05:08:07 +00009932 AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +00009933
Chris Lattner6934a042007-02-11 01:23:03 +00009934 // Move the name to the new instruction first.
9935 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +00009936
9937 // Insert the new instruction into the basic block...
9938 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +00009939 BasicBlock::iterator InsertPos = I;
9940
9941 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
9942 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
9943 ++InsertPos;
9944
9945 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +00009946
Chris Lattner00d51312004-05-01 23:27:23 +00009947 // Make sure that we reprocess all operands now that we reduced their
9948 // use counts.
Chris Lattnerdbab3862007-03-02 21:28:56 +00009949 AddUsesToWorkList(*I);
Chris Lattner216d4d82004-05-01 23:19:52 +00009950
Chris Lattnerf523d062004-06-09 05:08:07 +00009951 // Instructions can end up on the worklist more than once. Make sure
9952 // we do not process an instruction that has been deleted.
Chris Lattnerdbab3862007-03-02 21:28:56 +00009953 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +00009954
9955 // Erase the old instruction.
9956 InstParent->getInstList().erase(I);
Chris Lattner7e708292002-06-25 16:13:24 +00009957 } else {
Evan Chengc7baf682007-03-27 16:44:48 +00009958#ifndef NDEBUG
Reid Spencera9b81012007-03-26 17:44:01 +00009959 DOUT << "IC: Mod = " << OrigI
9960 << " New = " << *I;
Evan Chengc7baf682007-03-27 16:44:48 +00009961#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +00009962
Chris Lattner90ac28c2002-08-02 19:29:35 +00009963 // If the instruction was modified, it's possible that it is now dead.
9964 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +00009965 if (isInstructionTriviallyDead(I)) {
9966 // Make sure we process all operands now that we are reducing their
9967 // use counts.
Chris Lattnerec9c3582007-03-03 02:04:50 +00009968 AddUsesToWorkList(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +00009969
Chris Lattner00d51312004-05-01 23:27:23 +00009970 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchino1d7456d2006-01-13 22:48:06 +00009971 // occurrences of this instruction.
Chris Lattnerdbab3862007-03-02 21:28:56 +00009972 RemoveFromWorkList(I);
Chris Lattner2f503e62005-01-31 05:36:43 +00009973 I->eraseFromParent();
Chris Lattnerf523d062004-06-09 05:08:07 +00009974 } else {
Chris Lattnerec9c3582007-03-03 02:04:50 +00009975 AddToWorkList(I);
9976 AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +00009977 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +00009978 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00009979 Changed = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +00009980 }
9981 }
9982
Chris Lattnerec9c3582007-03-03 02:04:50 +00009983 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattnerdd841ae2002-04-18 17:39:14 +00009984 return Changed;
Chris Lattnerbd0ef772002-02-26 21:46:54 +00009985}
9986
Chris Lattnerec9c3582007-03-03 02:04:50 +00009987
9988bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +00009989 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
9990
Chris Lattnerec9c3582007-03-03 02:04:50 +00009991 bool EverMadeChange = false;
9992
9993 // Iterate while there is work to do.
9994 unsigned Iteration = 0;
9995 while (DoOneIteration(F, Iteration++))
9996 EverMadeChange = true;
9997 return EverMadeChange;
9998}
9999
Brian Gaeke96d4bf72004-07-27 17:43:21 +000010000FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000010001 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +000010002}
Brian Gaeked0fde302003-11-11 22:41:34 +000010003