blob: 1b7578904d5430f8dcee70d54246940f7ed8e951 [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//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha 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"
Nick Lewycky5be29202008-02-03 16:33:09 +000047#include "llvm/Support/ConstantRange.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000048#include "llvm/Support/Debug.h"
Chris Lattner28977af2004-04-05 01:30:19 +000049#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattnerdd841ae2002-04-18 17:39:14 +000050#include "llvm/Support/InstVisitor.h"
Chris Lattnerbcd7db52005-08-02 19:16:58 +000051#include "llvm/Support/MathExtras.h"
Chris Lattneracd1f0f2004-07-30 07:50:03 +000052#include "llvm/Support/PatternMatch.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000053#include "llvm/Support/Compiler.h"
Chris Lattnerdbab3862007-03-02 21:28:56 +000054#include "llvm/ADT/DenseMap.h"
Chris Lattner55eb1c42007-01-31 04:40:53 +000055#include "llvm/ADT/SmallVector.h"
Chris Lattner1f87a582007-02-15 19:41:52 +000056#include "llvm/ADT/SmallPtrSet.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000057#include "llvm/ADT/Statistic.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000058#include "llvm/ADT/STLExtras.h"
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000059#include <algorithm>
Reid Spencera9b81012007-03-26 17:44:01 +000060#include <sstream>
Chris Lattner67b1e1b2003-12-07 01:24:23 +000061using namespace llvm;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000062using namespace llvm::PatternMatch;
Brian Gaeked0fde302003-11-11 22:41:34 +000063
Chris Lattner0e5f4992006-12-19 21:40:18 +000064STATISTIC(NumCombined , "Number of insts combined");
65STATISTIC(NumConstProp, "Number of constant folds");
66STATISTIC(NumDeadInst , "Number of dead inst eliminated");
67STATISTIC(NumDeadStore, "Number of dead stores eliminated");
68STATISTIC(NumSunkInst , "Number of instructions sunk");
Chris Lattnera92f6962002-10-01 22:38:41 +000069
Chris Lattner0e5f4992006-12-19 21:40:18 +000070namespace {
Chris Lattnerf4b54612006-06-28 22:08:15 +000071 class VISIBILITY_HIDDEN InstCombiner
72 : public FunctionPass,
73 public InstVisitor<InstCombiner, Instruction*> {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000074 // Worklist of all of the instructions that need to be simplified.
Chris Lattnerdbab3862007-03-02 21:28:56 +000075 std::vector<Instruction*> Worklist;
76 DenseMap<Instruction*, unsigned> WorklistMap;
Chris Lattnerbc61e662003-11-02 05:57:39 +000077 TargetData *TD;
Chris Lattnerf964f322007-03-04 04:27:24 +000078 bool MustPreserveLCSSA;
Chris Lattnerdbab3862007-03-02 21:28:56 +000079 public:
Nick Lewyckyecd94c82007-05-06 13:37:16 +000080 static char ID; // Pass identification, replacement for typeid
Devang Patel794fd752007-05-01 21:15:47 +000081 InstCombiner() : FunctionPass((intptr_t)&ID) {}
82
Chris Lattnerdbab3862007-03-02 21:28:56 +000083 /// AddToWorkList - Add the specified instruction to the worklist if it
84 /// isn't already in it.
85 void AddToWorkList(Instruction *I) {
86 if (WorklistMap.insert(std::make_pair(I, Worklist.size())))
87 Worklist.push_back(I);
88 }
89
90 // RemoveFromWorkList - remove I from the worklist if it exists.
91 void RemoveFromWorkList(Instruction *I) {
92 DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
93 if (It == WorklistMap.end()) return; // Not in worklist.
94
95 // Don't bother moving everything down, just null out the slot.
96 Worklist[It->second] = 0;
97
98 WorklistMap.erase(It);
99 }
100
101 Instruction *RemoveOneFromWorkList() {
102 Instruction *I = Worklist.back();
103 Worklist.pop_back();
104 WorklistMap.erase(I);
105 return I;
106 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000107
Chris Lattnerdbab3862007-03-02 21:28:56 +0000108
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000109 /// AddUsersToWorkList - When an instruction is simplified, add all users of
110 /// the instruction to the work lists because they might get more simplified
111 /// now.
112 ///
Chris Lattner6dce1a72006-02-07 06:56:34 +0000113 void AddUsersToWorkList(Value &I) {
Chris Lattner7e708292002-06-25 16:13:24 +0000114 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000115 UI != UE; ++UI)
Chris Lattnerdbab3862007-03-02 21:28:56 +0000116 AddToWorkList(cast<Instruction>(*UI));
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000117 }
118
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000119 /// AddUsesToWorkList - When an instruction is simplified, add operands to
120 /// the work lists because they might get more simplified now.
121 ///
122 void AddUsesToWorkList(Instruction &I) {
123 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
124 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
Chris Lattnerdbab3862007-03-02 21:28:56 +0000125 AddToWorkList(Op);
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000126 }
Chris Lattner867b99f2006-10-05 06:55:50 +0000127
128 /// AddSoonDeadInstToWorklist - The specified instruction is about to become
129 /// dead. Add all of its operands to the worklist, turning them into
130 /// undef's to reduce the number of uses of those instructions.
131 ///
132 /// Return the specified operand before it is turned into an undef.
133 ///
134 Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
135 Value *R = I.getOperand(op);
136
137 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
138 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i))) {
Chris Lattnerdbab3862007-03-02 21:28:56 +0000139 AddToWorkList(Op);
Chris Lattner867b99f2006-10-05 06:55:50 +0000140 // Set the operand to undef to drop the use.
141 I.setOperand(i, UndefValue::get(Op->getType()));
142 }
143
144 return R;
145 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000146
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000147 public:
Chris Lattner7e708292002-06-25 16:13:24 +0000148 virtual bool runOnFunction(Function &F);
Chris Lattnerec9c3582007-03-03 02:04:50 +0000149
150 bool DoOneIteration(Function &F, unsigned ItNum);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000151
Chris Lattner97e52e42002-04-28 21:27:06 +0000152 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerbc61e662003-11-02 05:57:39 +0000153 AU.addRequired<TargetData>();
Owen Andersond1b78a12006-07-10 19:03:49 +0000154 AU.addPreservedID(LCSSAID);
Chris Lattnercb2610e2002-10-21 20:00:28 +0000155 AU.setPreservesCFG();
Chris Lattner97e52e42002-04-28 21:27:06 +0000156 }
157
Chris Lattner28977af2004-04-05 01:30:19 +0000158 TargetData &getTargetData() const { return *TD; }
159
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000160 // Visitation implementation - Implement instruction combining for different
161 // instruction types. The semantics are as follows:
162 // Return Value:
163 // null - No change was made
Chris Lattner233f7dc2002-08-12 21:17:25 +0000164 // I - Change was made, I is still valid, I may be dead though
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000165 // otherwise - Change was made, replace I with returned instruction
Misha Brukmanfd939082005-04-21 23:48:37 +0000166 //
Chris Lattner7e708292002-06-25 16:13:24 +0000167 Instruction *visitAdd(BinaryOperator &I);
168 Instruction *visitSub(BinaryOperator &I);
169 Instruction *visitMul(BinaryOperator &I);
Reid Spencer0a783f72006-11-02 01:53:59 +0000170 Instruction *visitURem(BinaryOperator &I);
171 Instruction *visitSRem(BinaryOperator &I);
172 Instruction *visitFRem(BinaryOperator &I);
173 Instruction *commonRemTransforms(BinaryOperator &I);
174 Instruction *commonIRemTransforms(BinaryOperator &I);
Reid Spencer1628cec2006-10-26 06:15:43 +0000175 Instruction *commonDivTransforms(BinaryOperator &I);
176 Instruction *commonIDivTransforms(BinaryOperator &I);
177 Instruction *visitUDiv(BinaryOperator &I);
178 Instruction *visitSDiv(BinaryOperator &I);
179 Instruction *visitFDiv(BinaryOperator &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000180 Instruction *visitAnd(BinaryOperator &I);
181 Instruction *visitOr (BinaryOperator &I);
182 Instruction *visitXor(BinaryOperator &I);
Reid Spencer832254e2007-02-02 02:16:23 +0000183 Instruction *visitShl(BinaryOperator &I);
184 Instruction *visitAShr(BinaryOperator &I);
185 Instruction *visitLShr(BinaryOperator &I);
186 Instruction *commonShiftTransforms(BinaryOperator &I);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000187 Instruction *visitFCmpInst(FCmpInst &I);
188 Instruction *visitICmpInst(ICmpInst &I);
189 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
Chris Lattner01deb9d2007-04-03 17:43:25 +0000190 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
191 Instruction *LHS,
192 ConstantInt *RHS);
Chris Lattner562ef782007-06-20 23:46:26 +0000193 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
194 ConstantInt *DivRHS);
Chris Lattner484d3cf2005-04-24 06:59:08 +0000195
Reid Spencere4d87aa2006-12-23 06:05:41 +0000196 Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
197 ICmpInst::Predicate Cond, Instruction &I);
Reid Spencerb83eb642006-10-20 07:07:24 +0000198 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +0000199 BinaryOperator &I);
Reid Spencer3da59db2006-11-27 01:05:10 +0000200 Instruction *commonCastTransforms(CastInst &CI);
201 Instruction *commonIntCastTransforms(CastInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000202 Instruction *commonPointerCastTransforms(CastInst &CI);
Chris Lattner8a9f5712007-04-11 06:57:46 +0000203 Instruction *visitTrunc(TruncInst &CI);
204 Instruction *visitZExt(ZExtInst &CI);
205 Instruction *visitSExt(SExtInst &CI);
Chris Lattnerb7530652008-01-27 05:29:54 +0000206 Instruction *visitFPTrunc(FPTruncInst &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000207 Instruction *visitFPExt(CastInst &CI);
208 Instruction *visitFPToUI(CastInst &CI);
209 Instruction *visitFPToSI(CastInst &CI);
210 Instruction *visitUIToFP(CastInst &CI);
211 Instruction *visitSIToFP(CastInst &CI);
212 Instruction *visitPtrToInt(CastInst &CI);
Chris Lattnerf9d9e452008-01-08 07:23:51 +0000213 Instruction *visitIntToPtr(IntToPtrInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000214 Instruction *visitBitCast(BitCastInst &CI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +0000215 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
216 Instruction *FI);
Chris Lattner3d69f462004-03-12 05:52:32 +0000217 Instruction *visitSelectInst(SelectInst &CI);
Chris Lattner9fe38862003-06-19 17:00:31 +0000218 Instruction *visitCallInst(CallInst &CI);
219 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner7e708292002-06-25 16:13:24 +0000220 Instruction *visitPHINode(PHINode &PN);
221 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner0864acf2002-11-04 16:18:53 +0000222 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner67b1e1b2003-12-07 01:24:23 +0000223 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner833b8a42003-06-26 05:06:25 +0000224 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner2f503e62005-01-31 05:36:43 +0000225 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattnerc4d10eb2003-06-04 04:46:00 +0000226 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner46238a62004-07-03 00:26:11 +0000227 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattnerefb47352006-04-15 01:39:45 +0000228 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchino1d7456d2006-01-13 22:48:06 +0000229 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +0000230 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000231
232 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner7e708292002-06-25 16:13:24 +0000233 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner8b170942002-08-09 23:47:40 +0000234
Chris Lattner9fe38862003-06-19 17:00:31 +0000235 private:
Chris Lattnera44d8a22003-10-07 22:32:43 +0000236 Instruction *visitCallSite(CallSite CS);
Chris Lattner9fe38862003-06-19 17:00:31 +0000237 bool transformConstExprCastCall(CallSite CS);
Duncan Sandscdb6d922007-09-17 10:26:40 +0000238 Instruction *transformCallThroughTrampoline(CallSite CS);
Chris Lattner9fe38862003-06-19 17:00:31 +0000239
Chris Lattner28977af2004-04-05 01:30:19 +0000240 public:
Chris Lattner8b170942002-08-09 23:47:40 +0000241 // InsertNewInstBefore - insert an instruction New before instruction Old
242 // in the program. Add the new instruction to the worklist.
243 //
Chris Lattner955f3312004-09-28 21:48:02 +0000244 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattnere6f9a912002-08-23 18:32:43 +0000245 assert(New && New->getParent() == 0 &&
246 "New instruction already inserted into a basic block!");
Chris Lattner8b170942002-08-09 23:47:40 +0000247 BasicBlock *BB = Old.getParent();
248 BB->getInstList().insert(&Old, New); // Insert inst
Chris Lattnerdbab3862007-03-02 21:28:56 +0000249 AddToWorkList(New);
Chris Lattner4cb170c2004-02-23 06:38:22 +0000250 return New;
Chris Lattner8b170942002-08-09 23:47:40 +0000251 }
252
Chris Lattner0c967662004-09-24 15:21:34 +0000253 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
254 /// This also adds the cast to the worklist. Finally, this returns the
255 /// cast.
Reid Spencer17212df2006-12-12 09:18:51 +0000256 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
257 Instruction &Pos) {
Chris Lattner0c967662004-09-24 15:21:34 +0000258 if (V->getType() == Ty) return V;
Misha Brukmanfd939082005-04-21 23:48:37 +0000259
Chris Lattnere2ed0572006-04-06 19:19:17 +0000260 if (Constant *CV = dyn_cast<Constant>(V))
Reid Spencer17212df2006-12-12 09:18:51 +0000261 return ConstantExpr::getCast(opc, CV, Ty);
Chris Lattnere2ed0572006-04-06 19:19:17 +0000262
Reid Spencer17212df2006-12-12 09:18:51 +0000263 Instruction *C = CastInst::create(opc, V, Ty, V->getName(), &Pos);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000264 AddToWorkList(C);
Chris Lattner0c967662004-09-24 15:21:34 +0000265 return C;
266 }
Chris Lattner6d0339d2008-01-13 22:23:22 +0000267
268 Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
269 return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
270 }
271
Chris Lattner0c967662004-09-24 15:21:34 +0000272
Chris Lattner8b170942002-08-09 23:47:40 +0000273 // ReplaceInstUsesWith - This method is to be used when an instruction is
274 // found to be dead, replacable with another preexisting expression. Here
275 // we add all uses of I to the worklist, replace all uses of I with the new
276 // value, then return I, so that the inst combiner will know that I was
277 // modified.
278 //
279 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000280 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner15a76c02004-04-05 02:10:19 +0000281 if (&I != V) {
282 I.replaceAllUsesWith(V);
283 return &I;
284 } else {
285 // If we are replacing the instruction with itself, this must be in a
286 // segment of unreachable code, so just clobber the instruction.
Chris Lattner17be6352004-10-18 02:59:09 +0000287 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +0000288 return &I;
289 }
Chris Lattner8b170942002-08-09 23:47:40 +0000290 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000291
Chris Lattner6dce1a72006-02-07 06:56:34 +0000292 // UpdateValueUsesWith - This method is to be used when an value is
293 // found to be replacable with another preexisting expression or was
294 // updated. Here we add all uses of I to the worklist, replace all uses of
295 // I with the new value (unless the instruction was just updated), then
296 // return true, so that the inst combiner will know that I was modified.
297 //
298 bool UpdateValueUsesWith(Value *Old, Value *New) {
299 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
300 if (Old != New)
301 Old->replaceAllUsesWith(New);
302 if (Instruction *I = dyn_cast<Instruction>(Old))
Chris Lattnerdbab3862007-03-02 21:28:56 +0000303 AddToWorkList(I);
Chris Lattnerf8c36f52006-02-12 08:02:11 +0000304 if (Instruction *I = dyn_cast<Instruction>(New))
Chris Lattnerdbab3862007-03-02 21:28:56 +0000305 AddToWorkList(I);
Chris Lattner6dce1a72006-02-07 06:56:34 +0000306 return true;
307 }
308
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000309 // EraseInstFromFunction - When dealing with an instruction that has side
310 // effects or produces a void value, we can't rely on DCE to delete the
311 // instruction. Instead, visit methods should return the value returned by
312 // this function.
313 Instruction *EraseInstFromFunction(Instruction &I) {
314 assert(I.use_empty() && "Cannot erase instruction that is used!");
315 AddUsesToWorkList(I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000316 RemoveFromWorkList(&I);
Chris Lattner954f66a2004-11-18 21:41:39 +0000317 I.eraseFromParent();
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000318 return 0; // Don't do anything with FI
319 }
320
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000321 private:
Chris Lattner24c8e382003-07-24 17:35:25 +0000322 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
323 /// InsertBefore instruction. This is specialized a bit to avoid inserting
324 /// casts that are known to not do anything...
325 ///
Reid Spencer17212df2006-12-12 09:18:51 +0000326 Value *InsertOperandCastBefore(Instruction::CastOps opcode,
327 Value *V, const Type *DestTy,
Chris Lattner24c8e382003-07-24 17:35:25 +0000328 Instruction *InsertBefore);
329
Reid Spencere4d87aa2006-12-23 06:05:41 +0000330 /// SimplifyCommutative - This performs a few simplifications for
331 /// commutative operators.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000332 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000333
Reid Spencere4d87aa2006-12-23 06:05:41 +0000334 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
335 /// most-complex to least-complex order.
336 bool SimplifyCompare(CmpInst &I);
337
Reid Spencer2ec619a2007-03-23 21:24:59 +0000338 /// SimplifyDemandedBits - Attempts to replace V with a simpler value based
339 /// on the demanded bits.
Reid Spencer8cb68342007-03-12 17:25:59 +0000340 bool SimplifyDemandedBits(Value *V, APInt DemandedMask,
341 APInt& KnownZero, APInt& KnownOne,
342 unsigned Depth = 0);
343
Chris Lattner867b99f2006-10-05 06:55:50 +0000344 Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
345 uint64_t &UndefElts, unsigned Depth = 0);
346
Chris Lattner4e998b22004-09-29 05:07:12 +0000347 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
348 // PHI node as operand #0, see if we can fold the instruction into the PHI
349 // (which is only possible if all operands to the PHI are constants).
350 Instruction *FoldOpIntoPhi(Instruction &I);
351
Chris Lattnerbac32862004-11-14 19:13:23 +0000352 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
353 // operator and they all are only used by the PHI, PHI together their
354 // inputs, and do the operation once, to the result of the PHI.
355 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
Chris Lattner7da52b22006-11-01 04:51:18 +0000356 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
357
358
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000359 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
360 ConstantInt *AndRHS, BinaryOperator &TheAnd);
Chris Lattnerc8e77562005-09-18 04:24:45 +0000361
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000362 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
Chris Lattnerc8e77562005-09-18 04:24:45 +0000363 bool isSub, Instruction &I);
Chris Lattnera96879a2004-09-29 17:40:11 +0000364 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000365 bool isSigned, bool Inside, Instruction &IB);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000366 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
Chris Lattnerafe91a52006-06-15 19:07:26 +0000367 Instruction *MatchBSwap(BinaryOperator &I);
Chris Lattner3284d1f2007-04-15 00:07:55 +0000368 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000369 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
370
Chris Lattnerafe91a52006-06-15 19:07:26 +0000371
Reid Spencerc55b2432006-12-13 18:21:21 +0000372 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000373 };
Chris Lattnerf6293092002-07-23 18:06:35 +0000374
Devang Patel19974732007-05-03 01:11:54 +0000375 char InstCombiner::ID = 0;
Chris Lattner7f8897f2006-08-27 22:42:52 +0000376 RegisterPass<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000377}
378
Chris Lattner4f98c562003-03-10 21:43:22 +0000379// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattnere87597f2004-10-16 18:11:37 +0000380// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattner4f98c562003-03-10 21:43:22 +0000381static unsigned getComplexity(Value *V) {
382 if (isa<Instruction>(V)) {
383 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattnere87597f2004-10-16 18:11:37 +0000384 return 3;
385 return 4;
Chris Lattner4f98c562003-03-10 21:43:22 +0000386 }
Chris Lattnere87597f2004-10-16 18:11:37 +0000387 if (isa<Argument>(V)) return 3;
388 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattner4f98c562003-03-10 21:43:22 +0000389}
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000390
Chris Lattnerc8802d22003-03-11 00:12:48 +0000391// isOnlyUse - Return true if this instruction will be deleted if we stop using
392// it.
393static bool isOnlyUse(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000394 return V->hasOneUse() || isa<Constant>(V);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000395}
396
Chris Lattner4cb170c2004-02-23 06:38:22 +0000397// getPromotedType - Return the specified type promoted as it would be to pass
398// though a va_arg area...
399static const Type *getPromotedType(const Type *Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000400 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
401 if (ITy->getBitWidth() < 32)
402 return Type::Int32Ty;
Chris Lattner2b7e0ad2007-05-23 01:17:04 +0000403 }
Reid Spencera54b7cb2007-01-12 07:05:14 +0000404 return Ty;
Chris Lattner4cb170c2004-02-23 06:38:22 +0000405}
406
Reid Spencer3da59db2006-11-27 01:05:10 +0000407/// getBitCastOperand - If the specified operand is a CastInst or a constant
408/// expression bitcast, return the operand value, otherwise return null.
409static Value *getBitCastOperand(Value *V) {
410 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
Chris Lattnereed48272005-09-13 00:40:14 +0000411 return I->getOperand(0);
412 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Reid Spencer3da59db2006-11-27 01:05:10 +0000413 if (CE->getOpcode() == Instruction::BitCast)
Chris Lattnereed48272005-09-13 00:40:14 +0000414 return CE->getOperand(0);
415 return 0;
416}
417
Reid Spencer3da59db2006-11-27 01:05:10 +0000418/// This function is a wrapper around CastInst::isEliminableCastPair. It
419/// simply extracts arguments and returns what that function returns.
Reid Spencer3da59db2006-11-27 01:05:10 +0000420static Instruction::CastOps
421isEliminableCastPair(
422 const CastInst *CI, ///< The first cast instruction
423 unsigned opcode, ///< The opcode of the second cast instruction
424 const Type *DstTy, ///< The target type for the second cast instruction
425 TargetData *TD ///< The target data for pointer size
426) {
427
428 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
429 const Type *MidTy = CI->getType(); // B from above
Chris Lattner33a61132006-05-06 09:00:16 +0000430
Reid Spencer3da59db2006-11-27 01:05:10 +0000431 // Get the opcodes of the two Cast instructions
432 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
433 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner33a61132006-05-06 09:00:16 +0000434
Reid Spencer3da59db2006-11-27 01:05:10 +0000435 return Instruction::CastOps(
436 CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
437 DstTy, TD->getIntPtrType()));
Chris Lattner33a61132006-05-06 09:00:16 +0000438}
439
440/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
441/// in any code being generated. It does not require codegen if V is simple
442/// enough or if the cast can be folded into other casts.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000443static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
444 const Type *Ty, TargetData *TD) {
Chris Lattner33a61132006-05-06 09:00:16 +0000445 if (V->getType() == Ty || isa<Constant>(V)) return false;
446
Chris Lattner01575b72006-05-25 23:24:33 +0000447 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner33a61132006-05-06 09:00:16 +0000448 if (const CastInst *CI = dyn_cast<CastInst>(V))
Reid Spencere4d87aa2006-12-23 06:05:41 +0000449 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner33a61132006-05-06 09:00:16 +0000450 return false;
451 return true;
452}
453
454/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
455/// InsertBefore instruction. This is specialized a bit to avoid inserting
456/// casts that are known to not do anything...
457///
Reid Spencer17212df2006-12-12 09:18:51 +0000458Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
459 Value *V, const Type *DestTy,
Chris Lattner33a61132006-05-06 09:00:16 +0000460 Instruction *InsertBefore) {
461 if (V->getType() == DestTy) return V;
462 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencer17212df2006-12-12 09:18:51 +0000463 return ConstantExpr::getCast(opcode, C, DestTy);
Chris Lattner33a61132006-05-06 09:00:16 +0000464
Reid Spencer17212df2006-12-12 09:18:51 +0000465 return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
Chris Lattner33a61132006-05-06 09:00:16 +0000466}
467
Chris Lattner4f98c562003-03-10 21:43:22 +0000468// SimplifyCommutative - This performs a few simplifications for commutative
469// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000470//
Chris Lattner4f98c562003-03-10 21:43:22 +0000471// 1. Order operands such that they are listed from right (least complex) to
472// left (most complex). This puts constants before unary operators before
473// binary operators.
474//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000475// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
476// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000477//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000478bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000479 bool Changed = false;
480 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
481 Changed = !I.swapOperands();
Misha Brukmanfd939082005-04-21 23:48:37 +0000482
Chris Lattner4f98c562003-03-10 21:43:22 +0000483 if (!I.isAssociative()) return Changed;
484 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000485 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
486 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
487 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner2a9c8472003-05-27 16:40:51 +0000488 Constant *Folded = ConstantExpr::get(I.getOpcode(),
489 cast<Constant>(I.getOperand(1)),
490 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000491 I.setOperand(0, Op->getOperand(0));
492 I.setOperand(1, Folded);
493 return true;
494 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
495 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
496 isOnlyUse(Op) && isOnlyUse(Op1)) {
497 Constant *C1 = cast<Constant>(Op->getOperand(1));
498 Constant *C2 = cast<Constant>(Op1->getOperand(1));
499
500 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner2a9c8472003-05-27 16:40:51 +0000501 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000502 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
503 Op1->getOperand(0),
504 Op1->getName(), &I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000505 AddToWorkList(New);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000506 I.setOperand(0, New);
507 I.setOperand(1, Folded);
508 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000509 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000510 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000511 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000512}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000513
Reid Spencere4d87aa2006-12-23 06:05:41 +0000514/// SimplifyCompare - For a CmpInst this function just orders the operands
515/// so that theyare listed from right (least complex) to left (most complex).
516/// This puts constants before unary operators before binary operators.
517bool InstCombiner::SimplifyCompare(CmpInst &I) {
518 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
519 return false;
520 I.swapOperands();
521 // Compare instructions are not associative so there's nothing else we can do.
522 return true;
523}
524
Chris Lattner8d969642003-03-10 23:06:50 +0000525// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
526// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000527//
Chris Lattner8d969642003-03-10 23:06:50 +0000528static inline Value *dyn_castNegVal(Value *V) {
529 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000530 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000531
Chris Lattner0ce85802004-12-14 20:08:06 +0000532 // Constants can be considered to be negated values if they can be folded.
533 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
534 return ConstantExpr::getNeg(C);
Chris Lattner8d969642003-03-10 23:06:50 +0000535 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000536}
537
Chris Lattner8d969642003-03-10 23:06:50 +0000538static inline Value *dyn_castNotVal(Value *V) {
539 if (BinaryOperator::isNot(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000540 return BinaryOperator::getNotArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000541
542 // Constants can be considered to be not'ed values...
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000543 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Zhou Sheng4a1822a2007-04-02 13:45:30 +0000544 return ConstantInt::get(~C->getValue());
Chris Lattner8d969642003-03-10 23:06:50 +0000545 return 0;
546}
547
Chris Lattnerc8802d22003-03-11 00:12:48 +0000548// dyn_castFoldableMul - If this value is a multiply that can be folded into
549// other computations (because it has a constant operand), return the
Chris Lattner50af16a2004-11-13 19:50:12 +0000550// non-constant operand of the multiply, and set CST to point to the multiplier.
551// Otherwise, return null.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000552//
Chris Lattner50af16a2004-11-13 19:50:12 +0000553static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattner42a75512007-01-15 02:27:26 +0000554 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner50af16a2004-11-13 19:50:12 +0000555 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000556 if (I->getOpcode() == Instruction::Mul)
Chris Lattner50e60c72004-11-15 05:54:07 +0000557 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000558 return I->getOperand(0);
Chris Lattner50af16a2004-11-13 19:50:12 +0000559 if (I->getOpcode() == Instruction::Shl)
Chris Lattner50e60c72004-11-15 05:54:07 +0000560 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000561 // The multiplier is really 1 << CST.
Zhou Sheng97b52c22007-03-29 01:57:21 +0000562 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000563 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Zhou Sheng97b52c22007-03-29 01:57:21 +0000564 CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
Chris Lattner50af16a2004-11-13 19:50:12 +0000565 return I->getOperand(0);
566 }
567 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000568 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000569}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000570
Chris Lattner574da9b2005-01-13 20:14:25 +0000571/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
572/// expression, return it.
573static User *dyn_castGetElementPtr(Value *V) {
574 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
575 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
576 if (CE->getOpcode() == Instruction::GetElementPtr)
577 return cast<User>(V);
578 return false;
579}
580
Reid Spencer7177c3a2007-03-25 05:33:51 +0000581/// AddOne - Add one to a ConstantInt
Chris Lattnera96879a2004-09-29 17:40:11 +0000582static ConstantInt *AddOne(ConstantInt *C) {
Reid Spencer2149a9d2007-03-25 19:55:33 +0000583 APInt Val(C->getValue());
584 return ConstantInt::get(++Val);
Chris Lattner955f3312004-09-28 21:48:02 +0000585}
Reid Spencer7177c3a2007-03-25 05:33:51 +0000586/// SubOne - Subtract one from a ConstantInt
Chris Lattnera96879a2004-09-29 17:40:11 +0000587static ConstantInt *SubOne(ConstantInt *C) {
Reid Spencer2149a9d2007-03-25 19:55:33 +0000588 APInt Val(C->getValue());
589 return ConstantInt::get(--Val);
Reid Spencer7177c3a2007-03-25 05:33:51 +0000590}
591/// Add - Add two ConstantInts together
592static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
593 return ConstantInt::get(C1->getValue() + C2->getValue());
594}
595/// And - Bitwise AND two ConstantInts together
596static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
597 return ConstantInt::get(C1->getValue() & C2->getValue());
598}
599/// Subtract - Subtract one ConstantInt from another
600static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
601 return ConstantInt::get(C1->getValue() - C2->getValue());
602}
603/// Multiply - Multiply two ConstantInts together
604static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
605 return ConstantInt::get(C1->getValue() * C2->getValue());
Chris Lattner955f3312004-09-28 21:48:02 +0000606}
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000607/// MultiplyOverflows - True if the multiply can not be expressed in an int
608/// this size.
609static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
610 uint32_t W = C1->getBitWidth();
611 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
612 if (sign) {
613 LHSExt.sext(W * 2);
614 RHSExt.sext(W * 2);
615 } else {
616 LHSExt.zext(W * 2);
617 RHSExt.zext(W * 2);
618 }
619
620 APInt MulExt = LHSExt * RHSExt;
621
622 if (sign) {
623 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
624 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
625 return MulExt.slt(Min) || MulExt.sgt(Max);
626 } else
627 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
628}
Chris Lattner955f3312004-09-28 21:48:02 +0000629
Chris Lattner68d5ff22006-02-09 07:38:58 +0000630/// ComputeMaskedBits - Determine which of the bits specified in Mask are
631/// known to be either zero or one and return them in the KnownZero/KnownOne
Reid Spencer3e7594f2007-03-08 01:46:38 +0000632/// bit sets. This code only analyzes bits in Mask, in order to short-circuit
633/// processing.
634/// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
635/// we cannot optimize based on the assumption that it is zero without changing
636/// it to be an explicit zero. If we don't change it to zero, other code could
637/// optimized based on the contradictory assumption that it is non-zero.
638/// Because instcombine aggressively folds operations with undef args anyway,
639/// this won't lose us code quality.
Reid Spencer55702aa2007-03-25 21:11:44 +0000640static void ComputeMaskedBits(Value *V, const APInt &Mask, APInt& KnownZero,
Reid Spencer3e7594f2007-03-08 01:46:38 +0000641 APInt& KnownOne, unsigned Depth = 0) {
Zhou Sheng771dbf72007-03-13 02:23:10 +0000642 assert(V && "No Value?");
643 assert(Depth <= 6 && "Limit Search Depth");
Reid Spencer3e7594f2007-03-08 01:46:38 +0000644 uint32_t BitWidth = Mask.getBitWidth();
Zhou Shengaa305ab2007-03-28 02:19:03 +0000645 assert(cast<IntegerType>(V->getType())->getBitWidth() == BitWidth &&
Zhou Sheng771dbf72007-03-13 02:23:10 +0000646 KnownZero.getBitWidth() == BitWidth &&
Reid Spencer3e7594f2007-03-08 01:46:38 +0000647 KnownOne.getBitWidth() == BitWidth &&
Zhou Shengaa305ab2007-03-28 02:19:03 +0000648 "V, Mask, KnownOne and KnownZero should have same BitWidth");
Reid Spencer3e7594f2007-03-08 01:46:38 +0000649 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
650 // We know all of the bits for a constant!
Zhou Sheng771dbf72007-03-13 02:23:10 +0000651 KnownOne = CI->getValue() & Mask;
Reid Spencer3e7594f2007-03-08 01:46:38 +0000652 KnownZero = ~KnownOne & Mask;
653 return;
654 }
655
Reid Spencer3e7594f2007-03-08 01:46:38 +0000656 if (Depth == 6 || Mask == 0)
657 return; // Limit search depth.
658
659 Instruction *I = dyn_cast<Instruction>(V);
660 if (!I) return;
661
Zhou Sheng771dbf72007-03-13 02:23:10 +0000662 KnownZero.clear(); KnownOne.clear(); // Don't know anything.
Reid Spencer3e7594f2007-03-08 01:46:38 +0000663 APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000664
665 switch (I->getOpcode()) {
Reid Spencer2b812072007-03-25 02:03:12 +0000666 case Instruction::And: {
Reid Spencer3e7594f2007-03-08 01:46:38 +0000667 // If either the LHS or the RHS are Zero, the result is zero.
668 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
Reid Spencer2b812072007-03-25 02:03:12 +0000669 APInt Mask2(Mask & ~KnownZero);
670 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000671 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
672 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
673
674 // Output known-1 bits are only known if set in both the LHS & RHS.
675 KnownOne &= KnownOne2;
676 // Output known-0 are known to be clear if zero in either the LHS | RHS.
677 KnownZero |= KnownZero2;
678 return;
Reid Spencer2b812072007-03-25 02:03:12 +0000679 }
680 case Instruction::Or: {
Reid Spencer3e7594f2007-03-08 01:46:38 +0000681 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
Reid Spencer2b812072007-03-25 02:03:12 +0000682 APInt Mask2(Mask & ~KnownOne);
683 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000684 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
685 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
686
687 // Output known-0 bits are only known if clear in both the LHS & RHS.
688 KnownZero &= KnownZero2;
689 // Output known-1 are known to be set if set in either the LHS | RHS.
690 KnownOne |= KnownOne2;
691 return;
Reid Spencer2b812072007-03-25 02:03:12 +0000692 }
Reid Spencer3e7594f2007-03-08 01:46:38 +0000693 case Instruction::Xor: {
694 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
695 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
696 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
697 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
698
699 // Output known-0 bits are known if clear or set in both the LHS & RHS.
700 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
701 // Output known-1 are known to be set if set in only one of the LHS, RHS.
702 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
703 KnownZero = KnownZeroOut;
704 return;
705 }
706 case Instruction::Select:
707 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
708 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
709 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
710 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
711
712 // Only known if known in both the LHS and RHS.
713 KnownOne &= KnownOne2;
714 KnownZero &= KnownZero2;
715 return;
716 case Instruction::FPTrunc:
717 case Instruction::FPExt:
718 case Instruction::FPToUI:
719 case Instruction::FPToSI:
720 case Instruction::SIToFP:
721 case Instruction::PtrToInt:
722 case Instruction::UIToFP:
723 case Instruction::IntToPtr:
724 return; // Can't work with floating point or pointers
Zhou Sheng771dbf72007-03-13 02:23:10 +0000725 case Instruction::Trunc: {
Reid Spencer3e7594f2007-03-08 01:46:38 +0000726 // All these have integer operands
Zhou Sheng771dbf72007-03-13 02:23:10 +0000727 uint32_t SrcBitWidth =
728 cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
Zhou Shengaa305ab2007-03-28 02:19:03 +0000729 APInt MaskIn(Mask);
730 MaskIn.zext(SrcBitWidth);
731 KnownZero.zext(SrcBitWidth);
732 KnownOne.zext(SrcBitWidth);
733 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
Zhou Sheng771dbf72007-03-13 02:23:10 +0000734 KnownZero.trunc(BitWidth);
735 KnownOne.trunc(BitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000736 return;
Zhou Sheng771dbf72007-03-13 02:23:10 +0000737 }
Reid Spencer3e7594f2007-03-08 01:46:38 +0000738 case Instruction::BitCast: {
739 const Type *SrcTy = I->getOperand(0)->getType();
740 if (SrcTy->isInteger()) {
741 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
742 return;
743 }
744 break;
745 }
746 case Instruction::ZExt: {
747 // Compute the bits in the result that are not present in the input.
748 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Zhou Sheng771dbf72007-03-13 02:23:10 +0000749 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer2f549172007-03-25 04:26:16 +0000750
Zhou Shengaa305ab2007-03-28 02:19:03 +0000751 APInt MaskIn(Mask);
752 MaskIn.trunc(SrcBitWidth);
753 KnownZero.trunc(SrcBitWidth);
754 KnownOne.trunc(SrcBitWidth);
755 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000756 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
757 // The top bits are known to be zero.
Zhou Sheng771dbf72007-03-13 02:23:10 +0000758 KnownZero.zext(BitWidth);
759 KnownOne.zext(BitWidth);
Zhou Shengaa305ab2007-03-28 02:19:03 +0000760 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000761 return;
762 }
763 case Instruction::SExt: {
764 // Compute the bits in the result that are not present in the input.
765 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Zhou Sheng771dbf72007-03-13 02:23:10 +0000766 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer2f549172007-03-25 04:26:16 +0000767
Zhou Shengaa305ab2007-03-28 02:19:03 +0000768 APInt MaskIn(Mask);
769 MaskIn.trunc(SrcBitWidth);
770 KnownZero.trunc(SrcBitWidth);
771 KnownOne.trunc(SrcBitWidth);
772 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000773 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Zhou Sheng771dbf72007-03-13 02:23:10 +0000774 KnownZero.zext(BitWidth);
775 KnownOne.zext(BitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000776
777 // If the sign bit of the input is known set or clear, then we know the
778 // top bits of the result.
Zhou Shengaa305ab2007-03-28 02:19:03 +0000779 if (KnownZero[SrcBitWidth-1]) // Input sign bit known zero
Zhou Sheng34a4b382007-03-28 17:38:21 +0000780 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Zhou Shengaa305ab2007-03-28 02:19:03 +0000781 else if (KnownOne[SrcBitWidth-1]) // Input sign bit known set
Zhou Sheng34a4b382007-03-28 17:38:21 +0000782 KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000783 return;
784 }
785 case Instruction::Shl:
786 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
787 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000788 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer2b812072007-03-25 02:03:12 +0000789 APInt Mask2(Mask.lshr(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?");
Zhou Sheng430f6262007-03-12 05:44:52 +0000792 KnownZero <<= ShiftAmt;
793 KnownOne <<= ShiftAmt;
Reid Spencer2149a9d2007-03-25 19:55:33 +0000794 KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt); // low bits known 0
Reid Spencer3e7594f2007-03-08 01:46:38 +0000795 return;
796 }
797 break;
798 case Instruction::LShr:
799 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
800 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
801 // Compute the new bits that are at the top now.
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000802 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000803
804 // Unsigned shift right.
Reid Spencer2b812072007-03-25 02:03:12 +0000805 APInt Mask2(Mask.shl(ShiftAmt));
806 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000807 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
808 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
809 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
Zhou Shengaa305ab2007-03-28 02:19:03 +0000810 // high bits known zero.
811 KnownZero |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000812 return;
813 }
814 break;
815 case Instruction::AShr:
Zhou Shengaa305ab2007-03-28 02:19:03 +0000816 // (ashr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
Reid Spencer3e7594f2007-03-08 01:46:38 +0000817 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
818 // Compute the new bits that are at the top now.
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000819 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000820
821 // Signed shift right.
Reid Spencer2b812072007-03-25 02:03:12 +0000822 APInt Mask2(Mask.shl(ShiftAmt));
823 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000824 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
825 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
826 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
827
Zhou Shengaa305ab2007-03-28 02:19:03 +0000828 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
829 if (KnownZero[BitWidth-ShiftAmt-1]) // New bits are known zero.
Reid Spencer3e7594f2007-03-08 01:46:38 +0000830 KnownZero |= HighBits;
Zhou Shengaa305ab2007-03-28 02:19:03 +0000831 else if (KnownOne[BitWidth-ShiftAmt-1]) // New bits are known one.
Reid Spencer3e7594f2007-03-08 01:46:38 +0000832 KnownOne |= HighBits;
Reid Spencer3e7594f2007-03-08 01:46:38 +0000833 return;
834 }
835 break;
Chris Lattner41dc0fc2008-03-21 05:19:58 +0000836 case Instruction::Add:
837 // If either the LHS or the RHS are Zero, the result is zero.
838 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
839 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
840 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
841 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
842
843 // Output known-0 bits are known if clear or set in both the low clear bits
844 // common to both LHS & RHS. For example, 8+(X<<3) is known to have the
845 // low 3 bits clear.
846 unsigned KnownZeroOut = std::min(KnownZero.countTrailingOnes(),
847 KnownZero2.countTrailingOnes());
848
849 KnownZero = APInt::getLowBitsSet(BitWidth, KnownZeroOut);
850 KnownOne = APInt(BitWidth, 0);
851 return;
852 case Instruction::Sub: {
853 ConstantInt *CLHS = dyn_cast<ConstantInt>(I->getOperand(0));
854 if (!CLHS) break;
855
856 // We know that the top bits of C-X are clear if X contains less bits
857 // than C (i.e. no wrap-around can happen). For example, 20-X is
858 // positive if we can prove that X is >= 0 and < 16.
859 if (CLHS->getValue().isNegative())
860 break;
861
862 unsigned NLZ = (CLHS->getValue()+1).countLeadingZeros();
863 // NLZ can't be BitWidth with no sign bit
864 APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
865 ComputeMaskedBits(I->getOperand(1), MaskV, KnownZero, KnownOne, Depth+1);
866
867 // If all of the MaskV bits are known to be zero, then we know the output
868 // top bits are zero, because we now know that the output is from [0-C].
869 if ((KnownZero & MaskV) == MaskV) {
870 unsigned NLZ2 = CLHS->getValue().countLeadingZeros();
871 // Top bits known zero.
872 KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2) & Mask;
873 KnownOne = APInt(BitWidth, 0); // No one bits known.
874 } else {
875 KnownZero = KnownOne = APInt(BitWidth, 0); // Otherwise, nothing known.
876 }
877 return;
878 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +0000879 case Instruction::SRem:
880 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
881 APInt RA = Rem->getValue();
882 if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
883 APInt LowBits = RA.isStrictlyPositive() ? ((RA - 1) | RA) : ~RA;
884 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
885 ComputeMaskedBits(I->getOperand(0), Mask2,KnownZero2,KnownOne2,Depth+1);
886
887 // The sign of a remainder is equal to the sign of the first
888 // operand (zero being positive).
889 if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
890 KnownZero2 |= ~LowBits;
891 else if (KnownOne2[BitWidth-1])
892 KnownOne2 |= ~LowBits;
893
894 KnownZero |= KnownZero2 & Mask;
895 KnownOne |= KnownOne2 & Mask;
896
897 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
898 }
899 }
900 break;
901 case Instruction::URem:
902 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
903 APInt RA = Rem->getValue();
904 if (RA.isStrictlyPositive() && RA.isPowerOf2()) {
905 APInt LowBits = (RA - 1) | RA;
906 APInt Mask2 = LowBits & Mask;
907 KnownZero |= ~LowBits & Mask;
908 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne,Depth+1);
909 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
910 }
911 } else {
912 // Since the result is less than or equal to RHS, any leading zero bits
913 // in RHS must also exist in the result.
914 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Chris Lattner41dc0fc2008-03-21 05:19:58 +0000915 ComputeMaskedBits(I->getOperand(1), AllOnes, KnownZero2, KnownOne2,
916 Depth+1);
Nick Lewyckyc1a2a612008-03-06 06:48:30 +0000917
918 uint32_t Leaders = KnownZero2.countLeadingOnes();
919 KnownZero |= APInt::getHighBitsSet(BitWidth, Leaders) & Mask;
920 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
921 }
922 break;
Reid Spencer3e7594f2007-03-08 01:46:38 +0000923 }
924}
925
Reid Spencere7816b52007-03-08 01:52:58 +0000926/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
927/// this predicate to simplify operations downstream. Mask is known to be zero
928/// for bits that V cannot have.
929static bool MaskedValueIsZero(Value *V, const APInt& Mask, unsigned Depth = 0) {
Zhou Shengedd089c2007-03-12 16:54:56 +0000930 APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
Reid Spencere7816b52007-03-08 01:52:58 +0000931 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
932 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
933 return (KnownZero & Mask) == Mask;
934}
935
Chris Lattner255d8912006-02-11 09:31:47 +0000936/// ShrinkDemandedConstant - Check to see if the specified operand of the
937/// specified instruction is a constant integer. If so, check to see if there
938/// are any bits set in the constant that are not demanded. If so, shrink the
939/// constant and return true.
940static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000941 APInt Demanded) {
942 assert(I && "No instruction?");
943 assert(OpNo < I->getNumOperands() && "Operand index too large");
944
945 // If the operand is not a constant integer, nothing to do.
946 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
947 if (!OpC) return false;
948
949 // If there are no bits set that aren't demanded, nothing to do.
950 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
951 if ((~Demanded & OpC->getValue()) == 0)
952 return false;
953
954 // This instruction is producing bits that are not demanded. Shrink the RHS.
955 Demanded &= OpC->getValue();
956 I->setOperand(OpNo, ConstantInt::get(Demanded));
957 return true;
958}
959
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000960// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
961// set of known zero and one bits, compute the maximum and minimum values that
962// could have the specified known zero and known one bits, returning them in
963// min/max.
964static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
Reid Spencer0460fb32007-03-22 20:36:03 +0000965 const APInt& KnownZero,
966 const APInt& KnownOne,
967 APInt& Min, APInt& Max) {
968 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
969 assert(KnownZero.getBitWidth() == BitWidth &&
970 KnownOne.getBitWidth() == BitWidth &&
971 Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
972 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000973 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000974
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000975 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
976 // bit if it is unknown.
977 Min = KnownOne;
978 Max = KnownOne|UnknownBits;
979
Zhou Sheng4acf1552007-03-28 05:15:57 +0000980 if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
Zhou Sheng4a1822a2007-04-02 13:45:30 +0000981 Min.set(BitWidth-1);
982 Max.clear(BitWidth-1);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000983 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000984}
985
986// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
987// a set of known zero and one bits, compute the maximum and minimum values that
988// could have the specified known zero and known one bits, returning them in
989// min/max.
990static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
Chris Lattnera9ff5eb2007-08-05 08:47:58 +0000991 const APInt &KnownZero,
992 const APInt &KnownOne,
993 APInt &Min, APInt &Max) {
994 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth(); BitWidth = BitWidth;
Reid Spencer0460fb32007-03-22 20:36:03 +0000995 assert(KnownZero.getBitWidth() == BitWidth &&
996 KnownOne.getBitWidth() == BitWidth &&
997 Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
998 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000999 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00001000
1001 // The minimum value is when the unknown bits are all zeros.
1002 Min = KnownOne;
1003 // The maximum value is when the unknown bits are all ones.
1004 Max = KnownOne|UnknownBits;
1005}
Chris Lattner255d8912006-02-11 09:31:47 +00001006
Reid Spencer8cb68342007-03-12 17:25:59 +00001007/// SimplifyDemandedBits - This function attempts to replace V with a simpler
1008/// value based on the demanded bits. When this function is called, it is known
1009/// that only the bits set in DemandedMask of the result of V are ever used
1010/// downstream. Consequently, depending on the mask and V, it may be possible
1011/// to replace V with a constant or one of its operands. In such cases, this
1012/// function does the replacement and returns true. In all other cases, it
1013/// returns false after analyzing the expression and setting KnownOne and known
1014/// to be one in the expression. KnownZero contains all the bits that are known
1015/// to be zero in the expression. These are provided to potentially allow the
1016/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
1017/// the expression. KnownOne and KnownZero always follow the invariant that
1018/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
1019/// the bits in KnownOne and KnownZero may only be accurate for those bits set
1020/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
1021/// and KnownOne must all be the same.
1022bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
1023 APInt& KnownZero, APInt& KnownOne,
1024 unsigned Depth) {
1025 assert(V != 0 && "Null pointer of Value???");
1026 assert(Depth <= 6 && "Limit Search Depth");
1027 uint32_t BitWidth = DemandedMask.getBitWidth();
1028 const IntegerType *VTy = cast<IntegerType>(V->getType());
1029 assert(VTy->getBitWidth() == BitWidth &&
1030 KnownZero.getBitWidth() == BitWidth &&
1031 KnownOne.getBitWidth() == BitWidth &&
1032 "Value *V, DemandedMask, KnownZero and KnownOne \
1033 must have same BitWidth");
1034 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
1035 // We know all of the bits for a constant!
1036 KnownOne = CI->getValue() & DemandedMask;
1037 KnownZero = ~KnownOne & DemandedMask;
1038 return false;
1039 }
1040
Zhou Sheng96704452007-03-14 03:21:24 +00001041 KnownZero.clear();
1042 KnownOne.clear();
Reid Spencer8cb68342007-03-12 17:25:59 +00001043 if (!V->hasOneUse()) { // Other users may use these bits.
1044 if (Depth != 0) { // Not at the root.
1045 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
1046 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
1047 return false;
1048 }
1049 // If this is the root being simplified, allow it to have multiple uses,
1050 // just set the DemandedMask to all bits.
1051 DemandedMask = APInt::getAllOnesValue(BitWidth);
1052 } else if (DemandedMask == 0) { // Not demanding any bits from V.
1053 if (V != UndefValue::get(VTy))
1054 return UpdateValueUsesWith(V, UndefValue::get(VTy));
1055 return false;
1056 } else if (Depth == 6) { // Limit search depth.
1057 return false;
1058 }
1059
1060 Instruction *I = dyn_cast<Instruction>(V);
1061 if (!I) return false; // Only analyze instructions.
1062
Reid Spencer8cb68342007-03-12 17:25:59 +00001063 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
1064 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
1065 switch (I->getOpcode()) {
1066 default: break;
1067 case Instruction::And:
1068 // If either the LHS or the RHS are Zero, the result is zero.
1069 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1070 RHSKnownZero, RHSKnownOne, Depth+1))
1071 return true;
1072 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1073 "Bits known to be one AND zero?");
1074
1075 // If something is known zero on the RHS, the bits aren't demanded on the
1076 // LHS.
1077 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
1078 LHSKnownZero, LHSKnownOne, Depth+1))
1079 return true;
1080 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1081 "Bits known to be one AND zero?");
1082
1083 // If all of the demanded bits are known 1 on one side, return the other.
1084 // These bits cannot contribute to the result of the 'and'.
1085 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
1086 (DemandedMask & ~LHSKnownZero))
1087 return UpdateValueUsesWith(I, I->getOperand(0));
1088 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
1089 (DemandedMask & ~RHSKnownZero))
1090 return UpdateValueUsesWith(I, I->getOperand(1));
1091
1092 // If all of the demanded bits in the inputs are known zeros, return zero.
1093 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
1094 return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
1095
1096 // If the RHS is a constant, see if we can simplify it.
1097 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
1098 return UpdateValueUsesWith(I, I);
1099
1100 // Output known-1 bits are only known if set in both the LHS & RHS.
1101 RHSKnownOne &= LHSKnownOne;
1102 // Output known-0 are known to be clear if zero in either the LHS | RHS.
1103 RHSKnownZero |= LHSKnownZero;
1104 break;
1105 case Instruction::Or:
1106 // If either the LHS or the RHS are One, the result is One.
1107 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1108 RHSKnownZero, RHSKnownOne, Depth+1))
1109 return true;
1110 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1111 "Bits known to be one AND zero?");
1112 // If something is known one on the RHS, the bits aren't demanded on the
1113 // LHS.
1114 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
1115 LHSKnownZero, LHSKnownOne, Depth+1))
1116 return true;
1117 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1118 "Bits known to be one AND zero?");
1119
1120 // If all of the demanded bits are known zero on one side, return the other.
1121 // These bits cannot contribute to the result of the 'or'.
1122 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
1123 (DemandedMask & ~LHSKnownOne))
1124 return UpdateValueUsesWith(I, I->getOperand(0));
1125 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
1126 (DemandedMask & ~RHSKnownOne))
1127 return UpdateValueUsesWith(I, I->getOperand(1));
1128
1129 // If all of the potentially set bits on one side are known to be set on
1130 // the other side, just use the 'other' side.
1131 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
1132 (DemandedMask & (~RHSKnownZero)))
1133 return UpdateValueUsesWith(I, I->getOperand(0));
1134 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
1135 (DemandedMask & (~LHSKnownZero)))
1136 return UpdateValueUsesWith(I, I->getOperand(1));
1137
1138 // If the RHS is a constant, see if we can simplify it.
1139 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1140 return UpdateValueUsesWith(I, I);
1141
1142 // Output known-0 bits are only known if clear in both the LHS & RHS.
1143 RHSKnownZero &= LHSKnownZero;
1144 // Output known-1 are known to be set if set in either the LHS | RHS.
1145 RHSKnownOne |= LHSKnownOne;
1146 break;
1147 case Instruction::Xor: {
1148 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1149 RHSKnownZero, RHSKnownOne, Depth+1))
1150 return true;
1151 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1152 "Bits known to be one AND zero?");
1153 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1154 LHSKnownZero, LHSKnownOne, Depth+1))
1155 return true;
1156 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1157 "Bits known to be one AND zero?");
1158
1159 // If all of the demanded bits are known zero on one side, return the other.
1160 // These bits cannot contribute to the result of the 'xor'.
1161 if ((DemandedMask & RHSKnownZero) == DemandedMask)
1162 return UpdateValueUsesWith(I, I->getOperand(0));
1163 if ((DemandedMask & LHSKnownZero) == DemandedMask)
1164 return UpdateValueUsesWith(I, I->getOperand(1));
1165
1166 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1167 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1168 (RHSKnownOne & LHSKnownOne);
1169 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1170 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1171 (RHSKnownOne & LHSKnownZero);
1172
1173 // If all of the demanded bits are known to be zero on one side or the
1174 // other, turn this into an *inclusive* or.
1175 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1176 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1177 Instruction *Or =
1178 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1179 I->getName());
1180 InsertNewInstBefore(Or, *I);
1181 return UpdateValueUsesWith(I, Or);
1182 }
1183
1184 // If all of the demanded bits on one side are known, and all of the set
1185 // bits on that side are also known to be set on the other side, turn this
1186 // into an AND, as we know the bits will be cleared.
1187 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1188 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1189 // all known
1190 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1191 Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
1192 Instruction *And =
1193 BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
1194 InsertNewInstBefore(And, *I);
1195 return UpdateValueUsesWith(I, And);
1196 }
1197 }
1198
1199 // If the RHS is a constant, see if we can simplify it.
1200 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1201 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1202 return UpdateValueUsesWith(I, I);
1203
1204 RHSKnownZero = KnownZeroOut;
1205 RHSKnownOne = KnownOneOut;
1206 break;
1207 }
1208 case Instruction::Select:
1209 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
1210 RHSKnownZero, RHSKnownOne, Depth+1))
1211 return true;
1212 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1213 LHSKnownZero, LHSKnownOne, Depth+1))
1214 return true;
1215 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1216 "Bits known to be one AND zero?");
1217 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1218 "Bits known to be one AND zero?");
1219
1220 // If the operands are constants, see if we can simplify them.
1221 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1222 return UpdateValueUsesWith(I, I);
1223 if (ShrinkDemandedConstant(I, 2, DemandedMask))
1224 return UpdateValueUsesWith(I, I);
1225
1226 // Only known if known in both the LHS and RHS.
1227 RHSKnownOne &= LHSKnownOne;
1228 RHSKnownZero &= LHSKnownZero;
1229 break;
1230 case Instruction::Trunc: {
1231 uint32_t truncBf =
1232 cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
Zhou Sheng01542f32007-03-29 02:26:30 +00001233 DemandedMask.zext(truncBf);
1234 RHSKnownZero.zext(truncBf);
1235 RHSKnownOne.zext(truncBf);
1236 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1237 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer8cb68342007-03-12 17:25:59 +00001238 return true;
1239 DemandedMask.trunc(BitWidth);
1240 RHSKnownZero.trunc(BitWidth);
1241 RHSKnownOne.trunc(BitWidth);
1242 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1243 "Bits known to be one AND zero?");
1244 break;
1245 }
1246 case Instruction::BitCast:
1247 if (!I->getOperand(0)->getType()->isInteger())
1248 return false;
1249
1250 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1251 RHSKnownZero, RHSKnownOne, Depth+1))
1252 return true;
1253 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1254 "Bits known to be one AND zero?");
1255 break;
1256 case Instruction::ZExt: {
1257 // Compute the bits in the result that are not present in the input.
1258 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Reid Spencer2f549172007-03-25 04:26:16 +00001259 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer8cb68342007-03-12 17:25:59 +00001260
Zhou Shengd48653a2007-03-29 04:45:55 +00001261 DemandedMask.trunc(SrcBitWidth);
1262 RHSKnownZero.trunc(SrcBitWidth);
1263 RHSKnownOne.trunc(SrcBitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001264 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1265 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer8cb68342007-03-12 17:25:59 +00001266 return true;
1267 DemandedMask.zext(BitWidth);
1268 RHSKnownZero.zext(BitWidth);
1269 RHSKnownOne.zext(BitWidth);
1270 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1271 "Bits known to be one AND zero?");
1272 // The top bits are known to be zero.
Zhou Sheng01542f32007-03-29 02:26:30 +00001273 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001274 break;
1275 }
1276 case Instruction::SExt: {
1277 // Compute the bits in the result that are not present in the input.
1278 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Reid Spencer2f549172007-03-25 04:26:16 +00001279 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer8cb68342007-03-12 17:25:59 +00001280
Reid Spencer8cb68342007-03-12 17:25:59 +00001281 APInt InputDemandedBits = DemandedMask &
Zhou Sheng01542f32007-03-29 02:26:30 +00001282 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001283
Zhou Sheng01542f32007-03-29 02:26:30 +00001284 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
Reid Spencer8cb68342007-03-12 17:25:59 +00001285 // If any of the sign extended bits are demanded, we know that the sign
1286 // bit is demanded.
1287 if ((NewBits & DemandedMask) != 0)
Zhou Sheng4a1822a2007-04-02 13:45:30 +00001288 InputDemandedBits.set(SrcBitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001289
Zhou Shengd48653a2007-03-29 04:45:55 +00001290 InputDemandedBits.trunc(SrcBitWidth);
1291 RHSKnownZero.trunc(SrcBitWidth);
1292 RHSKnownOne.trunc(SrcBitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001293 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1294 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer8cb68342007-03-12 17:25:59 +00001295 return true;
1296 InputDemandedBits.zext(BitWidth);
1297 RHSKnownZero.zext(BitWidth);
1298 RHSKnownOne.zext(BitWidth);
1299 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1300 "Bits known to be one AND zero?");
1301
1302 // If the sign bit of the input is known set or clear, then we know the
1303 // top bits of the result.
1304
1305 // If the input sign bit is known zero, or if the NewBits are not demanded
1306 // convert this into a zero extension.
Zhou Sheng01542f32007-03-29 02:26:30 +00001307 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits)
Reid Spencer8cb68342007-03-12 17:25:59 +00001308 {
1309 // Convert to ZExt cast
1310 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1311 return UpdateValueUsesWith(I, NewCast);
Zhou Sheng01542f32007-03-29 02:26:30 +00001312 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
Reid Spencer8cb68342007-03-12 17:25:59 +00001313 RHSKnownOne |= NewBits;
Reid Spencer8cb68342007-03-12 17:25:59 +00001314 }
1315 break;
1316 }
1317 case Instruction::Add: {
1318 // Figure out what the input bits are. If the top bits of the and result
1319 // are not demanded, then the add doesn't demand them from its input
1320 // either.
Reid Spencer55702aa2007-03-25 21:11:44 +00001321 uint32_t NLZ = DemandedMask.countLeadingZeros();
Reid Spencer8cb68342007-03-12 17:25:59 +00001322
1323 // If there is a constant on the RHS, there are a variety of xformations
1324 // we can do.
1325 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1326 // If null, this should be simplified elsewhere. Some of the xforms here
1327 // won't work if the RHS is zero.
1328 if (RHS->isZero())
1329 break;
1330
1331 // If the top bit of the output is demanded, demand everything from the
1332 // input. Otherwise, we demand all the input bits except NLZ top bits.
Zhou Sheng01542f32007-03-29 02:26:30 +00001333 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001334
1335 // Find information about known zero/one bits in the input.
1336 if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits,
1337 LHSKnownZero, LHSKnownOne, Depth+1))
1338 return true;
1339
1340 // If the RHS of the add has bits set that can't affect the input, reduce
1341 // the constant.
1342 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1343 return UpdateValueUsesWith(I, I);
1344
1345 // Avoid excess work.
1346 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1347 break;
1348
1349 // Turn it into OR if input bits are zero.
1350 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1351 Instruction *Or =
1352 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1353 I->getName());
1354 InsertNewInstBefore(Or, *I);
1355 return UpdateValueUsesWith(I, Or);
1356 }
1357
1358 // We can say something about the output known-zero and known-one bits,
1359 // depending on potential carries from the input constant and the
1360 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1361 // bits set and the RHS constant is 0x01001, then we know we have a known
1362 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1363
1364 // To compute this, we first compute the potential carry bits. These are
1365 // the bits which may be modified. I'm not aware of a better way to do
1366 // this scan.
Zhou Shengb9cb95f2007-03-31 02:38:39 +00001367 const APInt& RHSVal = RHS->getValue();
1368 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
Reid Spencer8cb68342007-03-12 17:25:59 +00001369
1370 // Now that we know which bits have carries, compute the known-1/0 sets.
1371
1372 // Bits are known one if they are known zero in one operand and one in the
1373 // other, and there is no input carry.
1374 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1375 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1376
1377 // Bits are known zero if they are known zero in both operands and there
1378 // is no input carry.
1379 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1380 } else {
1381 // If the high-bits of this ADD are not demanded, then it does not demand
1382 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001383 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001384 // Right fill the mask of bits for this ADD to demand the most
1385 // significant bit and all those below it.
Zhou Sheng01542f32007-03-29 02:26:30 +00001386 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001387 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1388 LHSKnownZero, LHSKnownOne, Depth+1))
1389 return true;
1390 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1391 LHSKnownZero, LHSKnownOne, Depth+1))
1392 return true;
1393 }
1394 }
1395 break;
1396 }
1397 case Instruction::Sub:
1398 // If the high-bits of this SUB are not demanded, then it does not demand
1399 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001400 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001401 // Right fill the mask of bits for this SUB to demand the most
1402 // significant bit and all those below it.
Zhou Sheng4351c642007-04-02 08:20:41 +00001403 uint32_t NLZ = DemandedMask.countLeadingZeros();
Zhou Sheng01542f32007-03-29 02:26:30 +00001404 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001405 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1406 LHSKnownZero, LHSKnownOne, Depth+1))
1407 return true;
1408 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1409 LHSKnownZero, LHSKnownOne, Depth+1))
1410 return true;
1411 }
1412 break;
1413 case Instruction::Shl:
1414 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001415 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001416 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1417 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001418 RHSKnownZero, RHSKnownOne, Depth+1))
1419 return true;
1420 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1421 "Bits known to be one AND zero?");
1422 RHSKnownZero <<= ShiftAmt;
1423 RHSKnownOne <<= ShiftAmt;
1424 // low bits known zero.
Zhou Shengadc14952007-03-14 09:07:33 +00001425 if (ShiftAmt)
Zhou Shenge9e03f62007-03-28 15:02:20 +00001426 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
Reid Spencer8cb68342007-03-12 17:25:59 +00001427 }
1428 break;
1429 case Instruction::LShr:
1430 // For a logical shift right
1431 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001432 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001433
Reid Spencer8cb68342007-03-12 17:25:59 +00001434 // Unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001435 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1436 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001437 RHSKnownZero, RHSKnownOne, Depth+1))
1438 return true;
1439 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1440 "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001441 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1442 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
Zhou Shengadc14952007-03-14 09:07:33 +00001443 if (ShiftAmt) {
1444 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001445 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Zhou Shengadc14952007-03-14 09:07:33 +00001446 RHSKnownZero |= HighBits; // high bits known zero.
1447 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001448 }
1449 break;
1450 case Instruction::AShr:
1451 // If this is an arithmetic shift right and only the low-bit is set, we can
1452 // always convert this into a logical shr, even if the shift amount is
1453 // variable. The low bit of the shift cannot be an input sign bit unless
1454 // the shift amount is >= the size of the datatype, which is undefined.
1455 if (DemandedMask == 1) {
1456 // Perform the logical shift right.
1457 Value *NewVal = BinaryOperator::createLShr(
1458 I->getOperand(0), I->getOperand(1), I->getName());
1459 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1460 return UpdateValueUsesWith(I, NewVal);
1461 }
Chris Lattner4241e4d2007-07-15 20:54:51 +00001462
1463 // If the sign bit is the only bit demanded by this ashr, then there is no
1464 // need to do it, the shift doesn't change the high bit.
1465 if (DemandedMask.isSignBit())
1466 return UpdateValueUsesWith(I, I->getOperand(0));
Reid Spencer8cb68342007-03-12 17:25:59 +00001467
1468 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00001469 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001470
Reid Spencer8cb68342007-03-12 17:25:59 +00001471 // Signed shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001472 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Lauro Ramos Venanciod0499af2007-06-06 17:08:48 +00001473 // If any of the "high bits" are demanded, we should set the sign bit as
1474 // demanded.
1475 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1476 DemandedMaskIn.set(BitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001477 if (SimplifyDemandedBits(I->getOperand(0),
Zhou Sheng01542f32007-03-29 02:26:30 +00001478 DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001479 RHSKnownZero, RHSKnownOne, Depth+1))
1480 return true;
1481 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1482 "Bits known to be one AND zero?");
1483 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001484 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Reid Spencer8cb68342007-03-12 17:25:59 +00001485 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1486 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1487
1488 // Handle the sign bits.
1489 APInt SignBit(APInt::getSignBit(BitWidth));
1490 // Adjust to where it is now in the mask.
1491 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1492
1493 // If the input sign bit is known to be zero, or if none of the top bits
1494 // are demanded, turn this into an unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001495 if (RHSKnownZero[BitWidth-ShiftAmt-1] ||
Reid Spencer8cb68342007-03-12 17:25:59 +00001496 (HighBits & ~DemandedMask) == HighBits) {
1497 // Perform the logical shift right.
1498 Value *NewVal = BinaryOperator::createLShr(
1499 I->getOperand(0), SA, I->getName());
1500 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1501 return UpdateValueUsesWith(I, NewVal);
1502 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1503 RHSKnownOne |= HighBits;
1504 }
1505 }
1506 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001507 case Instruction::SRem:
1508 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1509 APInt RA = Rem->getValue();
1510 if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
1511 APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) | RA : ~RA;
1512 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1513 if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1514 LHSKnownZero, LHSKnownOne, Depth+1))
1515 return true;
1516
1517 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1518 LHSKnownZero |= ~LowBits;
1519 else if (LHSKnownOne[BitWidth-1])
1520 LHSKnownOne |= ~LowBits;
1521
1522 KnownZero |= LHSKnownZero & DemandedMask;
1523 KnownOne |= LHSKnownOne & DemandedMask;
1524
1525 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1526 }
1527 }
1528 break;
1529 case Instruction::URem:
1530 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1531 APInt RA = Rem->getValue();
1532 if (RA.isPowerOf2()) {
1533 APInt LowBits = (RA - 1) | RA;
1534 APInt Mask2 = LowBits & DemandedMask;
1535 KnownZero |= ~LowBits & DemandedMask;
1536 if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1537 KnownZero, KnownOne, Depth+1))
1538 return true;
1539
1540 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1541 }
1542 } else {
1543 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1544 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1545 if (SimplifyDemandedBits(I->getOperand(1), AllOnes,
1546 KnownZero2, KnownOne2, Depth+1))
1547 return true;
1548
1549 uint32_t Leaders = KnownZero2.countLeadingOnes();
1550 KnownZero |= APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
1551 }
1552 break;
Reid Spencer8cb68342007-03-12 17:25:59 +00001553 }
1554
1555 // If the client is only demanding bits that we know, return the known
1556 // constant.
1557 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1558 return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
1559 return false;
1560}
1561
Chris Lattner867b99f2006-10-05 06:55:50 +00001562
1563/// SimplifyDemandedVectorElts - The specified value producecs a vector with
1564/// 64 or fewer elements. DemandedElts contains the set of elements that are
1565/// actually used by the caller. This method analyzes which elements of the
1566/// operand are undef and returns that information in UndefElts.
1567///
1568/// If the information about demanded elements can be used to simplify the
1569/// operation, the operation is simplified, then the resultant value is
1570/// returned. This returns null if no change was made.
1571Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1572 uint64_t &UndefElts,
1573 unsigned Depth) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001574 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner867b99f2006-10-05 06:55:50 +00001575 assert(VWidth <= 64 && "Vector too wide to analyze!");
1576 uint64_t EltMask = ~0ULL >> (64-VWidth);
1577 assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1578 "Invalid DemandedElts!");
1579
1580 if (isa<UndefValue>(V)) {
1581 // If the entire vector is undefined, just return this info.
1582 UndefElts = EltMask;
1583 return 0;
1584 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1585 UndefElts = EltMask;
1586 return UndefValue::get(V->getType());
1587 }
1588
1589 UndefElts = 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001590 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1591 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner867b99f2006-10-05 06:55:50 +00001592 Constant *Undef = UndefValue::get(EltTy);
1593
1594 std::vector<Constant*> Elts;
1595 for (unsigned i = 0; i != VWidth; ++i)
1596 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1597 Elts.push_back(Undef);
1598 UndefElts |= (1ULL << i);
1599 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1600 Elts.push_back(Undef);
1601 UndefElts |= (1ULL << i);
1602 } else { // Otherwise, defined.
1603 Elts.push_back(CP->getOperand(i));
1604 }
1605
1606 // If we changed the constant, return it.
Reid Spencer9d6565a2007-02-15 02:26:10 +00001607 Constant *NewCP = ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001608 return NewCP != CP ? NewCP : 0;
1609 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001610 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner867b99f2006-10-05 06:55:50 +00001611 // set to undef.
Reid Spencer9d6565a2007-02-15 02:26:10 +00001612 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner867b99f2006-10-05 06:55:50 +00001613 Constant *Zero = Constant::getNullValue(EltTy);
1614 Constant *Undef = UndefValue::get(EltTy);
1615 std::vector<Constant*> Elts;
1616 for (unsigned i = 0; i != VWidth; ++i)
1617 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1618 UndefElts = DemandedElts ^ EltMask;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001619 return ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001620 }
1621
1622 if (!V->hasOneUse()) { // Other users may use these bits.
1623 if (Depth != 0) { // Not at the root.
1624 // TODO: Just compute the UndefElts information recursively.
1625 return false;
1626 }
1627 return false;
1628 } else if (Depth == 10) { // Limit search depth.
1629 return false;
1630 }
1631
1632 Instruction *I = dyn_cast<Instruction>(V);
1633 if (!I) return false; // Only analyze instructions.
1634
1635 bool MadeChange = false;
1636 uint64_t UndefElts2;
1637 Value *TmpV;
1638 switch (I->getOpcode()) {
1639 default: break;
1640
1641 case Instruction::InsertElement: {
1642 // If this is a variable index, we don't know which element it overwrites.
1643 // demand exactly the same input as we produce.
Reid Spencerb83eb642006-10-20 07:07:24 +00001644 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner867b99f2006-10-05 06:55:50 +00001645 if (Idx == 0) {
1646 // Note that we can't propagate undef elt info, because we don't know
1647 // which elt is getting updated.
1648 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1649 UndefElts2, Depth+1);
1650 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1651 break;
1652 }
1653
1654 // If this is inserting an element that isn't demanded, remove this
1655 // insertelement.
Reid Spencerb83eb642006-10-20 07:07:24 +00001656 unsigned IdxNo = Idx->getZExtValue();
Chris Lattner867b99f2006-10-05 06:55:50 +00001657 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1658 return AddSoonDeadInstToWorklist(*I, 0);
1659
1660 // Otherwise, the element inserted overwrites whatever was there, so the
1661 // input demanded set is simpler than the output set.
1662 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1663 DemandedElts & ~(1ULL << IdxNo),
1664 UndefElts, Depth+1);
1665 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1666
1667 // The inserted element is defined.
1668 UndefElts |= 1ULL << IdxNo;
1669 break;
1670 }
Chris Lattner69878332007-04-14 22:29:23 +00001671 case Instruction::BitCast: {
Dan Gohman07a96762007-07-16 14:29:03 +00001672 // Vector->vector casts only.
Chris Lattner69878332007-04-14 22:29:23 +00001673 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1674 if (!VTy) break;
1675 unsigned InVWidth = VTy->getNumElements();
1676 uint64_t InputDemandedElts = 0;
1677 unsigned Ratio;
1678
1679 if (VWidth == InVWidth) {
Dan Gohman07a96762007-07-16 14:29:03 +00001680 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
Chris Lattner69878332007-04-14 22:29:23 +00001681 // elements as are demanded of us.
1682 Ratio = 1;
1683 InputDemandedElts = DemandedElts;
1684 } else if (VWidth > InVWidth) {
1685 // Untested so far.
1686 break;
1687
1688 // If there are more elements in the result than there are in the source,
1689 // then an input element is live if any of the corresponding output
1690 // elements are live.
1691 Ratio = VWidth/InVWidth;
1692 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1693 if (DemandedElts & (1ULL << OutIdx))
1694 InputDemandedElts |= 1ULL << (OutIdx/Ratio);
1695 }
1696 } else {
1697 // Untested so far.
1698 break;
1699
1700 // If there are more elements in the source than there are in the result,
1701 // then an input element is live if the corresponding output element is
1702 // live.
1703 Ratio = InVWidth/VWidth;
1704 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1705 if (DemandedElts & (1ULL << InIdx/Ratio))
1706 InputDemandedElts |= 1ULL << InIdx;
1707 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001708
Chris Lattner69878332007-04-14 22:29:23 +00001709 // div/rem demand all inputs, because they don't want divide by zero.
1710 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1711 UndefElts2, Depth+1);
1712 if (TmpV) {
1713 I->setOperand(0, TmpV);
1714 MadeChange = true;
1715 }
1716
1717 UndefElts = UndefElts2;
1718 if (VWidth > InVWidth) {
1719 assert(0 && "Unimp");
1720 // If there are more elements in the result than there are in the source,
1721 // then an output element is undef if the corresponding input element is
1722 // undef.
1723 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1724 if (UndefElts2 & (1ULL << (OutIdx/Ratio)))
1725 UndefElts |= 1ULL << OutIdx;
1726 } else if (VWidth < InVWidth) {
1727 assert(0 && "Unimp");
1728 // If there are more elements in the source than there are in the result,
1729 // then a result element is undef if all of the corresponding input
1730 // elements are undef.
1731 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1732 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1733 if ((UndefElts2 & (1ULL << InIdx)) == 0) // Not undef?
1734 UndefElts &= ~(1ULL << (InIdx/Ratio)); // Clear undef bit.
1735 }
1736 break;
1737 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001738 case Instruction::And:
1739 case Instruction::Or:
1740 case Instruction::Xor:
1741 case Instruction::Add:
1742 case Instruction::Sub:
1743 case Instruction::Mul:
1744 // div/rem demand all inputs, because they don't want divide by zero.
1745 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1746 UndefElts, Depth+1);
1747 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1748 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1749 UndefElts2, Depth+1);
1750 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1751
1752 // Output elements are undefined if both are undefined. Consider things
1753 // like undef&0. The result is known zero, not undef.
1754 UndefElts &= UndefElts2;
1755 break;
1756
1757 case Instruction::Call: {
1758 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1759 if (!II) break;
1760 switch (II->getIntrinsicID()) {
1761 default: break;
1762
1763 // Binary vector operations that work column-wise. A dest element is a
1764 // function of the corresponding input elements from the two inputs.
1765 case Intrinsic::x86_sse_sub_ss:
1766 case Intrinsic::x86_sse_mul_ss:
1767 case Intrinsic::x86_sse_min_ss:
1768 case Intrinsic::x86_sse_max_ss:
1769 case Intrinsic::x86_sse2_sub_sd:
1770 case Intrinsic::x86_sse2_mul_sd:
1771 case Intrinsic::x86_sse2_min_sd:
1772 case Intrinsic::x86_sse2_max_sd:
1773 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1774 UndefElts, Depth+1);
1775 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1776 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1777 UndefElts2, Depth+1);
1778 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1779
1780 // If only the low elt is demanded and this is a scalarizable intrinsic,
1781 // scalarize it now.
1782 if (DemandedElts == 1) {
1783 switch (II->getIntrinsicID()) {
1784 default: break;
1785 case Intrinsic::x86_sse_sub_ss:
1786 case Intrinsic::x86_sse_mul_ss:
1787 case Intrinsic::x86_sse2_sub_sd:
1788 case Intrinsic::x86_sse2_mul_sd:
1789 // TODO: Lower MIN/MAX/ABS/etc
1790 Value *LHS = II->getOperand(1);
1791 Value *RHS = II->getOperand(2);
1792 // Extract the element as scalars.
1793 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1794 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1795
1796 switch (II->getIntrinsicID()) {
1797 default: assert(0 && "Case stmts out of sync!");
1798 case Intrinsic::x86_sse_sub_ss:
1799 case Intrinsic::x86_sse2_sub_sd:
1800 TmpV = InsertNewInstBefore(BinaryOperator::createSub(LHS, RHS,
1801 II->getName()), *II);
1802 break;
1803 case Intrinsic::x86_sse_mul_ss:
1804 case Intrinsic::x86_sse2_mul_sd:
1805 TmpV = InsertNewInstBefore(BinaryOperator::createMul(LHS, RHS,
1806 II->getName()), *II);
1807 break;
1808 }
1809
1810 Instruction *New =
1811 new InsertElementInst(UndefValue::get(II->getType()), TmpV, 0U,
1812 II->getName());
1813 InsertNewInstBefore(New, *II);
1814 AddSoonDeadInstToWorklist(*II, 0);
1815 return New;
1816 }
1817 }
1818
1819 // Output elements are undefined if both are undefined. Consider things
1820 // like undef&0. The result is known zero, not undef.
1821 UndefElts &= UndefElts2;
1822 break;
1823 }
1824 break;
1825 }
1826 }
1827 return MadeChange ? I : 0;
1828}
1829
Nick Lewycky455e1762007-09-06 02:40:25 +00001830/// @returns true if the specified compare predicate is
Reid Spencere4d87aa2006-12-23 06:05:41 +00001831/// true when both operands are equal...
Nick Lewycky455e1762007-09-06 02:40:25 +00001832/// @brief Determine if the icmp Predicate is true when both operands are equal
1833static bool isTrueWhenEqual(ICmpInst::Predicate pred) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001834 return pred == ICmpInst::ICMP_EQ || pred == ICmpInst::ICMP_UGE ||
1835 pred == ICmpInst::ICMP_SGE || pred == ICmpInst::ICMP_ULE ||
1836 pred == ICmpInst::ICMP_SLE;
1837}
1838
Nick Lewycky455e1762007-09-06 02:40:25 +00001839/// @returns true if the specified compare instruction is
1840/// true when both operands are equal...
1841/// @brief Determine if the ICmpInst returns true when both operands are equal
1842static bool isTrueWhenEqual(ICmpInst &ICI) {
1843 return isTrueWhenEqual(ICI.getPredicate());
1844}
1845
Chris Lattner564a7272003-08-13 19:01:45 +00001846/// AssociativeOpt - Perform an optimization on an associative operator. This
1847/// function is designed to check a chain of associative operators for a
1848/// potential to apply a certain optimization. Since the optimization may be
1849/// applicable if the expression was reassociated, this checks the chain, then
1850/// reassociates the expression as necessary to expose the optimization
1851/// opportunity. This makes use of a special Functor, which must define
1852/// 'shouldApply' and 'apply' methods.
1853///
1854template<typename Functor>
1855Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1856 unsigned Opcode = Root.getOpcode();
1857 Value *LHS = Root.getOperand(0);
1858
1859 // Quick check, see if the immediate LHS matches...
1860 if (F.shouldApply(LHS))
1861 return F.apply(Root);
1862
1863 // Otherwise, if the LHS is not of the same opcode as the root, return.
1864 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +00001865 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +00001866 // Should we apply this transform to the RHS?
1867 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1868
1869 // If not to the RHS, check to see if we should apply to the LHS...
1870 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1871 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1872 ShouldApply = true;
1873 }
1874
1875 // If the functor wants to apply the optimization to the RHS of LHSI,
1876 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1877 if (ShouldApply) {
1878 BasicBlock *BB = Root.getParent();
Misha Brukmanfd939082005-04-21 23:48:37 +00001879
Chris Lattner564a7272003-08-13 19:01:45 +00001880 // Now all of the instructions are in the current basic block, go ahead
1881 // and perform the reassociation.
1882 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1883
1884 // First move the selected RHS to the LHS of the root...
1885 Root.setOperand(0, LHSI->getOperand(1));
1886
1887 // Make what used to be the LHS of the root be the user of the root...
1888 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +00001889 if (&Root == TmpLHSI) {
Chris Lattner15a76c02004-04-05 02:10:19 +00001890 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1891 return 0;
1892 }
Chris Lattner65725312004-04-16 18:08:07 +00001893 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +00001894 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +00001895 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1896 BasicBlock::iterator ARI = &Root; ++ARI;
1897 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
1898 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +00001899
1900 // Now propagate the ExtraOperand down the chain of instructions until we
1901 // get to LHSI.
1902 while (TmpLHSI != LHSI) {
1903 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +00001904 // Move the instruction to immediately before the chain we are
1905 // constructing to avoid breaking dominance properties.
1906 NextLHSI->getParent()->getInstList().remove(NextLHSI);
1907 BB->getInstList().insert(ARI, NextLHSI);
1908 ARI = NextLHSI;
1909
Chris Lattner564a7272003-08-13 19:01:45 +00001910 Value *NextOp = NextLHSI->getOperand(1);
1911 NextLHSI->setOperand(1, ExtraOperand);
1912 TmpLHSI = NextLHSI;
1913 ExtraOperand = NextOp;
1914 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001915
Chris Lattner564a7272003-08-13 19:01:45 +00001916 // Now that the instructions are reassociated, have the functor perform
1917 // the transformation...
1918 return F.apply(Root);
1919 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001920
Chris Lattner564a7272003-08-13 19:01:45 +00001921 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1922 }
1923 return 0;
1924}
1925
1926
1927// AddRHS - Implements: X + X --> X << 1
1928struct AddRHS {
1929 Value *RHS;
1930 AddRHS(Value *rhs) : RHS(rhs) {}
1931 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1932 Instruction *apply(BinaryOperator &Add) const {
Reid Spencercc46cdb2007-02-02 14:08:20 +00001933 return BinaryOperator::createShl(Add.getOperand(0),
Reid Spencer832254e2007-02-02 02:16:23 +00001934 ConstantInt::get(Add.getType(), 1));
Chris Lattner564a7272003-08-13 19:01:45 +00001935 }
1936};
1937
1938// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1939// iff C1&C2 == 0
1940struct AddMaskingAnd {
1941 Constant *C2;
1942 AddMaskingAnd(Constant *c) : C2(c) {}
1943 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001944 ConstantInt *C1;
Misha Brukmanfd939082005-04-21 23:48:37 +00001945 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001946 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +00001947 }
1948 Instruction *apply(BinaryOperator &Add) const {
Chris Lattner48595f12004-06-10 02:07:29 +00001949 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +00001950 }
1951};
1952
Chris Lattner6e7ba452005-01-01 16:22:27 +00001953static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +00001954 InstCombiner *IC) {
Reid Spencer3da59db2006-11-27 01:05:10 +00001955 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Chris Lattner6e7ba452005-01-01 16:22:27 +00001956 if (Constant *SOC = dyn_cast<Constant>(SO))
Reid Spencer3da59db2006-11-27 01:05:10 +00001957 return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
Misha Brukmanfd939082005-04-21 23:48:37 +00001958
Reid Spencer3da59db2006-11-27 01:05:10 +00001959 return IC->InsertNewInstBefore(CastInst::create(
1960 CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001961 }
1962
Chris Lattner2eefe512004-04-09 19:05:30 +00001963 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +00001964 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1965 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +00001966
Chris Lattner2eefe512004-04-09 19:05:30 +00001967 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1968 if (ConstIsRHS)
Chris Lattner6e7ba452005-01-01 16:22:27 +00001969 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1970 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +00001971 }
1972
1973 Value *Op0 = SO, *Op1 = ConstOperand;
1974 if (!ConstIsRHS)
1975 std::swap(Op0, Op1);
1976 Instruction *New;
Chris Lattner6e7ba452005-01-01 16:22:27 +00001977 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1978 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Reid Spencere4d87aa2006-12-23 06:05:41 +00001979 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1980 New = CmpInst::create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
1981 SO->getName()+".cmp");
Chris Lattner326c0f32004-04-10 19:15:56 +00001982 else {
Chris Lattner2eefe512004-04-09 19:05:30 +00001983 assert(0 && "Unknown binary instruction type!");
Chris Lattner326c0f32004-04-10 19:15:56 +00001984 abort();
1985 }
Chris Lattner6e7ba452005-01-01 16:22:27 +00001986 return IC->InsertNewInstBefore(New, I);
1987}
1988
1989// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1990// constant as the other operand, try to fold the binary operator into the
1991// select arguments. This also works for Cast instructions, which obviously do
1992// not have a second operand.
1993static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1994 InstCombiner *IC) {
1995 // Don't modify shared select instructions
1996 if (!SI->hasOneUse()) return 0;
1997 Value *TV = SI->getOperand(1);
1998 Value *FV = SI->getOperand(2);
1999
2000 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +00002001 // Bool selects with constant operands can be folded to logical ops.
Reid Spencer4fe16d62007-01-11 18:21:29 +00002002 if (SI->getType() == Type::Int1Ty) return 0;
Chris Lattner956db272005-04-21 05:43:13 +00002003
Chris Lattner6e7ba452005-01-01 16:22:27 +00002004 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
2005 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
2006
2007 return new SelectInst(SI->getCondition(), SelectTrueVal,
2008 SelectFalseVal);
2009 }
2010 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +00002011}
2012
Chris Lattner4e998b22004-09-29 05:07:12 +00002013
2014/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
2015/// node as operand #0, see if we can fold the instruction into the PHI (which
2016/// is only possible if all operands to the PHI are constants).
2017Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
2018 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00002019 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002020 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner4e998b22004-09-29 05:07:12 +00002021
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002022 // Check to see if all of the operands of the PHI are constants. If there is
2023 // one non-constant value, remember the BB it is. If there is more than one
Chris Lattnerb3036682007-02-24 01:03:45 +00002024 // or if *it* is a PHI, bail out.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002025 BasicBlock *NonConstBB = 0;
2026 for (unsigned i = 0; i != NumPHIValues; ++i)
2027 if (!isa<Constant>(PN->getIncomingValue(i))) {
2028 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +00002029 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002030 NonConstBB = PN->getIncomingBlock(i);
2031
2032 // If the incoming non-constant value is in I's block, we have an infinite
2033 // loop.
2034 if (NonConstBB == I.getParent())
2035 return 0;
2036 }
2037
2038 // If there is exactly one non-constant value, we can insert a copy of the
2039 // operation in that block. However, if this is a critical edge, we would be
2040 // inserting the computation one some other paths (e.g. inside a loop). Only
2041 // do this if the pred block is unconditionally branching into the phi block.
2042 if (NonConstBB) {
2043 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
2044 if (!BI || !BI->isUnconditional()) return 0;
2045 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002046
2047 // Okay, we can do the transformation: create the new PHI node.
Chris Lattner6934a042007-02-11 01:23:03 +00002048 PHINode *NewPN = new PHINode(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +00002049 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner4e998b22004-09-29 05:07:12 +00002050 InsertNewInstBefore(NewPN, *PN);
Chris Lattner6934a042007-02-11 01:23:03 +00002051 NewPN->takeName(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +00002052
2053 // Next, add all of the operands to the PHI.
2054 if (I.getNumOperands() == 2) {
2055 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +00002056 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00002057 Value *InV = 0;
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002058 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002059 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2060 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
2061 else
2062 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002063 } else {
2064 assert(PN->getIncomingBlock(i) == NonConstBB);
2065 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
2066 InV = BinaryOperator::create(BO->getOpcode(),
2067 PN->getIncomingValue(i), C, "phitmp",
2068 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +00002069 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2070 InV = CmpInst::create(CI->getOpcode(),
2071 CI->getPredicate(),
2072 PN->getIncomingValue(i), C, "phitmp",
2073 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002074 else
2075 assert(0 && "Unknown binop!");
2076
Chris Lattnerdbab3862007-03-02 21:28:56 +00002077 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002078 }
2079 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002080 }
Reid Spencer3da59db2006-11-27 01:05:10 +00002081 } else {
2082 CastInst *CI = cast<CastInst>(&I);
2083 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +00002084 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002085 Value *InV;
2086 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00002087 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002088 } else {
2089 assert(PN->getIncomingBlock(i) == NonConstBB);
Reid Spencer3da59db2006-11-27 01:05:10 +00002090 InV = CastInst::create(CI->getOpcode(), PN->getIncomingValue(i),
2091 I.getType(), "phitmp",
2092 NonConstBB->getTerminator());
Chris Lattnerdbab3862007-03-02 21:28:56 +00002093 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002094 }
2095 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002096 }
2097 }
2098 return ReplaceInstUsesWith(I, NewPN);
2099}
2100
Chris Lattner2454a2e2008-01-29 06:52:45 +00002101
2102/// CannotBeNegativeZero - Return true if we can prove that the specified FP
2103/// value is never equal to -0.0.
2104///
2105/// Note that this function will need to be revisited when we support nondefault
2106/// rounding modes!
2107///
2108static bool CannotBeNegativeZero(const Value *V) {
2109 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
2110 return !CFP->getValueAPF().isNegZero();
2111
2112 // (add x, 0.0) is guaranteed to return +0.0, not -0.0.
2113 if (const Instruction *I = dyn_cast<Instruction>(V)) {
2114 if (I->getOpcode() == Instruction::Add &&
2115 isa<ConstantFP>(I->getOperand(1)) &&
2116 cast<ConstantFP>(I->getOperand(1))->isNullValue())
2117 return true;
2118
2119 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
2120 if (II->getIntrinsicID() == Intrinsic::sqrt)
2121 return CannotBeNegativeZero(II->getOperand(1));
2122
2123 if (const CallInst *CI = dyn_cast<CallInst>(I))
2124 if (const Function *F = CI->getCalledFunction()) {
2125 if (F->isDeclaration()) {
2126 switch (F->getNameLen()) {
2127 case 3: // abs(x) != -0.0
2128 if (!strcmp(F->getNameStart(), "abs")) return true;
2129 break;
2130 case 4: // abs[lf](x) != -0.0
2131 if (!strcmp(F->getNameStart(), "absf")) return true;
2132 if (!strcmp(F->getNameStart(), "absl")) return true;
2133 break;
2134 }
2135 }
2136 }
2137 }
2138
2139 return false;
2140}
2141
2142
Chris Lattner7e708292002-06-25 16:13:24 +00002143Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002144 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002145 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002146
Chris Lattner66331a42004-04-10 22:01:55 +00002147 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattnere87597f2004-10-16 18:11:37 +00002148 // X + undef -> undef
2149 if (isa<UndefValue>(RHS))
2150 return ReplaceInstUsesWith(I, RHS);
2151
Chris Lattner66331a42004-04-10 22:01:55 +00002152 // X + 0 --> X
Chris Lattner9919e3d2006-12-02 00:13:08 +00002153 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
Chris Lattner5e678e02005-10-17 17:56:38 +00002154 if (RHSC->isNullValue())
2155 return ReplaceInstUsesWith(I, LHS);
Chris Lattner8532cf62005-10-17 20:18:38 +00002156 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00002157 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
2158 (I.getType())->getValueAPF()))
Chris Lattner8532cf62005-10-17 20:18:38 +00002159 return ReplaceInstUsesWith(I, LHS);
Chris Lattner5e678e02005-10-17 17:56:38 +00002160 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002161
Chris Lattner66331a42004-04-10 22:01:55 +00002162 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002163 // X + (signbit) --> X ^ signbit
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002164 const APInt& Val = CI->getValue();
Zhou Sheng4351c642007-04-02 08:20:41 +00002165 uint32_t BitWidth = Val.getBitWidth();
Reid Spencer2ec619a2007-03-23 21:24:59 +00002166 if (Val == APInt::getSignBit(BitWidth))
Chris Lattner48595f12004-06-10 02:07:29 +00002167 return BinaryOperator::createXor(LHS, RHS);
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002168
2169 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2170 // (X & 254)+1 -> (X&254)|1
Reid Spencer2ec619a2007-03-23 21:24:59 +00002171 if (!isa<VectorType>(I.getType())) {
2172 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2173 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
2174 KnownZero, KnownOne))
2175 return &I;
2176 }
Chris Lattner66331a42004-04-10 22:01:55 +00002177 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002178
2179 if (isa<PHINode>(LHS))
2180 if (Instruction *NV = FoldOpIntoPhi(I))
2181 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +00002182
Chris Lattner4f637d42006-01-06 17:59:59 +00002183 ConstantInt *XorRHS = 0;
2184 Value *XorLHS = 0;
Chris Lattnerc5eff442007-01-30 22:32:46 +00002185 if (isa<ConstantInt>(RHSC) &&
2186 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002187 uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002188 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner5931c542005-09-24 23:43:33 +00002189
Zhou Sheng4351c642007-04-02 08:20:41 +00002190 uint32_t Size = TySizeBits / 2;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002191 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2192 APInt CFF80Val(-C0080Val);
Chris Lattner5931c542005-09-24 23:43:33 +00002193 do {
2194 if (TySizeBits > Size) {
Chris Lattner5931c542005-09-24 23:43:33 +00002195 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2196 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002197 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2198 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner5931c542005-09-24 23:43:33 +00002199 // This is a sign extend if the top bits are known zero.
Zhou Sheng290bec52007-03-29 08:15:12 +00002200 if (!MaskedValueIsZero(XorLHS,
2201 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner5931c542005-09-24 23:43:33 +00002202 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002203 break;
Chris Lattner5931c542005-09-24 23:43:33 +00002204 }
2205 }
2206 Size >>= 1;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002207 C0080Val = APIntOps::lshr(C0080Val, Size);
2208 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2209 } while (Size >= 1);
Chris Lattner5931c542005-09-24 23:43:33 +00002210
Reid Spencer35c38852007-03-28 01:36:16 +00002211 // FIXME: This shouldn't be necessary. When the backends can handle types
2212 // with funny bit widths then this whole cascade of if statements should
2213 // be removed. It is just here to get the size of the "middle" type back
2214 // up to something that the back ends can handle.
2215 const Type *MiddleType = 0;
2216 switch (Size) {
2217 default: break;
2218 case 32: MiddleType = Type::Int32Ty; break;
2219 case 16: MiddleType = Type::Int16Ty; break;
2220 case 8: MiddleType = Type::Int8Ty; break;
2221 }
2222 if (MiddleType) {
Reid Spencerd977d862006-12-12 23:36:14 +00002223 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
Chris Lattner5931c542005-09-24 23:43:33 +00002224 InsertNewInstBefore(NewTrunc, I);
Reid Spencer35c38852007-03-28 01:36:16 +00002225 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner5931c542005-09-24 23:43:33 +00002226 }
2227 }
Chris Lattner66331a42004-04-10 22:01:55 +00002228 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002229
Chris Lattner564a7272003-08-13 19:01:45 +00002230 // X + X --> X << 1
Chris Lattner42a75512007-01-15 02:27:26 +00002231 if (I.getType()->isInteger() && I.getType() != Type::Int1Ty) {
Chris Lattner564a7272003-08-13 19:01:45 +00002232 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +00002233
2234 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2235 if (RHSI->getOpcode() == Instruction::Sub)
2236 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2237 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2238 }
2239 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2240 if (LHSI->getOpcode() == Instruction::Sub)
2241 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2242 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2243 }
Robert Bocchino71698282004-07-27 21:02:21 +00002244 }
Chris Lattnere92d2f42003-08-13 04:18:28 +00002245
Chris Lattner5c4afb92002-05-08 22:46:53 +00002246 // -A + B --> B - A
Chris Lattnerdd12f962008-02-17 21:03:36 +00002247 // -A + -B --> -(A + B)
2248 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattnere10c0b92008-02-18 17:50:16 +00002249 if (LHS->getType()->isIntOrIntVector()) {
2250 if (Value *RHSV = dyn_castNegVal(RHS)) {
2251 Instruction *NewAdd = BinaryOperator::createAdd(LHSV, RHSV, "sum");
2252 InsertNewInstBefore(NewAdd, I);
2253 return BinaryOperator::createNeg(NewAdd);
2254 }
Chris Lattnerdd12f962008-02-17 21:03:36 +00002255 }
2256
2257 return BinaryOperator::createSub(RHS, LHSV);
2258 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002259
2260 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +00002261 if (!isa<Constant>(RHS))
2262 if (Value *V = dyn_castNegVal(RHS))
Chris Lattner48595f12004-06-10 02:07:29 +00002263 return BinaryOperator::createSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002264
Misha Brukmanfd939082005-04-21 23:48:37 +00002265
Chris Lattner50af16a2004-11-13 19:50:12 +00002266 ConstantInt *C2;
2267 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2268 if (X == RHS) // X*C + X --> X * (C+1)
2269 return BinaryOperator::createMul(RHS, AddOne(C2));
2270
2271 // X*C1 + X*C2 --> X * (C1+C2)
2272 ConstantInt *C1;
2273 if (X == dyn_castFoldableMul(RHS, C1))
Reid Spencer7177c3a2007-03-25 05:33:51 +00002274 return BinaryOperator::createMul(X, Add(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002275 }
2276
2277 // X + X*C --> X * (C+1)
Chris Lattner50af16a2004-11-13 19:50:12 +00002278 if (dyn_castFoldableMul(RHS, C2) == LHS)
2279 return BinaryOperator::createMul(LHS, AddOne(C2));
2280
Chris Lattnere617c9e2007-01-05 02:17:46 +00002281 // X + ~X --> -1 since ~X = -X-1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00002282 if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2283 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere617c9e2007-01-05 02:17:46 +00002284
Chris Lattnerad3448c2003-02-18 19:57:07 +00002285
Chris Lattner564a7272003-08-13 19:01:45 +00002286 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002287 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnere617c9e2007-01-05 02:17:46 +00002288 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2289 return R;
Chris Lattnerc8802d22003-03-11 00:12:48 +00002290
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002291 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky0c2c3f62008-02-03 08:19:11 +00002292 if (I.getType()->isIntOrIntVector()) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002293 Value *W, *X, *Y, *Z;
2294 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2295 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2296 if (W != Y) {
2297 if (W == Z) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002298 std::swap(Y, Z);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002299 } else if (Y == X) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002300 std::swap(W, X);
2301 } else if (X == Z) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002302 std::swap(Y, Z);
2303 std::swap(W, X);
2304 }
2305 }
2306
2307 if (W == Y) {
2308 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, Z,
2309 LHS->getName()), I);
2310 return BinaryOperator::createMul(W, NewAdd);
2311 }
2312 }
2313 }
2314
Chris Lattner6b032052003-10-02 15:11:26 +00002315 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002316 Value *X = 0;
Reid Spencer7177c3a2007-03-25 05:33:51 +00002317 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
2318 return BinaryOperator::createSub(SubOne(CRHS), X);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002319
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002320 // (X & FF00) + xx00 -> (X+xx00) & FF00
2321 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002322 Constant *Anded = And(CRHS, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002323 if (Anded == CRHS) {
2324 // See if all bits from the first bit set in the Add RHS up are included
2325 // in the mask. First, get the rightmost bit.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002326 const APInt& AddRHSV = CRHS->getValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002327
2328 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002329 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002330
2331 // See if the and mask includes all of these bits.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002332 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanfd939082005-04-21 23:48:37 +00002333
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002334 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2335 // Okay, the xform is safe. Insert the new add pronto.
2336 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
2337 LHS->getName()), I);
2338 return BinaryOperator::createAnd(NewAdd, C2);
2339 }
2340 }
2341 }
2342
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002343 // Try to fold constant add into select arguments.
2344 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002345 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002346 return R;
Chris Lattner6b032052003-10-02 15:11:26 +00002347 }
2348
Reid Spencer1628cec2006-10-26 06:15:43 +00002349 // add (cast *A to intptrtype) B ->
Chris Lattner42790482007-12-20 01:56:58 +00002350 // cast (GEP (cast *A to sbyte*) B) --> intptrtype
Andrew Lenharth16d79552006-09-19 18:24:51 +00002351 {
Reid Spencer3da59db2006-11-27 01:05:10 +00002352 CastInst *CI = dyn_cast<CastInst>(LHS);
2353 Value *Other = RHS;
Andrew Lenharth16d79552006-09-19 18:24:51 +00002354 if (!CI) {
2355 CI = dyn_cast<CastInst>(RHS);
2356 Other = LHS;
2357 }
Andrew Lenharth45633262006-09-20 15:37:57 +00002358 if (CI && CI->getType()->isSized() &&
Reid Spencerabaa8ca2007-01-08 16:32:00 +00002359 (CI->getType()->getPrimitiveSizeInBits() ==
2360 TD->getIntPtrType()->getPrimitiveSizeInBits())
Andrew Lenharth45633262006-09-20 15:37:57 +00002361 && isa<PointerType>(CI->getOperand(0)->getType())) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00002362 unsigned AS =
2363 cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +00002364 Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2365 PointerType::get(Type::Int8Ty, AS), I);
Andrew Lenharth45633262006-09-20 15:37:57 +00002366 I2 = InsertNewInstBefore(new GetElementPtrInst(I2, Other, "ctg2"), I);
Reid Spencer3da59db2006-11-27 01:05:10 +00002367 return new PtrToIntInst(I2, CI->getType());
Andrew Lenharth16d79552006-09-19 18:24:51 +00002368 }
2369 }
Christopher Lamb30f017a2007-12-18 09:34:41 +00002370
Chris Lattner42790482007-12-20 01:56:58 +00002371 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb30f017a2007-12-18 09:34:41 +00002372 {
2373 SelectInst *SI = dyn_cast<SelectInst>(LHS);
2374 Value *Other = RHS;
2375 if (!SI) {
2376 SI = dyn_cast<SelectInst>(RHS);
2377 Other = LHS;
2378 }
Chris Lattner42790482007-12-20 01:56:58 +00002379 if (SI && SI->hasOneUse()) {
Christopher Lamb30f017a2007-12-18 09:34:41 +00002380 Value *TV = SI->getTrueValue();
2381 Value *FV = SI->getFalseValue();
Chris Lattner42790482007-12-20 01:56:58 +00002382 Value *A, *N;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002383
2384 // Can we fold the add into the argument of the select?
2385 // We check both true and false select arguments for a matching subtract.
Chris Lattner42790482007-12-20 01:56:58 +00002386 if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Value(A))) &&
2387 A == Other) // Fold the add into the true select value.
2388 return new SelectInst(SI->getCondition(), N, A);
2389 if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Value(A))) &&
2390 A == Other) // Fold the add into the false select value.
2391 return new SelectInst(SI->getCondition(), A, N);
Christopher Lamb30f017a2007-12-18 09:34:41 +00002392 }
2393 }
Chris Lattner2454a2e2008-01-29 06:52:45 +00002394
2395 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2396 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2397 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2398 return ReplaceInstUsesWith(I, LHS);
Andrew Lenharth16d79552006-09-19 18:24:51 +00002399
Chris Lattner7e708292002-06-25 16:13:24 +00002400 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002401}
2402
Chris Lattner1ba5bcd2003-07-22 21:46:59 +00002403// isSignBit - Return true if the value represented by the constant only has the
2404// highest order bit set.
2405static bool isSignBit(ConstantInt *CI) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002406 uint32_t NumBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencer5a1e3e12007-03-19 20:58:18 +00002407 return CI->getValue() == APInt::getSignBit(NumBits);
Chris Lattner1ba5bcd2003-07-22 21:46:59 +00002408}
2409
Chris Lattner7e708292002-06-25 16:13:24 +00002410Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00002411 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002412
Chris Lattner233f7dc2002-08-12 21:17:25 +00002413 if (Op0 == Op1) // sub X, X -> 0
2414 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002415
Chris Lattner233f7dc2002-08-12 21:17:25 +00002416 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattner8d969642003-03-10 23:06:50 +00002417 if (Value *V = dyn_castNegVal(Op1))
Chris Lattner48595f12004-06-10 02:07:29 +00002418 return BinaryOperator::createAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002419
Chris Lattnere87597f2004-10-16 18:11:37 +00002420 if (isa<UndefValue>(Op0))
2421 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2422 if (isa<UndefValue>(Op1))
2423 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2424
Chris Lattnerd65460f2003-11-05 01:06:05 +00002425 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2426 // Replace (-1 - A) with (~A)...
Chris Lattnera2881962003-02-18 19:28:33 +00002427 if (C->isAllOnesValue())
2428 return BinaryOperator::createNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +00002429
Chris Lattnerd65460f2003-11-05 01:06:05 +00002430 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002431 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002432 if (match(Op1, m_Not(m_Value(X))))
Reid Spencer7177c3a2007-03-25 05:33:51 +00002433 return BinaryOperator::createAdd(X, AddOne(C));
2434
Chris Lattner76b7a062007-01-15 07:02:54 +00002435 // -(X >>u 31) -> (X >>s 31)
2436 // -(X >>s 31) -> (X >>u 31)
Zhou Sheng302748d2007-03-30 17:20:39 +00002437 if (C->isZero()) {
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002438 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002439 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002440 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00002441 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002442 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerb83eb642006-10-20 07:07:24 +00002443 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002444 // Ok, the transformation is safe. Insert AShr.
Reid Spencer832254e2007-02-02 02:16:23 +00002445 return BinaryOperator::create(Instruction::AShr,
2446 SI->getOperand(0), CU, SI->getName());
Chris Lattner9c290672004-03-12 23:53:13 +00002447 }
2448 }
Reid Spencer3822ff52006-11-08 06:47:33 +00002449 }
2450 else if (SI->getOpcode() == Instruction::AShr) {
2451 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2452 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002453 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencer3822ff52006-11-08 06:47:33 +00002454 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00002455 // Ok, the transformation is safe. Insert LShr.
Reid Spencercc46cdb2007-02-02 14:08:20 +00002456 return BinaryOperator::createLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00002457 SI->getOperand(0), CU, SI->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00002458 }
2459 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002460 }
2461 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00002462 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002463
2464 // Try to fold constant sub into select arguments.
2465 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002466 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002467 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002468
2469 if (isa<PHINode>(Op0))
2470 if (Instruction *NV = FoldOpIntoPhi(I))
2471 return NV;
Chris Lattnerd65460f2003-11-05 01:06:05 +00002472 }
2473
Chris Lattner43d84d62005-04-07 16:15:25 +00002474 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2475 if (Op1I->getOpcode() == Instruction::Add &&
Chris Lattner9919e3d2006-12-02 00:13:08 +00002476 !Op0->getType()->isFPOrFPVector()) {
Chris Lattner08954a22005-04-07 16:28:01 +00002477 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Chris Lattner43d84d62005-04-07 16:15:25 +00002478 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002479 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Chris Lattner43d84d62005-04-07 16:15:25 +00002480 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002481 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2482 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2483 // C1-(X+C2) --> (C1-C2)-X
Reid Spencer7177c3a2007-03-25 05:33:51 +00002484 return BinaryOperator::createSub(Subtract(CI1, CI2),
Chris Lattner08954a22005-04-07 16:28:01 +00002485 Op1I->getOperand(0));
2486 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002487 }
2488
Chris Lattnerfd059242003-10-15 16:48:29 +00002489 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002490 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2491 // is not used by anyone else...
2492 //
Chris Lattner0517e722004-02-02 20:09:56 +00002493 if (Op1I->getOpcode() == Instruction::Sub &&
Chris Lattner9919e3d2006-12-02 00:13:08 +00002494 !Op1I->getType()->isFPOrFPVector()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002495 // Swap the two operands of the subexpr...
2496 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2497 Op1I->setOperand(0, IIOp1);
2498 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00002499
Chris Lattnera2881962003-02-18 19:28:33 +00002500 // Create the new top level add instruction...
Chris Lattner48595f12004-06-10 02:07:29 +00002501 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00002502 }
2503
2504 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2505 //
2506 if (Op1I->getOpcode() == Instruction::And &&
2507 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2508 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2509
Chris Lattnerf523d062004-06-09 05:08:07 +00002510 Value *NewNot =
2511 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattner48595f12004-06-10 02:07:29 +00002512 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00002513 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00002514
Reid Spencerac5209e2006-10-16 23:08:08 +00002515 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer1628cec2006-10-26 06:15:43 +00002516 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencerb83eb642006-10-20 07:07:24 +00002517 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Zhou Sheng843f07672007-04-19 05:39:12 +00002518 if (CSI->isZero())
Chris Lattner91ccc152004-10-06 15:08:25 +00002519 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Reid Spencer1628cec2006-10-26 06:15:43 +00002520 return BinaryOperator::createSDiv(Op1I->getOperand(0),
Chris Lattner91ccc152004-10-06 15:08:25 +00002521 ConstantExpr::getNeg(DivRHS));
2522
Chris Lattnerad3448c2003-02-18 19:57:07 +00002523 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002524 ConstantInt *C2 = 0;
Chris Lattner50af16a2004-11-13 19:50:12 +00002525 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002526 Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
Chris Lattner48595f12004-06-10 02:07:29 +00002527 return BinaryOperator::createMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00002528 }
Dan Gohman5d066ff2007-09-17 17:31:57 +00002529
2530 // X - ((X / Y) * Y) --> X % Y
2531 if (Op1I->getOpcode() == Instruction::Mul)
2532 if (Instruction *I = dyn_cast<Instruction>(Op1I->getOperand(0)))
2533 if (Op0 == I->getOperand(0) &&
2534 Op1I->getOperand(1) == I->getOperand(1)) {
2535 if (I->getOpcode() == Instruction::SDiv)
2536 return BinaryOperator::createSRem(Op0, Op1I->getOperand(1));
2537 if (I->getOpcode() == Instruction::UDiv)
2538 return BinaryOperator::createURem(Op0, Op1I->getOperand(1));
2539 }
Chris Lattner40371712002-05-09 01:29:19 +00002540 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002541 }
Chris Lattnera2881962003-02-18 19:28:33 +00002542
Chris Lattner9919e3d2006-12-02 00:13:08 +00002543 if (!Op0->getType()->isFPOrFPVector())
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002544 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner7edc8c22005-04-07 17:14:51 +00002545 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00002546 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2547 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2548 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2549 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner7edc8c22005-04-07 17:14:51 +00002550 } else if (Op0I->getOpcode() == Instruction::Sub) {
2551 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
2552 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00002553 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002554 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002555
Chris Lattner50af16a2004-11-13 19:50:12 +00002556 ConstantInt *C1;
2557 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002558 if (X == Op1) // X*C - X --> X * (C-1)
2559 return BinaryOperator::createMul(Op1, SubOne(C1));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002560
Chris Lattner50af16a2004-11-13 19:50:12 +00002561 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2562 if (X == dyn_castFoldableMul(Op1, C2))
Zhou Sheng58d13af2008-02-22 10:00:35 +00002563 return BinaryOperator::createMul(X, Subtract(C1, C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002564 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002565 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002566}
2567
Chris Lattnera0141b92007-07-15 20:42:37 +00002568/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2569/// comparison only checks the sign bit. If it only checks the sign bit, set
2570/// TrueIfSigned if the result of the comparison is true when the input value is
2571/// signed.
2572static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2573 bool &TrueIfSigned) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002574 switch (pred) {
Chris Lattnera0141b92007-07-15 20:42:37 +00002575 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2576 TrueIfSigned = true;
2577 return RHS->isZero();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002578 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2579 TrueIfSigned = true;
2580 return RHS->isAllOnesValue();
Chris Lattnera0141b92007-07-15 20:42:37 +00002581 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2582 TrueIfSigned = false;
2583 return RHS->isAllOnesValue();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002584 case ICmpInst::ICMP_UGT:
2585 // True if LHS u> RHS and RHS == high-bit-mask - 1
2586 TrueIfSigned = true;
2587 return RHS->getValue() ==
2588 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2589 case ICmpInst::ICMP_UGE:
2590 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2591 TrueIfSigned = true;
2592 return RHS->getValue() ==
2593 APInt::getSignBit(RHS->getType()->getPrimitiveSizeInBits());
Chris Lattnera0141b92007-07-15 20:42:37 +00002594 default:
2595 return false;
Chris Lattner4cb170c2004-02-23 06:38:22 +00002596 }
Chris Lattner4cb170c2004-02-23 06:38:22 +00002597}
2598
Chris Lattner7e708292002-06-25 16:13:24 +00002599Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002600 bool Changed = SimplifyCommutative(I);
Chris Lattnera2881962003-02-18 19:28:33 +00002601 Value *Op0 = I.getOperand(0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002602
Chris Lattnere87597f2004-10-16 18:11:37 +00002603 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2604 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2605
Chris Lattner233f7dc2002-08-12 21:17:25 +00002606 // Simplify mul instructions with a constant RHS...
Chris Lattnera2881962003-02-18 19:28:33 +00002607 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2608 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00002609
2610 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer832254e2007-02-02 02:16:23 +00002611 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnere92d2f42003-08-13 04:18:28 +00002612 if (SI->getOpcode() == Instruction::Shl)
2613 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattner48595f12004-06-10 02:07:29 +00002614 return BinaryOperator::createMul(SI->getOperand(0),
2615 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00002616
Zhou Sheng843f07672007-04-19 05:39:12 +00002617 if (CI->isZero())
Chris Lattner515c97c2003-09-11 22:24:54 +00002618 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2619 if (CI->equalsInt(1)) // X * 1 == X
2620 return ReplaceInstUsesWith(I, Op0);
2621 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner0af1fab2003-06-25 17:09:20 +00002622 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00002623
Zhou Sheng97b52c22007-03-29 01:57:21 +00002624 const APInt& Val = cast<ConstantInt>(CI)->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002625 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Reid Spencercc46cdb2007-02-02 14:08:20 +00002626 return BinaryOperator::createShl(Op0,
Reid Spencerbca0e382007-03-23 20:05:17 +00002627 ConstantInt::get(Op0->getType(), Val.logBase2()));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00002628 }
Robert Bocchino71698282004-07-27 21:02:21 +00002629 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattnera2881962003-02-18 19:28:33 +00002630 if (Op1F->isNullValue())
2631 return ReplaceInstUsesWith(I, Op1);
Chris Lattner6c1ce212002-04-29 22:24:47 +00002632
Chris Lattnera2881962003-02-18 19:28:33 +00002633 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2634 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00002635 // We need a better interface for long double here.
2636 if (Op1->getType() == Type::FloatTy || Op1->getType() == Type::DoubleTy)
2637 if (Op1F->isExactlyValue(1.0))
2638 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
Chris Lattnera2881962003-02-18 19:28:33 +00002639 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002640
2641 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2642 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2643 isa<ConstantInt>(Op0I->getOperand(1))) {
2644 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2645 Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
2646 Op1, "tmp");
2647 InsertNewInstBefore(Add, I);
2648 Value *C1C2 = ConstantExpr::getMul(Op1,
2649 cast<Constant>(Op0I->getOperand(1)));
2650 return BinaryOperator::createAdd(Add, C1C2);
2651
2652 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002653
2654 // Try to fold constant mul into select arguments.
2655 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002656 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002657 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002658
2659 if (isa<PHINode>(Op0))
2660 if (Instruction *NV = FoldOpIntoPhi(I))
2661 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002662 }
2663
Chris Lattnera4f445b2003-03-10 23:23:04 +00002664 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2665 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattner48595f12004-06-10 02:07:29 +00002666 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00002667
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002668 // If one of the operands of the multiply is a cast from a boolean value, then
2669 // we know the bool is either zero or one, so this is a 'masking' multiply.
2670 // See if we can simplify things based on how the boolean was originally
2671 // formed.
2672 CastInst *BoolCast = 0;
Reid Spencerc55b2432006-12-13 18:21:21 +00002673 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(0)))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002674 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002675 BoolCast = CI;
2676 if (!BoolCast)
Reid Spencerc55b2432006-12-13 18:21:21 +00002677 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002678 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002679 BoolCast = CI;
2680 if (BoolCast) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002681 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002682 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2683 const Type *SCOpTy = SCIOp0->getType();
Chris Lattnera0141b92007-07-15 20:42:37 +00002684 bool TIS = false;
2685
Reid Spencere4d87aa2006-12-23 06:05:41 +00002686 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattner4cb170c2004-02-23 06:38:22 +00002687 // multiply into a shift/and combination.
2688 if (isa<ConstantInt>(SCIOp1) &&
Chris Lattnera0141b92007-07-15 20:42:37 +00002689 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2690 TIS) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002691 // Shift the X value right to turn it into "all signbits".
Reid Spencer832254e2007-02-02 02:16:23 +00002692 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
Chris Lattner484d3cf2005-04-24 06:59:08 +00002693 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattner4cb170c2004-02-23 06:38:22 +00002694 Value *V =
Reid Spencer832254e2007-02-02 02:16:23 +00002695 InsertNewInstBefore(
2696 BinaryOperator::create(Instruction::AShr, SCIOp0, Amt,
Chris Lattner4cb170c2004-02-23 06:38:22 +00002697 BoolCast->getOperand(0)->getName()+
2698 ".mask"), I);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002699
2700 // If the multiply type is not the same as the source type, sign extend
2701 // or truncate to the multiply type.
Reid Spencer17212df2006-12-12 09:18:51 +00002702 if (I.getType() != V->getType()) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002703 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2704 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +00002705 Instruction::CastOps opcode =
2706 (SrcBits == DstBits ? Instruction::BitCast :
2707 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2708 V = InsertCastBefore(opcode, V, I.getType(), I);
2709 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002710
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002711 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattner48595f12004-06-10 02:07:29 +00002712 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002713 }
2714 }
2715 }
2716
Chris Lattner7e708292002-06-25 16:13:24 +00002717 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002718}
2719
Reid Spencer1628cec2006-10-26 06:15:43 +00002720/// This function implements the transforms on div instructions that work
2721/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2722/// used by the visitors to those instructions.
2723/// @brief Transforms common to all three div instructions
Reid Spencer3da59db2006-11-27 01:05:10 +00002724Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002725 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00002726
Chris Lattner50b2ca42008-02-19 06:12:18 +00002727 // undef / X -> 0 for integer.
2728 // undef / X -> undef for FP (the undef could be a snan).
2729 if (isa<UndefValue>(Op0)) {
2730 if (Op0->getType()->isFPOrFPVector())
2731 return ReplaceInstUsesWith(I, Op0);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002732 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00002733 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002734
2735 // X / undef -> undef
Chris Lattner857e8cd2004-12-12 21:48:58 +00002736 if (isa<UndefValue>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00002737 return ReplaceInstUsesWith(I, Op1);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002738
Chris Lattner25feae52008-01-28 00:58:18 +00002739 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2740 // This does not apply for fdiv.
Chris Lattner8e49e082006-09-09 20:26:32 +00002741 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
Chris Lattner25feae52008-01-28 00:58:18 +00002742 // [su]div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in
2743 // the same basic block, then we replace the select with Y, and the
2744 // condition of the select with false (if the cond value is in the same BB).
2745 // If the select has uses other than the div, this allows them to be
2746 // simplified also. Note that div X, Y is just as good as div X, 0 (undef)
2747 if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(1)))
Chris Lattner8e49e082006-09-09 20:26:32 +00002748 if (ST->isNullValue()) {
2749 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2750 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002751 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Chris Lattner8e49e082006-09-09 20:26:32 +00002752 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2753 I.setOperand(1, SI->getOperand(2));
2754 else
2755 UpdateValueUsesWith(SI, SI->getOperand(2));
2756 return &I;
2757 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002758
Chris Lattner25feae52008-01-28 00:58:18 +00002759 // Likewise for: [su]div X, (Cond ? Y : 0) -> div X, Y
2760 if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(2)))
Chris Lattner8e49e082006-09-09 20:26:32 +00002761 if (ST->isNullValue()) {
2762 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2763 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002764 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Chris Lattner8e49e082006-09-09 20:26:32 +00002765 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2766 I.setOperand(1, SI->getOperand(1));
2767 else
2768 UpdateValueUsesWith(SI, SI->getOperand(1));
2769 return &I;
2770 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002771 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002772
Reid Spencer1628cec2006-10-26 06:15:43 +00002773 return 0;
2774}
Misha Brukmanfd939082005-04-21 23:48:37 +00002775
Reid Spencer1628cec2006-10-26 06:15:43 +00002776/// This function implements the transforms common to both integer division
2777/// instructions (udiv and sdiv). It is called by the visitors to those integer
2778/// division instructions.
2779/// @brief Common integer divide transforms
Reid Spencer3da59db2006-11-27 01:05:10 +00002780Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002781 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2782
2783 if (Instruction *Common = commonDivTransforms(I))
2784 return Common;
2785
2786 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2787 // div X, 1 == X
2788 if (RHS->equalsInt(1))
2789 return ReplaceInstUsesWith(I, Op0);
2790
2791 // (X / C1) / C2 -> X / (C1*C2)
2792 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2793 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2794 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00002795 if (MultiplyOverflows(RHS, LHSRHS, I.getOpcode()==Instruction::SDiv))
2796 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2797 else
2798 return BinaryOperator::create(I.getOpcode(), LHS->getOperand(0),
2799 Multiply(RHS, LHSRHS));
Chris Lattnerbf70b832005-04-08 04:03:26 +00002800 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002801
Reid Spencerbca0e382007-03-23 20:05:17 +00002802 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer1628cec2006-10-26 06:15:43 +00002803 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2804 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2805 return R;
2806 if (isa<PHINode>(Op0))
2807 if (Instruction *NV = FoldOpIntoPhi(I))
2808 return NV;
2809 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002810 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002811
Chris Lattnera2881962003-02-18 19:28:33 +00002812 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00002813 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00002814 if (LHS->equalsInt(0))
2815 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2816
Reid Spencer1628cec2006-10-26 06:15:43 +00002817 return 0;
2818}
2819
2820Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2821 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2822
2823 // Handle the integer div common cases
2824 if (Instruction *Common = commonIDivTransforms(I))
2825 return Common;
2826
2827 // X udiv C^2 -> X >> C
2828 // Check to see if this is an unsigned division with an exact power of 2,
2829 // if so, convert to a right shift.
2830 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Reid Spencer6eb0d992007-03-26 23:58:26 +00002831 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Reid Spencerbca0e382007-03-23 20:05:17 +00002832 return BinaryOperator::createLShr(Op0,
Zhou Sheng0fc50952007-03-25 05:01:29 +00002833 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Reid Spencer1628cec2006-10-26 06:15:43 +00002834 }
2835
2836 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer832254e2007-02-02 02:16:23 +00002837 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002838 if (RHSI->getOpcode() == Instruction::Shl &&
2839 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002840 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002841 if (C1.isPowerOf2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002842 Value *N = RHSI->getOperand(1);
Reid Spencer3da59db2006-11-27 01:05:10 +00002843 const Type *NTy = N->getType();
Reid Spencer2ec619a2007-03-23 21:24:59 +00002844 if (uint32_t C2 = C1.logBase2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002845 Constant *C2V = ConstantInt::get(NTy, C2);
2846 N = InsertNewInstBefore(BinaryOperator::createAdd(N, C2V, "tmp"), I);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002847 }
Reid Spencercc46cdb2007-02-02 14:08:20 +00002848 return BinaryOperator::createLShr(Op0, N);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002849 }
2850 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00002851 }
2852
Reid Spencer1628cec2006-10-26 06:15:43 +00002853 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2854 // where C1&C2 are powers of two.
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002855 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00002856 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002857 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002858 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002859 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002860 // Compute the shift amounts
Reid Spencerbca0e382007-03-23 20:05:17 +00002861 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002862 // Construct the "on true" case of the select
2863 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
2864 Instruction *TSI = BinaryOperator::createLShr(
2865 Op0, TC, SI->getName()+".t");
2866 TSI = InsertNewInstBefore(TSI, I);
2867
2868 // Construct the "on false" case of the select
2869 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
2870 Instruction *FSI = BinaryOperator::createLShr(
2871 Op0, FC, SI->getName()+".f");
2872 FSI = InsertNewInstBefore(FSI, I);
Reid Spencer1628cec2006-10-26 06:15:43 +00002873
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002874 // construct the select instruction and return it.
2875 return new SelectInst(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00002876 }
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002877 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002878 return 0;
2879}
2880
Reid Spencer1628cec2006-10-26 06:15:43 +00002881Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2882 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2883
2884 // Handle the integer div common cases
2885 if (Instruction *Common = commonIDivTransforms(I))
2886 return Common;
2887
2888 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2889 // sdiv X, -1 == -X
2890 if (RHS->isAllOnesValue())
2891 return BinaryOperator::createNeg(Op0);
2892
2893 // -X/C -> X/-C
2894 if (Value *LHSNeg = dyn_castNegVal(Op0))
2895 return BinaryOperator::createSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2896 }
2897
2898 // If the sign bits of both operands are zero (i.e. we can prove they are
2899 // unsigned inputs), turn this into a udiv.
Chris Lattner42a75512007-01-15 02:27:26 +00002900 if (I.getType()->isInteger()) {
Reid Spencerbca0e382007-03-23 20:05:17 +00002901 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Reid Spencer1628cec2006-10-26 06:15:43 +00002902 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Dan Gohmancff55092007-11-05 23:16:33 +00002903 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
Reid Spencer1628cec2006-10-26 06:15:43 +00002904 return BinaryOperator::createUDiv(Op0, Op1, I.getName());
2905 }
2906 }
2907
2908 return 0;
2909}
2910
2911Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2912 return commonDivTransforms(I);
2913}
Chris Lattner3f5b8772002-05-06 16:14:14 +00002914
Reid Spencer0a783f72006-11-02 01:53:59 +00002915/// This function implements the transforms on rem instructions that work
2916/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
2917/// is used by the visitors to those instructions.
2918/// @brief Transforms common to all three rem instructions
2919Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002920 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer0a783f72006-11-02 01:53:59 +00002921
Chris Lattner50b2ca42008-02-19 06:12:18 +00002922 // 0 % X == 0 for integer, we don't need to preserve faults!
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002923 if (Constant *LHS = dyn_cast<Constant>(Op0))
2924 if (LHS->isNullValue())
2925 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2926
Chris Lattner50b2ca42008-02-19 06:12:18 +00002927 if (isa<UndefValue>(Op0)) { // undef % X -> 0
2928 if (I.getType()->isFPOrFPVector())
2929 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002930 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00002931 }
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002932 if (isa<UndefValue>(Op1))
2933 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer0a783f72006-11-02 01:53:59 +00002934
2935 // Handle cases involving: rem X, (select Cond, Y, Z)
2936 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2937 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
2938 // the same basic block, then we replace the select with Y, and the
2939 // condition of the select with false (if the cond value is in the same
2940 // BB). If the select has uses other than the div, this allows them to be
2941 // simplified also.
2942 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2943 if (ST->isNullValue()) {
2944 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2945 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002946 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Reid Spencer0a783f72006-11-02 01:53:59 +00002947 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2948 I.setOperand(1, SI->getOperand(2));
2949 else
2950 UpdateValueUsesWith(SI, SI->getOperand(2));
Chris Lattner5b73c082004-07-06 07:01:22 +00002951 return &I;
2952 }
Reid Spencer0a783f72006-11-02 01:53:59 +00002953 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2954 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2955 if (ST->isNullValue()) {
2956 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2957 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002958 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Reid Spencer0a783f72006-11-02 01:53:59 +00002959 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2960 I.setOperand(1, SI->getOperand(1));
2961 else
2962 UpdateValueUsesWith(SI, SI->getOperand(1));
2963 return &I;
2964 }
Chris Lattner11a49f22005-11-05 07:28:37 +00002965 }
Chris Lattner5b73c082004-07-06 07:01:22 +00002966
Reid Spencer0a783f72006-11-02 01:53:59 +00002967 return 0;
2968}
2969
2970/// This function implements the transforms common to both integer remainder
2971/// instructions (urem and srem). It is called by the visitors to those integer
2972/// remainder instructions.
2973/// @brief Common integer remainder transforms
2974Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2975 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2976
2977 if (Instruction *common = commonRemTransforms(I))
2978 return common;
2979
Chris Lattner857e8cd2004-12-12 21:48:58 +00002980 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002981 // X % 0 == undef, we don't need to preserve faults!
2982 if (RHS->equalsInt(0))
2983 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2984
Chris Lattnera2881962003-02-18 19:28:33 +00002985 if (RHS->equalsInt(1)) // X % 1 == 0
2986 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2987
Chris Lattner97943922006-02-28 05:49:21 +00002988 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2989 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2990 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2991 return R;
2992 } else if (isa<PHINode>(Op0I)) {
2993 if (Instruction *NV = FoldOpIntoPhi(I))
2994 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00002995 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00002996
2997 // See if we can fold away this rem instruction.
2998 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
2999 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3000 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3001 KnownZero, KnownOne))
3002 return &I;
Chris Lattner97943922006-02-28 05:49:21 +00003003 }
Chris Lattnera2881962003-02-18 19:28:33 +00003004 }
3005
Reid Spencer0a783f72006-11-02 01:53:59 +00003006 return 0;
3007}
3008
3009Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3010 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3011
3012 if (Instruction *common = commonIRemTransforms(I))
3013 return common;
3014
3015 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3016 // X urem C^2 -> X and C
3017 // Check to see if this is an unsigned remainder with an exact power of 2,
3018 // if so, convert to a bitwise and.
3019 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencerbca0e382007-03-23 20:05:17 +00003020 if (C->getValue().isPowerOf2())
Reid Spencer0a783f72006-11-02 01:53:59 +00003021 return BinaryOperator::createAnd(Op0, SubOne(C));
3022 }
3023
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003024 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003025 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3026 if (RHSI->getOpcode() == Instruction::Shl &&
3027 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng0fc50952007-03-25 05:01:29 +00003028 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003029 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
3030 Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
3031 "tmp"), I);
3032 return BinaryOperator::createAnd(Op0, Add);
3033 }
3034 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003035 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003036
Reid Spencer0a783f72006-11-02 01:53:59 +00003037 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3038 // where C1&C2 are powers of two.
3039 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3040 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3041 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3042 // STO == 0 and SFO == 0 handled above.
Reid Spencerbca0e382007-03-23 20:05:17 +00003043 if ((STO->getValue().isPowerOf2()) &&
3044 (SFO->getValue().isPowerOf2())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003045 Value *TrueAnd = InsertNewInstBefore(
3046 BinaryOperator::createAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
3047 Value *FalseAnd = InsertNewInstBefore(
3048 BinaryOperator::createAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
3049 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
3050 }
3051 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003052 }
3053
Chris Lattner3f5b8772002-05-06 16:14:14 +00003054 return 0;
3055}
3056
Reid Spencer0a783f72006-11-02 01:53:59 +00003057Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3058 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3059
Dan Gohmancff55092007-11-05 23:16:33 +00003060 // Handle the integer rem common cases
Reid Spencer0a783f72006-11-02 01:53:59 +00003061 if (Instruction *common = commonIRemTransforms(I))
3062 return common;
3063
3064 if (Value *RHSNeg = dyn_castNegVal(Op1))
3065 if (!isa<ConstantInt>(RHSNeg) ||
Zhou Sheng0fc50952007-03-25 05:01:29 +00003066 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive()) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003067 // X % -Y -> X % Y
3068 AddUsesToWorkList(I);
3069 I.setOperand(1, RHSNeg);
3070 return &I;
3071 }
3072
Dan Gohmancff55092007-11-05 23:16:33 +00003073 // If the sign bits of both operands are zero (i.e. we can prove they are
Reid Spencer0a783f72006-11-02 01:53:59 +00003074 // unsigned inputs), turn this into a urem.
Dan Gohmancff55092007-11-05 23:16:33 +00003075 if (I.getType()->isInteger()) {
3076 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3077 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3078 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
3079 return BinaryOperator::createURem(Op0, Op1, I.getName());
3080 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003081 }
3082
3083 return 0;
3084}
3085
3086Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003087 return commonRemTransforms(I);
3088}
3089
Chris Lattner8b170942002-08-09 23:47:40 +00003090// isMaxValueMinusOne - return true if this is Max-1
Reid Spencere4d87aa2006-12-23 06:05:41 +00003091static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
Reid Spencer3a2a9fb2007-03-19 21:10:28 +00003092 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattnera0141b92007-07-15 20:42:37 +00003093 if (!isSigned)
3094 return C->getValue() == APInt::getAllOnesValue(TypeBits) - 1;
3095 return C->getValue() == APInt::getSignedMaxValue(TypeBits)-1;
Chris Lattner8b170942002-08-09 23:47:40 +00003096}
3097
3098// isMinValuePlusOne - return true if this is Min+1
Reid Spencere4d87aa2006-12-23 06:05:41 +00003099static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
Chris Lattnera0141b92007-07-15 20:42:37 +00003100 if (!isSigned)
3101 return C->getValue() == 1; // unsigned
3102
3103 // Calculate 1111111111000000000000
3104 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
3105 return C->getValue() == APInt::getSignedMinValue(TypeBits)+1;
Chris Lattner8b170942002-08-09 23:47:40 +00003106}
3107
Chris Lattner457dd822004-06-09 07:59:58 +00003108// isOneBitSet - Return true if there is exactly one bit set in the specified
3109// constant.
3110static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer5f6a8952007-03-20 00:16:52 +00003111 return CI->getValue().isPowerOf2();
Chris Lattner457dd822004-06-09 07:59:58 +00003112}
3113
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003114// isHighOnes - Return true if the constant is of the form 1+0+.
3115// This is the same as lowones(~X).
3116static bool isHighOnes(const ConstantInt *CI) {
Zhou Sheng2cde46c2007-03-20 12:49:06 +00003117 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003118}
3119
Reid Spencere4d87aa2006-12-23 06:05:41 +00003120/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003121/// are carefully arranged to allow folding of expressions such as:
3122///
3123/// (A < B) | (A > B) --> (A != B)
3124///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003125/// Note that this is only valid if the first and second predicates have the
3126/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003127///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003128/// Three bits are used to represent the condition, as follows:
3129/// 0 A > B
3130/// 1 A == B
3131/// 2 A < B
3132///
3133/// <=> Value Definition
3134/// 000 0 Always false
3135/// 001 1 A > B
3136/// 010 2 A == B
3137/// 011 3 A >= B
3138/// 100 4 A < B
3139/// 101 5 A != B
3140/// 110 6 A <= B
3141/// 111 7 Always true
3142///
3143static unsigned getICmpCode(const ICmpInst *ICI) {
3144 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003145 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00003146 case ICmpInst::ICMP_UGT: return 1; // 001
3147 case ICmpInst::ICMP_SGT: return 1; // 001
3148 case ICmpInst::ICMP_EQ: return 2; // 010
3149 case ICmpInst::ICMP_UGE: return 3; // 011
3150 case ICmpInst::ICMP_SGE: return 3; // 011
3151 case ICmpInst::ICMP_ULT: return 4; // 100
3152 case ICmpInst::ICMP_SLT: return 4; // 100
3153 case ICmpInst::ICMP_NE: return 5; // 101
3154 case ICmpInst::ICMP_ULE: return 6; // 110
3155 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003156 // True -> 7
3157 default:
Reid Spencere4d87aa2006-12-23 06:05:41 +00003158 assert(0 && "Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003159 return 0;
3160 }
3161}
3162
Reid Spencere4d87aa2006-12-23 06:05:41 +00003163/// getICmpValue - This is the complement of getICmpCode, which turns an
3164/// opcode and two operands into either a constant true or false, or a brand
Dan Gohman5d066ff2007-09-17 17:31:57 +00003165/// new ICmp instruction. The sign is passed in to determine which kind
Reid Spencere4d87aa2006-12-23 06:05:41 +00003166/// of predicate to use in new icmp instructions.
3167static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3168 switch (code) {
3169 default: assert(0 && "Illegal ICmp code!");
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003170 case 0: return ConstantInt::getFalse();
Reid Spencere4d87aa2006-12-23 06:05:41 +00003171 case 1:
3172 if (sign)
3173 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3174 else
3175 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3176 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
3177 case 3:
3178 if (sign)
3179 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3180 else
3181 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3182 case 4:
3183 if (sign)
3184 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3185 else
3186 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3187 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
3188 case 6:
3189 if (sign)
3190 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3191 else
3192 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003193 case 7: return ConstantInt::getTrue();
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003194 }
3195}
3196
Reid Spencere4d87aa2006-12-23 06:05:41 +00003197static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3198 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3199 (ICmpInst::isSignedPredicate(p1) &&
3200 (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
3201 (ICmpInst::isSignedPredicate(p2) &&
3202 (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
3203}
3204
3205namespace {
3206// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3207struct FoldICmpLogical {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003208 InstCombiner &IC;
3209 Value *LHS, *RHS;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003210 ICmpInst::Predicate pred;
3211 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3212 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3213 pred(ICI->getPredicate()) {}
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003214 bool shouldApply(Value *V) const {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003215 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3216 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003217 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3218 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003219 return false;
3220 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003221 Instruction *apply(Instruction &Log) const {
3222 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3223 if (ICI->getOperand(0) != LHS) {
3224 assert(ICI->getOperand(1) == LHS);
3225 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003226 }
3227
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003228 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003229 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003230 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003231 unsigned Code;
3232 switch (Log.getOpcode()) {
3233 case Instruction::And: Code = LHSCode & RHSCode; break;
3234 case Instruction::Or: Code = LHSCode | RHSCode; break;
3235 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner021c1902003-09-22 20:33:34 +00003236 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003237 }
3238
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003239 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3240 ICmpInst::isSignedPredicate(ICI->getPredicate());
3241
3242 Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003243 if (Instruction *I = dyn_cast<Instruction>(RV))
3244 return I;
3245 // Otherwise, it's a constant boolean value...
3246 return IC.ReplaceInstUsesWith(Log, RV);
3247 }
3248};
Chris Lattnerd23b5ba2006-11-15 04:53:24 +00003249} // end anonymous namespace
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003250
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003251// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3252// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +00003253// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003254Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003255 ConstantInt *OpRHS,
3256 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003257 BinaryOperator &TheAnd) {
3258 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00003259 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +00003260 if (!Op->isShift())
Reid Spencer7177c3a2007-03-25 05:33:51 +00003261 Together = And(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00003262
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003263 switch (Op->getOpcode()) {
3264 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003265 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003266 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Chris Lattner6934a042007-02-11 01:23:03 +00003267 Instruction *And = BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003268 InsertNewInstBefore(And, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003269 And->takeName(Op);
Chris Lattner48595f12004-06-10 02:07:29 +00003270 return BinaryOperator::createXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003271 }
3272 break;
3273 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003274 if (Together == AndRHS) // (X | C) & C --> C
3275 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003276
Chris Lattner6e7ba452005-01-01 16:22:27 +00003277 if (Op->hasOneUse() && Together != OpRHS) {
3278 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Chris Lattner6934a042007-02-11 01:23:03 +00003279 Instruction *Or = BinaryOperator::createOr(X, Together);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003280 InsertNewInstBefore(Or, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003281 Or->takeName(Op);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003282 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003283 }
3284 break;
3285 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00003286 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003287 // Adding a one to a single bit bit-field should be turned into an XOR
3288 // of the bit. First thing to check is to see if this AND is with a
3289 // single bit constant.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003290 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003291
3292 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00003293 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003294 // Ok, at this point, we know that we are masking the result of the
3295 // ADD down to exactly one bit. If the constant we are adding has
3296 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003297 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00003298
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003299 // Check to see if any bits below the one bit set in AndRHSV are set.
3300 if ((AddRHS & (AndRHSV-1)) == 0) {
3301 // If not, the only thing that can effect the output of the AND is
3302 // the bit specified by AndRHSV. If that bit is set, the effect of
3303 // the XOR is to toggle the bit. If it is clear, then the ADD has
3304 // no effect.
3305 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3306 TheAnd.setOperand(0, X);
3307 return &TheAnd;
3308 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003309 // Pull the XOR out of the AND.
Chris Lattner6934a042007-02-11 01:23:03 +00003310 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003311 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003312 NewAnd->takeName(Op);
Chris Lattner48595f12004-06-10 02:07:29 +00003313 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003314 }
3315 }
3316 }
3317 }
3318 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00003319
3320 case Instruction::Shl: {
3321 // We know that the AND will not produce any of the bits shifted in, so if
3322 // the anded constant includes them, clear them now!
3323 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003324 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003325 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003326 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3327 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00003328
Zhou Sheng290bec52007-03-29 08:15:12 +00003329 if (CI->getValue() == ShlMask) {
3330 // Masking out bits that the shift already masks
Chris Lattner0c967662004-09-24 15:21:34 +00003331 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3332 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00003333 TheAnd.setOperand(1, CI);
3334 return &TheAnd;
3335 }
3336 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00003337 }
Reid Spencer3822ff52006-11-08 06:47:33 +00003338 case Instruction::LShr:
3339 {
Chris Lattner62a355c2003-09-19 19:05:02 +00003340 // We know that the AND will not produce any of the bits shifted in, so if
3341 // the anded constant includes them, clear them now! This only applies to
3342 // unsigned shifts, because a signed shr may bring in set bits!
3343 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003344 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003345 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003346 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3347 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00003348
Zhou Sheng290bec52007-03-29 08:15:12 +00003349 if (CI->getValue() == ShrMask) {
3350 // Masking out bits that the shift already masks.
Reid Spencer3822ff52006-11-08 06:47:33 +00003351 return ReplaceInstUsesWith(TheAnd, Op);
3352 } else if (CI != AndRHS) {
3353 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3354 return &TheAnd;
3355 }
3356 break;
3357 }
3358 case Instruction::AShr:
3359 // Signed shr.
3360 // See if this is shifting in some sign extension, then masking it out
3361 // with an and.
3362 if (Op->hasOneUse()) {
Zhou Sheng290bec52007-03-29 08:15:12 +00003363 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003364 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003365 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3366 Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
Reid Spencer7eb76382006-12-13 17:19:09 +00003367 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +00003368 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +00003369 // Make the argument unsigned.
3370 Value *ShVal = Op->getOperand(0);
Reid Spencer832254e2007-02-02 02:16:23 +00003371 ShVal = InsertNewInstBefore(
Reid Spencercc46cdb2007-02-02 14:08:20 +00003372 BinaryOperator::createLShr(ShVal, OpRHS,
Reid Spencer832254e2007-02-02 02:16:23 +00003373 Op->getName()), TheAnd);
Reid Spencer7eb76382006-12-13 17:19:09 +00003374 return BinaryOperator::createAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00003375 }
Chris Lattner62a355c2003-09-19 19:05:02 +00003376 }
3377 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003378 }
3379 return 0;
3380}
3381
Chris Lattner8b170942002-08-09 23:47:40 +00003382
Chris Lattnera96879a2004-09-29 17:40:11 +00003383/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3384/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +00003385/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3386/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +00003387/// insert new instructions.
3388Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003389 bool isSigned, bool Inside,
3390 Instruction &IB) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003391 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +00003392 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +00003393 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003394
Chris Lattnera96879a2004-09-29 17:40:11 +00003395 if (Inside) {
3396 if (Lo == Hi) // Trivially false.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003397 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +00003398
Reid Spencere4d87aa2006-12-23 06:05:41 +00003399 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003400 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4e40032007-03-21 23:19:50 +00003401 ICmpInst::Predicate pred = (isSigned ?
Reid Spencere4d87aa2006-12-23 06:05:41 +00003402 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3403 return new ICmpInst(pred, V, Hi);
3404 }
3405
3406 // Emit V-Lo <u Hi-Lo
3407 Constant *NegLo = ConstantExpr::getNeg(Lo);
3408 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003409 InsertNewInstBefore(Add, IB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003410 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3411 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003412 }
3413
3414 if (Lo == Hi) // Trivially true.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003415 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +00003416
Reid Spencere4e40032007-03-21 23:19:50 +00003417 // V < Min || V >= Hi -> V > Hi-1
Chris Lattnera96879a2004-09-29 17:40:11 +00003418 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003419 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003420 ICmpInst::Predicate pred = (isSigned ?
3421 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3422 return new ICmpInst(pred, V, Hi);
3423 }
Reid Spencerb83eb642006-10-20 07:07:24 +00003424
Reid Spencere4e40032007-03-21 23:19:50 +00003425 // Emit V-Lo >u Hi-1-Lo
3426 // Note that Hi has already had one subtracted from it, above.
3427 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003428 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003429 InsertNewInstBefore(Add, IB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003430 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3431 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003432}
3433
Chris Lattner7203e152005-09-18 07:22:02 +00003434// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3435// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3436// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3437// not, since all 1s are not contiguous.
Zhou Sheng4351c642007-04-02 08:20:41 +00003438static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003439 const APInt& V = Val->getValue();
Reid Spencerf2442522007-03-24 00:42:08 +00003440 uint32_t BitWidth = Val->getType()->getBitWidth();
3441 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattner7203e152005-09-18 07:22:02 +00003442
3443 // look for the first zero bit after the run of ones
Reid Spencerf2442522007-03-24 00:42:08 +00003444 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattner7203e152005-09-18 07:22:02 +00003445 // look for the first non-zero bit
Reid Spencerf2442522007-03-24 00:42:08 +00003446 ME = V.getActiveBits();
Chris Lattner7203e152005-09-18 07:22:02 +00003447 return true;
3448}
3449
Chris Lattner7203e152005-09-18 07:22:02 +00003450/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3451/// where isSub determines whether the operator is a sub. If we can fold one of
3452/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00003453///
3454/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3455/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3456/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3457///
3458/// return (A +/- B).
3459///
3460Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003461 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +00003462 Instruction &I) {
3463 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3464 if (!LHSI || LHSI->getNumOperands() != 2 ||
3465 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3466
3467 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3468
3469 switch (LHSI->getOpcode()) {
3470 default: return 0;
3471 case Instruction::And:
Reid Spencer7177c3a2007-03-25 05:33:51 +00003472 if (And(N, Mask) == Mask) {
Chris Lattner7203e152005-09-18 07:22:02 +00003473 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Sheng00f436c2007-03-24 15:34:37 +00003474 if ((Mask->getValue().countLeadingZeros() +
3475 Mask->getValue().countPopulation()) ==
3476 Mask->getValue().getBitWidth())
Chris Lattner7203e152005-09-18 07:22:02 +00003477 break;
3478
3479 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3480 // part, we don't need any explicit masks to take them out of A. If that
3481 // is all N is, ignore it.
Zhou Sheng4351c642007-04-02 08:20:41 +00003482 uint32_t MB = 0, ME = 0;
Chris Lattner7203e152005-09-18 07:22:02 +00003483 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerb35ae032007-03-23 18:46:34 +00003484 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Sheng290bec52007-03-29 08:15:12 +00003485 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattner3bedbd92006-02-07 07:27:52 +00003486 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00003487 break;
3488 }
3489 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00003490 return 0;
3491 case Instruction::Or:
3492 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00003493 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Sheng00f436c2007-03-24 15:34:37 +00003494 if ((Mask->getValue().countLeadingZeros() +
3495 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Reid Spencer6eb0d992007-03-26 23:58:26 +00003496 && And(N, Mask)->isZero())
Chris Lattnerc8e77562005-09-18 04:24:45 +00003497 break;
3498 return 0;
3499 }
3500
3501 Instruction *New;
3502 if (isSub)
3503 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
3504 else
3505 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
3506 return InsertNewInstBefore(New, I);
3507}
3508
Chris Lattner7e708292002-06-25 16:13:24 +00003509Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003510 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00003511 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003512
Chris Lattnere87597f2004-10-16 18:11:37 +00003513 if (isa<UndefValue>(Op1)) // X & undef -> 0
3514 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3515
Chris Lattner6e7ba452005-01-01 16:22:27 +00003516 // and X, X = X
3517 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00003518 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003519
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003520 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00003521 // purpose is to compute bits we don't care about.
Reid Spencer9d6565a2007-02-15 02:26:10 +00003522 if (!isa<VectorType>(I.getType())) {
Reid Spencera03d45f2007-03-22 22:19:58 +00003523 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3524 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3525 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
Chris Lattner696ee0a2007-01-18 22:16:33 +00003526 KnownZero, KnownOne))
Reid Spencer6eb0d992007-03-26 23:58:26 +00003527 return &I;
Chris Lattner696ee0a2007-01-18 22:16:33 +00003528 } else {
Reid Spencer9d6565a2007-02-15 02:26:10 +00003529 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
Chris Lattner041a6c92007-06-15 05:26:55 +00003530 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
Chris Lattner696ee0a2007-01-18 22:16:33 +00003531 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner041a6c92007-06-15 05:26:55 +00003532 } else if (isa<ConstantAggregateZero>(Op1)) {
3533 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
Chris Lattner696ee0a2007-01-18 22:16:33 +00003534 }
3535 }
Chris Lattner9ca96412006-02-08 03:25:32 +00003536
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003537 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003538 const APInt& AndRHSMask = AndRHS->getValue();
3539 APInt NotAndRHS(~AndRHSMask);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003540
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003541 // Optimize a variety of ((val OP C1) & C2) combinations...
Reid Spencer832254e2007-02-02 02:16:23 +00003542 if (isa<BinaryOperator>(Op0)) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003543 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003544 Value *Op0LHS = Op0I->getOperand(0);
3545 Value *Op0RHS = Op0I->getOperand(1);
3546 switch (Op0I->getOpcode()) {
3547 case Instruction::Xor:
3548 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00003549 // If the mask is only needed on one incoming arm, push it up.
3550 if (Op0I->hasOneUse()) {
3551 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3552 // Not masking anything out for the LHS, move to RHS.
3553 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
3554 Op0RHS->getName()+".masked");
3555 InsertNewInstBefore(NewRHS, I);
3556 return BinaryOperator::create(
3557 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003558 }
Chris Lattner3bedbd92006-02-07 07:27:52 +00003559 if (!isa<Constant>(Op0RHS) &&
Chris Lattnerad1e3022005-01-23 20:26:55 +00003560 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3561 // Not masking anything out for the RHS, move to LHS.
3562 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
3563 Op0LHS->getName()+".masked");
3564 InsertNewInstBefore(NewLHS, I);
3565 return BinaryOperator::create(
3566 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3567 }
3568 }
3569
Chris Lattner6e7ba452005-01-01 16:22:27 +00003570 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00003571 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00003572 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3573 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3574 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3575 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3576 return BinaryOperator::createAnd(V, AndRHS);
3577 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3578 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00003579 break;
3580
3581 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00003582 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3583 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3584 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3585 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3586 return BinaryOperator::createAnd(V, AndRHS);
Chris Lattnerc8e77562005-09-18 04:24:45 +00003587 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00003588 }
3589
Chris Lattner58403262003-07-23 19:25:52 +00003590 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003591 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003592 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00003593 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00003594 // If this is an integer truncation or change from signed-to-unsigned, and
3595 // if the source is an and/or with immediate, transform it. This
3596 // frequently occurs for bitfield accesses.
3597 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00003598 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00003599 CastOp->getNumOperands() == 2)
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003600 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
Chris Lattner2b83af22005-08-07 07:03:10 +00003601 if (CastOp->getOpcode() == Instruction::And) {
3602 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00003603 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
3604 // This will fold the two constants together, which may allow
3605 // other simplifications.
Reid Spencerd977d862006-12-12 23:36:14 +00003606 Instruction *NewCast = CastInst::createTruncOrBitCast(
3607 CastOp->getOperand(0), I.getType(),
3608 CastOp->getName()+".shrunk");
Chris Lattner2b83af22005-08-07 07:03:10 +00003609 NewCast = InsertNewInstBefore(NewCast, I);
Reid Spencer3da59db2006-11-27 01:05:10 +00003610 // trunc_or_bitcast(C1)&C2
Reid Spencerd977d862006-12-12 23:36:14 +00003611 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00003612 C3 = ConstantExpr::getAnd(C3, AndRHS);
Chris Lattner2b83af22005-08-07 07:03:10 +00003613 return BinaryOperator::createAnd(NewCast, C3);
3614 } else if (CastOp->getOpcode() == Instruction::Or) {
3615 // Change: and (cast (or X, C1) to T), C2
3616 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattnerbb4e7b22006-12-12 19:11:20 +00003617 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Chris Lattner2b83af22005-08-07 07:03:10 +00003618 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3619 return ReplaceInstUsesWith(I, AndRHS);
3620 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003621 }
Chris Lattner2b83af22005-08-07 07:03:10 +00003622 }
Chris Lattner06782f82003-07-23 19:36:21 +00003623 }
Chris Lattner2eefe512004-04-09 19:05:30 +00003624
3625 // Try to fold constant and into select arguments.
3626 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003627 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00003628 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00003629 if (isa<PHINode>(Op0))
3630 if (Instruction *NV = FoldOpIntoPhi(I))
3631 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00003632 }
3633
Chris Lattner8d969642003-03-10 23:06:50 +00003634 Value *Op0NotVal = dyn_castNotVal(Op0);
3635 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00003636
Chris Lattner5b62aa72004-06-18 06:07:51 +00003637 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3638 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3639
Misha Brukmancb6267b2004-07-30 12:50:08 +00003640 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00003641 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattner48595f12004-06-10 02:07:29 +00003642 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
3643 I.getName()+".demorgan");
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00003644 InsertNewInstBefore(Or, I);
Chris Lattnera2881962003-02-18 19:28:33 +00003645 return BinaryOperator::createNot(Or);
3646 }
Chris Lattner2082ad92006-02-13 23:07:23 +00003647
3648 {
Chris Lattner003b6202007-06-15 05:58:24 +00003649 Value *A = 0, *B = 0, *C = 0, *D = 0;
3650 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00003651 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3652 return ReplaceInstUsesWith(I, Op1);
Chris Lattner003b6202007-06-15 05:58:24 +00003653
3654 // (A|B) & ~(A&B) -> A^B
3655 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
3656 if ((A == C && B == D) || (A == D && B == C))
3657 return BinaryOperator::createXor(A, B);
3658 }
3659 }
3660
3661 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00003662 if (A == Op0 || B == Op0) // A & (A | ?) --> A
3663 return ReplaceInstUsesWith(I, Op0);
Chris Lattner003b6202007-06-15 05:58:24 +00003664
3665 // ~(A&B) & (A|B) -> A^B
3666 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
3667 if ((A == C && B == D) || (A == D && B == C))
3668 return BinaryOperator::createXor(A, B);
3669 }
3670 }
Chris Lattner64daab52006-04-01 08:03:55 +00003671
3672 if (Op0->hasOneUse() &&
3673 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3674 if (A == Op1) { // (A^B)&A -> A&(A^B)
3675 I.swapOperands(); // Simplify below
3676 std::swap(Op0, Op1);
3677 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
3678 cast<BinaryOperator>(Op0)->swapOperands();
3679 I.swapOperands(); // Simplify below
3680 std::swap(Op0, Op1);
3681 }
3682 }
3683 if (Op1->hasOneUse() &&
3684 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3685 if (B == Op0) { // B&(A^B) -> B&(B^A)
3686 cast<BinaryOperator>(Op1)->swapOperands();
3687 std::swap(A, B);
3688 }
3689 if (A == Op0) { // A&(A^B) -> A & ~B
3690 Instruction *NotB = BinaryOperator::createNot(B, "tmp");
3691 InsertNewInstBefore(NotB, I);
3692 return BinaryOperator::createAnd(A, NotB);
3693 }
3694 }
Chris Lattner2082ad92006-02-13 23:07:23 +00003695 }
3696
Reid Spencere4d87aa2006-12-23 06:05:41 +00003697 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3698 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3699 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003700 return R;
3701
Chris Lattner955f3312004-09-28 21:48:02 +00003702 Value *LHSVal, *RHSVal;
3703 ConstantInt *LHSCst, *RHSCst;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003704 ICmpInst::Predicate LHSCC, RHSCC;
3705 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3706 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3707 if (LHSVal == RHSVal && // Found (X icmp C1) & (X icmp C2)
3708 // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3709 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3710 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3711 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
Chris Lattnereec8b9a2007-11-22 23:47:13 +00003712 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
3713
3714 // Don't try to fold ICMP_SLT + ICMP_ULT.
3715 (ICmpInst::isEquality(LHSCC) || ICmpInst::isEquality(RHSCC) ||
3716 ICmpInst::isSignedPredicate(LHSCC) ==
3717 ICmpInst::isSignedPredicate(RHSCC))) {
Chris Lattner955f3312004-09-28 21:48:02 +00003718 // Ensure that the larger constant is on the RHS.
Chris Lattneree2b7a42008-01-13 20:59:02 +00003719 ICmpInst::Predicate GT;
3720 if (ICmpInst::isSignedPredicate(LHSCC) ||
3721 (ICmpInst::isEquality(LHSCC) &&
3722 ICmpInst::isSignedPredicate(RHSCC)))
3723 GT = ICmpInst::ICMP_SGT;
3724 else
3725 GT = ICmpInst::ICMP_UGT;
3726
Reid Spencere4d87aa2006-12-23 06:05:41 +00003727 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3728 ICmpInst *LHS = cast<ICmpInst>(Op0);
Reid Spencer579dca12007-01-12 04:24:46 +00003729 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
Chris Lattner955f3312004-09-28 21:48:02 +00003730 std::swap(LHS, RHS);
3731 std::swap(LHSCst, RHSCst);
3732 std::swap(LHSCC, RHSCC);
3733 }
3734
Reid Spencere4d87aa2006-12-23 06:05:41 +00003735 // At this point, we know we have have two icmp instructions
Chris Lattner955f3312004-09-28 21:48:02 +00003736 // comparing a value against two constants and and'ing the result
3737 // together. Because of the above check, we know that we only have
Reid Spencere4d87aa2006-12-23 06:05:41 +00003738 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3739 // (from the FoldICmpLogical check above), that the two constants
3740 // are not equal and that the larger constant is on the RHS
Chris Lattner955f3312004-09-28 21:48:02 +00003741 assert(LHSCst != RHSCst && "Compares not folded above?");
3742
3743 switch (LHSCC) {
3744 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003745 case ICmpInst::ICMP_EQ:
Chris Lattner955f3312004-09-28 21:48:02 +00003746 switch (RHSCC) {
3747 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003748 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3749 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3750 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003751 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00003752 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3753 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3754 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
Chris Lattner955f3312004-09-28 21:48:02 +00003755 return ReplaceInstUsesWith(I, LHS);
3756 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003757 case ICmpInst::ICMP_NE:
Chris Lattner955f3312004-09-28 21:48:02 +00003758 switch (RHSCC) {
3759 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003760 case ICmpInst::ICMP_ULT:
3761 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3762 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
3763 break; // (X != 13 & X u< 15) -> no change
3764 case ICmpInst::ICMP_SLT:
3765 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3766 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
3767 break; // (X != 13 & X s< 15) -> no change
3768 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3769 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3770 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
Chris Lattner955f3312004-09-28 21:48:02 +00003771 return ReplaceInstUsesWith(I, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003772 case ICmpInst::ICMP_NE:
3773 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Chris Lattner955f3312004-09-28 21:48:02 +00003774 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3775 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3776 LHSVal->getName()+".off");
3777 InsertNewInstBefore(Add, I);
Chris Lattner424db022007-01-27 23:08:34 +00003778 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3779 ConstantInt::get(Add->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +00003780 }
3781 break; // (X != 13 & X != 15) -> no change
3782 }
3783 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003784 case ICmpInst::ICMP_ULT:
Chris Lattner955f3312004-09-28 21:48:02 +00003785 switch (RHSCC) {
3786 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003787 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3788 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003789 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00003790 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3791 break;
3792 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3793 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
Chris Lattner955f3312004-09-28 21:48:02 +00003794 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003795 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3796 break;
Chris Lattner955f3312004-09-28 21:48:02 +00003797 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003798 break;
3799 case ICmpInst::ICMP_SLT:
Chris Lattner955f3312004-09-28 21:48:02 +00003800 switch (RHSCC) {
3801 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003802 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3803 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003804 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00003805 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3806 break;
3807 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3808 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
Chris Lattner955f3312004-09-28 21:48:02 +00003809 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003810 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3811 break;
Chris Lattner955f3312004-09-28 21:48:02 +00003812 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003813 break;
3814 case ICmpInst::ICMP_UGT:
3815 switch (RHSCC) {
3816 default: assert(0 && "Unknown integer condition code!");
3817 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X > 13
3818 return ReplaceInstUsesWith(I, LHS);
3819 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3820 return ReplaceInstUsesWith(I, RHS);
3821 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3822 break;
3823 case ICmpInst::ICMP_NE:
3824 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3825 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3826 break; // (X u> 13 & X != 15) -> no change
3827 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) ->(X-14) <u 1
3828 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false,
3829 true, I);
3830 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3831 break;
3832 }
3833 break;
3834 case ICmpInst::ICMP_SGT:
3835 switch (RHSCC) {
3836 default: assert(0 && "Unknown integer condition code!");
Chris Lattnera7d1ab02007-11-16 06:04:17 +00003837 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
Reid Spencere4d87aa2006-12-23 06:05:41 +00003838 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3839 return ReplaceInstUsesWith(I, RHS);
3840 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3841 break;
3842 case ICmpInst::ICMP_NE:
3843 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3844 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3845 break; // (X s> 13 & X != 15) -> no change
3846 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) ->(X-14) s< 1
3847 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true,
3848 true, I);
3849 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3850 break;
3851 }
3852 break;
Chris Lattner955f3312004-09-28 21:48:02 +00003853 }
3854 }
3855 }
3856
Chris Lattner6fc205f2006-05-05 06:39:07 +00003857 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003858 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3859 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3860 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3861 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00003862 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003863 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003864 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
3865 I.getType(), TD) &&
3866 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
3867 I.getType(), TD)) {
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003868 Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
3869 Op1C->getOperand(0),
3870 I.getName());
3871 InsertNewInstBefore(NewOp, I);
3872 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3873 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00003874 }
Chris Lattnere511b742006-11-14 07:46:50 +00003875
3876 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00003877 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3878 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3879 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00003880 SI0->getOperand(1) == SI1->getOperand(1) &&
3881 (SI0->hasOneUse() || SI1->hasOneUse())) {
3882 Instruction *NewOp =
3883 InsertNewInstBefore(BinaryOperator::createAnd(SI0->getOperand(0),
3884 SI1->getOperand(0),
3885 SI0->getName()), I);
Reid Spencer832254e2007-02-02 02:16:23 +00003886 return BinaryOperator::create(SI1->getOpcode(), NewOp,
3887 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00003888 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00003889 }
3890
Chris Lattner99c65742007-10-24 05:38:08 +00003891 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
3892 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
3893 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
3894 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
3895 RHS->getPredicate() == FCmpInst::FCMP_ORD)
3896 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3897 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3898 // If either of the constants are nans, then the whole thing returns
3899 // false.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00003900 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner99c65742007-10-24 05:38:08 +00003901 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3902 return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
3903 RHS->getOperand(0));
3904 }
3905 }
3906 }
3907
Chris Lattner7e708292002-06-25 16:13:24 +00003908 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00003909}
3910
Chris Lattnerafe91a52006-06-15 19:07:26 +00003911/// CollectBSwapParts - Look to see if the specified value defines a single byte
3912/// in the result. If it does, and if the specified byte hasn't been filled in
3913/// yet, fill it in and return false.
Chris Lattner535014f2007-02-15 22:52:10 +00003914static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00003915 Instruction *I = dyn_cast<Instruction>(V);
3916 if (I == 0) return true;
3917
3918 // If this is an or instruction, it is an inner node of the bswap.
3919 if (I->getOpcode() == Instruction::Or)
3920 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3921 CollectBSwapParts(I->getOperand(1), ByteValues);
3922
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003923 uint32_t BitWidth = I->getType()->getPrimitiveSizeInBits();
Chris Lattnerafe91a52006-06-15 19:07:26 +00003924 // If this is a shift by a constant int, and it is "24", then its operand
3925 // defines a byte. We only handle unsigned types here.
Reid Spencer832254e2007-02-02 02:16:23 +00003926 if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00003927 // Not shifting the entire input by N-1 bytes?
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003928 if (cast<ConstantInt>(I->getOperand(1))->getLimitedValue(BitWidth) !=
Chris Lattnerafe91a52006-06-15 19:07:26 +00003929 8*(ByteValues.size()-1))
3930 return true;
3931
3932 unsigned DestNo;
3933 if (I->getOpcode() == Instruction::Shl) {
3934 // X << 24 defines the top byte with the lowest of the input bytes.
3935 DestNo = ByteValues.size()-1;
3936 } else {
3937 // X >>u 24 defines the low byte with the highest of the input bytes.
3938 DestNo = 0;
3939 }
3940
3941 // If the destination byte value is already defined, the values are or'd
3942 // together, which isn't a bswap (unless it's an or of the same bits).
3943 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3944 return true;
3945 ByteValues[DestNo] = I->getOperand(0);
3946 return false;
3947 }
3948
3949 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
3950 // don't have this.
3951 Value *Shift = 0, *ShiftLHS = 0;
3952 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3953 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3954 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3955 return true;
3956 Instruction *SI = cast<Instruction>(Shift);
3957
3958 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003959 if (ShiftAmt->getLimitedValue(BitWidth) & 7 ||
3960 ShiftAmt->getLimitedValue(BitWidth) > 8*ByteValues.size())
Chris Lattnerafe91a52006-06-15 19:07:26 +00003961 return true;
3962
3963 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3964 unsigned DestByte;
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003965 if (AndAmt->getValue().getActiveBits() > 64)
3966 return true;
3967 uint64_t AndAmtVal = AndAmt->getZExtValue();
Chris Lattnerafe91a52006-06-15 19:07:26 +00003968 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003969 if (AndAmtVal == uint64_t(0xFF) << 8*DestByte)
Chris Lattnerafe91a52006-06-15 19:07:26 +00003970 break;
3971 // Unknown mask for bswap.
3972 if (DestByte == ByteValues.size()) return true;
3973
Reid Spencerb83eb642006-10-20 07:07:24 +00003974 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
Chris Lattnerafe91a52006-06-15 19:07:26 +00003975 unsigned SrcByte;
3976 if (SI->getOpcode() == Instruction::Shl)
3977 SrcByte = DestByte - ShiftBytes;
3978 else
3979 SrcByte = DestByte + ShiftBytes;
3980
3981 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3982 if (SrcByte != ByteValues.size()-DestByte-1)
3983 return true;
3984
3985 // If the destination byte value is already defined, the values are or'd
3986 // together, which isn't a bswap (unless it's an or of the same bits).
3987 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3988 return true;
3989 ByteValues[DestByte] = SI->getOperand(0);
3990 return false;
3991}
3992
3993/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3994/// If so, insert the new bswap intrinsic and return it.
3995Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattner55fc8c42007-04-01 20:57:36 +00003996 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
3997 if (!ITy || ITy->getBitWidth() % 16)
3998 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerafe91a52006-06-15 19:07:26 +00003999
4000 /// ByteValues - For each byte of the result, we keep track of which value
4001 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00004002 SmallVector<Value*, 8> ByteValues;
Chris Lattner55fc8c42007-04-01 20:57:36 +00004003 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004004
4005 // Try to find all the pieces corresponding to the bswap.
4006 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
4007 CollectBSwapParts(I.getOperand(1), ByteValues))
4008 return 0;
4009
4010 // Check to see if all of the bytes come from the same value.
4011 Value *V = ByteValues[0];
4012 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4013
4014 // Check to make sure that all of the bytes come from the same value.
4015 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4016 if (ByteValues[i] != V)
4017 return 0;
Chandler Carruth69940402007-08-04 01:51:18 +00004018 const Type *Tys[] = { ITy };
Chris Lattnerafe91a52006-06-15 19:07:26 +00004019 Module *M = I.getParent()->getParent()->getParent();
Chandler Carruth69940402007-08-04 01:51:18 +00004020 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004021 return new CallInst(F, V);
4022}
4023
4024
Chris Lattner7e708292002-06-25 16:13:24 +00004025Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004026 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004027 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004028
Chris Lattner42593e62007-03-24 23:56:43 +00004029 if (isa<UndefValue>(Op1)) // X | undef -> -1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004030 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004031
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004032 // or X, X = X
4033 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00004034 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004035
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004036 // See if we can simplify any instructions used by the instruction whose sole
4037 // purpose is to compute bits we don't care about.
Chris Lattner42593e62007-03-24 23:56:43 +00004038 if (!isa<VectorType>(I.getType())) {
4039 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4040 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4041 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4042 KnownZero, KnownOne))
4043 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00004044 } else if (isa<ConstantAggregateZero>(Op1)) {
4045 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4046 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4047 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4048 return ReplaceInstUsesWith(I, I.getOperand(1));
Chris Lattner42593e62007-03-24 23:56:43 +00004049 }
Chris Lattner041a6c92007-06-15 05:26:55 +00004050
4051
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004052
Chris Lattner3f5b8772002-05-06 16:14:14 +00004053 // or X, -1 == -1
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004054 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00004055 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004056 // (X & C1) | C2 --> (X | C2) & (C1|C2)
4057 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattner6934a042007-02-11 01:23:03 +00004058 Instruction *Or = BinaryOperator::createOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004059 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00004060 Or->takeName(Op0);
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004061 return BinaryOperator::createAnd(Or,
4062 ConstantInt::get(RHS->getValue() | C1->getValue()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004063 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004064
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004065 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4066 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattner6934a042007-02-11 01:23:03 +00004067 Instruction *Or = BinaryOperator::createOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004068 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00004069 Or->takeName(Op0);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004070 return BinaryOperator::createXor(Or,
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004071 ConstantInt::get(C1->getValue() & ~RHS->getValue()));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004072 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004073
4074 // Try to fold constant and into select arguments.
4075 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004076 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004077 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004078 if (isa<PHINode>(Op0))
4079 if (Instruction *NV = FoldOpIntoPhi(I))
4080 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004081 }
4082
Chris Lattner4f637d42006-01-06 17:59:59 +00004083 Value *A = 0, *B = 0;
4084 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004085
4086 if (match(Op0, m_And(m_Value(A), m_Value(B))))
4087 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4088 return ReplaceInstUsesWith(I, Op1);
4089 if (match(Op1, m_And(m_Value(A), m_Value(B))))
4090 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4091 return ReplaceInstUsesWith(I, Op0);
4092
Chris Lattner6423d4c2006-07-10 20:25:24 +00004093 // (A | B) | C and A | (B | C) -> bswap if possible.
4094 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004095 if (match(Op0, m_Or(m_Value(), m_Value())) ||
Chris Lattner6423d4c2006-07-10 20:25:24 +00004096 match(Op1, m_Or(m_Value(), m_Value())) ||
4097 (match(Op0, m_Shift(m_Value(), m_Value())) &&
4098 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00004099 if (Instruction *BSwap = MatchBSwap(I))
4100 return BSwap;
4101 }
4102
Chris Lattner6e4c6492005-05-09 04:58:36 +00004103 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4104 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004105 MaskedValueIsZero(Op1, C1->getValue())) {
Chris Lattner6934a042007-02-11 01:23:03 +00004106 Instruction *NOr = BinaryOperator::createOr(A, Op1);
4107 InsertNewInstBefore(NOr, I);
4108 NOr->takeName(Op0);
4109 return BinaryOperator::createXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004110 }
4111
4112 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4113 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004114 MaskedValueIsZero(Op0, C1->getValue())) {
Chris Lattner6934a042007-02-11 01:23:03 +00004115 Instruction *NOr = BinaryOperator::createOr(A, Op0);
4116 InsertNewInstBefore(NOr, I);
4117 NOr->takeName(Op0);
4118 return BinaryOperator::createXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004119 }
4120
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004121 // (A & C)|(B & D)
Chris Lattner2384d7b2007-06-19 05:43:49 +00004122 Value *C = 0, *D = 0;
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004123 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4124 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004125 Value *V1 = 0, *V2 = 0, *V3 = 0;
4126 C1 = dyn_cast<ConstantInt>(C);
4127 C2 = dyn_cast<ConstantInt>(D);
4128 if (C1 && C2) { // (A & C1)|(B & C2)
4129 // If we have: ((V + N) & C1) | (V & C2)
4130 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4131 // replace with V+N.
4132 if (C1->getValue() == ~C2->getValue()) {
4133 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4134 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4135 // Add commutes, try both ways.
4136 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4137 return ReplaceInstUsesWith(I, A);
4138 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4139 return ReplaceInstUsesWith(I, A);
4140 }
4141 // Or commutes, try both ways.
4142 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4143 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4144 // Add commutes, try both ways.
4145 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4146 return ReplaceInstUsesWith(I, B);
4147 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4148 return ReplaceInstUsesWith(I, B);
4149 }
4150 }
Chris Lattner044e5332007-04-08 08:01:49 +00004151 V1 = 0; V2 = 0; V3 = 0;
Chris Lattner6cae0e02007-04-08 07:55:22 +00004152 }
4153
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004154 // Check to see if we have any common things being and'ed. If so, find the
4155 // terms for V1 & (V2|V3).
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004156 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4157 if (A == B) // (A & C)|(A & D) == A & (C|D)
4158 V1 = A, V2 = C, V3 = D;
4159 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4160 V1 = A, V2 = B, V3 = C;
4161 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4162 V1 = C, V2 = A, V3 = D;
4163 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4164 V1 = C, V2 = A, V3 = B;
4165
4166 if (V1) {
4167 Value *Or =
4168 InsertNewInstBefore(BinaryOperator::createOr(V2, V3, "tmp"), I);
4169 return BinaryOperator::createAnd(V1, Or);
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00004170 }
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004171 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004172 }
Chris Lattnere511b742006-11-14 07:46:50 +00004173
4174 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004175 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4176 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4177 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004178 SI0->getOperand(1) == SI1->getOperand(1) &&
4179 (SI0->hasOneUse() || SI1->hasOneUse())) {
4180 Instruction *NewOp =
4181 InsertNewInstBefore(BinaryOperator::createOr(SI0->getOperand(0),
4182 SI1->getOperand(0),
4183 SI0->getName()), I);
Reid Spencer832254e2007-02-02 02:16:23 +00004184 return BinaryOperator::create(SI1->getOpcode(), NewOp,
4185 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004186 }
4187 }
Chris Lattner67ca7682003-08-12 19:11:07 +00004188
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004189 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
4190 if (A == Op1) // ~A | A == -1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004191 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004192 } else {
4193 A = 0;
4194 }
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004195 // Note, A is still live here!
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004196 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
4197 if (Op0 == B)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004198 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera27231a2003-03-10 23:13:59 +00004199
Misha Brukmancb6267b2004-07-30 12:50:08 +00004200 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004201 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4202 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
4203 I.getName()+".demorgan"), I);
4204 return BinaryOperator::createNot(And);
4205 }
Chris Lattnera27231a2003-03-10 23:13:59 +00004206 }
Chris Lattnera2881962003-02-18 19:28:33 +00004207
Reid Spencere4d87aa2006-12-23 06:05:41 +00004208 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4209 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4210 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004211 return R;
4212
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004213 Value *LHSVal, *RHSVal;
4214 ConstantInt *LHSCst, *RHSCst;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004215 ICmpInst::Predicate LHSCC, RHSCC;
4216 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
4217 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
4218 if (LHSVal == RHSVal && // Found (X icmp C1) | (X icmp C2)
4219 // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
4220 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
4221 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
4222 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
Chris Lattner88858872007-05-11 05:55:56 +00004223 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
4224 // We can't fold (ugt x, C) | (sgt x, C2).
4225 PredicatesFoldable(LHSCC, RHSCC)) {
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004226 // Ensure that the larger constant is on the RHS.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004227 ICmpInst *LHS = cast<ICmpInst>(Op0);
Chris Lattner88858872007-05-11 05:55:56 +00004228 bool NeedsSwap;
4229 if (ICmpInst::isSignedPredicate(LHSCC))
Chris Lattner3aea1bd2007-05-11 16:58:45 +00004230 NeedsSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner88858872007-05-11 05:55:56 +00004231 else
Chris Lattner3aea1bd2007-05-11 16:58:45 +00004232 NeedsSwap = LHSCst->getValue().ugt(RHSCst->getValue());
Chris Lattner88858872007-05-11 05:55:56 +00004233
4234 if (NeedsSwap) {
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004235 std::swap(LHS, RHS);
4236 std::swap(LHSCst, RHSCst);
4237 std::swap(LHSCC, RHSCC);
4238 }
4239
Reid Spencere4d87aa2006-12-23 06:05:41 +00004240 // At this point, we know we have have two icmp instructions
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004241 // comparing a value against two constants and or'ing the result
4242 // together. Because of the above check, we know that we only have
Reid Spencere4d87aa2006-12-23 06:05:41 +00004243 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4244 // FoldICmpLogical check above), that the two constants are not
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004245 // equal.
4246 assert(LHSCst != RHSCst && "Compares not folded above?");
4247
4248 switch (LHSCC) {
4249 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004250 case ICmpInst::ICMP_EQ:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004251 switch (RHSCC) {
4252 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004253 case ICmpInst::ICMP_EQ:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004254 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
4255 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4256 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
4257 LHSVal->getName()+".off");
4258 InsertNewInstBefore(Add, I);
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004259 AddCST = Subtract(AddOne(RHSCst), LHSCst);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004260 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004261 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004262 break; // (X == 13 | X == 15) -> no change
4263 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4264 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
Chris Lattner240d6f42005-04-19 06:04:18 +00004265 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004266 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4267 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4268 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004269 return ReplaceInstUsesWith(I, RHS);
4270 }
4271 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004272 case ICmpInst::ICMP_NE:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004273 switch (RHSCC) {
4274 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004275 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4276 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4277 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004278 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004279 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4280 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4281 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004282 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004283 }
4284 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004285 case ICmpInst::ICMP_ULT:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004286 switch (RHSCC) {
4287 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004288 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004289 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004290 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) ->(X-13) u> 2
Chris Lattner74e012a2007-11-01 02:18:41 +00004291 // If RHSCst is [us]MAXINT, it is always false. Not handling
4292 // this can cause overflow.
4293 if (RHSCst->isMaxValue(false))
4294 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004295 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false,
4296 false, I);
4297 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4298 break;
4299 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4300 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004301 return ReplaceInstUsesWith(I, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004302 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4303 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004304 }
4305 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004306 case ICmpInst::ICMP_SLT:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004307 switch (RHSCC) {
4308 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004309 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4310 break;
4311 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) ->(X-13) s> 2
Chris Lattner74e012a2007-11-01 02:18:41 +00004312 // If RHSCst is [us]MAXINT, it is always false. Not handling
4313 // this can cause overflow.
4314 if (RHSCst->isMaxValue(true))
4315 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004316 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true,
4317 false, I);
4318 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4319 break;
4320 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4321 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4322 return ReplaceInstUsesWith(I, RHS);
4323 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4324 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004325 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004326 break;
4327 case ICmpInst::ICMP_UGT:
4328 switch (RHSCC) {
4329 default: assert(0 && "Unknown integer condition code!");
4330 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4331 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4332 return ReplaceInstUsesWith(I, LHS);
4333 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4334 break;
4335 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4336 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004337 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004338 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4339 break;
4340 }
4341 break;
4342 case ICmpInst::ICMP_SGT:
4343 switch (RHSCC) {
4344 default: assert(0 && "Unknown integer condition code!");
4345 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4346 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4347 return ReplaceInstUsesWith(I, LHS);
4348 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4349 break;
4350 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4351 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004352 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004353 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4354 break;
4355 }
4356 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004357 }
4358 }
4359 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004360
4361 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00004362 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00004363 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004364 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4365 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00004366 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004367 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004368 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4369 I.getType(), TD) &&
4370 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4371 I.getType(), TD)) {
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004372 Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
4373 Op1C->getOperand(0),
4374 I.getName());
4375 InsertNewInstBefore(NewOp, I);
4376 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4377 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004378 }
Chris Lattner99c65742007-10-24 05:38:08 +00004379 }
4380
4381
4382 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4383 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4384 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4385 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
Chris Lattner5ebd9362008-02-29 06:09:11 +00004386 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
4387 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType())
Chris Lattner99c65742007-10-24 05:38:08 +00004388 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4389 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4390 // If either of the constants are nans, then the whole thing returns
4391 // true.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00004392 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner99c65742007-10-24 05:38:08 +00004393 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4394
4395 // Otherwise, no need to compare the two constants, compare the
4396 // rest.
4397 return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4398 RHS->getOperand(0));
4399 }
4400 }
4401 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004402
Chris Lattner7e708292002-06-25 16:13:24 +00004403 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004404}
4405
Chris Lattnerc317d392004-02-16 01:20:27 +00004406// XorSelf - Implements: X ^ X --> 0
4407struct XorSelf {
4408 Value *RHS;
4409 XorSelf(Value *rhs) : RHS(rhs) {}
4410 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4411 Instruction *apply(BinaryOperator &Xor) const {
4412 return &Xor;
4413 }
4414};
Chris Lattner3f5b8772002-05-06 16:14:14 +00004415
4416
Chris Lattner7e708292002-06-25 16:13:24 +00004417Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004418 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004419 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004420
Chris Lattnere87597f2004-10-16 18:11:37 +00004421 if (isa<UndefValue>(Op1))
4422 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
4423
Chris Lattnerc317d392004-02-16 01:20:27 +00004424 // xor X, X = 0, even if X is nested in a sequence of Xor's.
4425 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00004426 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Chris Lattner233f7dc2002-08-12 21:17:25 +00004427 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00004428 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004429
4430 // See if we can simplify any instructions used by the instruction whose sole
4431 // purpose is to compute bits we don't care about.
Reid Spencera03d45f2007-03-22 22:19:58 +00004432 if (!isa<VectorType>(I.getType())) {
4433 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4434 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4435 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4436 KnownZero, KnownOne))
4437 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00004438 } else if (isa<ConstantAggregateZero>(Op1)) {
4439 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Reid Spencera03d45f2007-03-22 22:19:58 +00004440 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00004441
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004442 // Is this a ~ operation?
4443 if (Value *NotOp = dyn_castNotVal(&I)) {
4444 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4445 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4446 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4447 if (Op0I->getOpcode() == Instruction::And ||
4448 Op0I->getOpcode() == Instruction::Or) {
4449 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4450 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4451 Instruction *NotY =
4452 BinaryOperator::createNot(Op0I->getOperand(1),
4453 Op0I->getOperand(1)->getName()+".not");
4454 InsertNewInstBefore(NotY, I);
4455 if (Op0I->getOpcode() == Instruction::And)
4456 return BinaryOperator::createOr(Op0NotVal, NotY);
4457 else
4458 return BinaryOperator::createAnd(Op0NotVal, NotY);
4459 }
4460 }
4461 }
4462 }
4463
4464
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004465 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00004466 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
4467 if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
4468 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00004469 return new ICmpInst(ICI->getInversePredicate(),
4470 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00004471
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00004472 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
4473 return new FCmpInst(FCI->getInversePredicate(),
4474 FCI->getOperand(0), FCI->getOperand(1));
4475 }
4476
Reid Spencere4d87aa2006-12-23 06:05:41 +00004477 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00004478 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00004479 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4480 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattner48595f12004-06-10 02:07:29 +00004481 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4482 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattner7c4049c2004-01-12 19:35:11 +00004483 ConstantInt::get(I.getType(), 1));
Chris Lattner48595f12004-06-10 02:07:29 +00004484 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00004485 }
Chris Lattner5c6e2db2007-04-02 05:36:22 +00004486
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004487 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004488 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00004489 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00004490 if (RHS->isAllOnesValue()) {
Chris Lattner48595f12004-06-10 02:07:29 +00004491 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
4492 return BinaryOperator::createSub(
4493 ConstantExpr::getSub(NegOp0CI,
Chris Lattner7c4049c2004-01-12 19:35:11 +00004494 ConstantInt::get(I.getType(), 1)),
Chris Lattner689d24b2003-11-04 23:37:10 +00004495 Op0I->getOperand(0));
Chris Lattneracf4e072007-04-02 05:42:22 +00004496 } else if (RHS->getValue().isSignBit()) {
Chris Lattner5c6e2db2007-04-02 05:36:22 +00004497 // (X + C) ^ signbit -> (X + C + signbit)
4498 Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
4499 return BinaryOperator::createAdd(Op0I->getOperand(0), C);
Chris Lattnercd1d6d52007-04-02 05:48:58 +00004500
Chris Lattner7c4049c2004-01-12 19:35:11 +00004501 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00004502 } else if (Op0I->getOpcode() == Instruction::Or) {
4503 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencera03d45f2007-03-22 22:19:58 +00004504 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Chris Lattner02bd1b32006-02-26 19:57:54 +00004505 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4506 // Anything in both C1 and C2 is known to be zero, remove it from
4507 // NewRHS.
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004508 Constant *CommonBits = And(Op0CI, RHS);
Chris Lattner02bd1b32006-02-26 19:57:54 +00004509 NewRHS = ConstantExpr::getAnd(NewRHS,
4510 ConstantExpr::getNot(CommonBits));
Chris Lattnerdbab3862007-03-02 21:28:56 +00004511 AddToWorkList(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00004512 I.setOperand(0, Op0I->getOperand(0));
4513 I.setOperand(1, NewRHS);
4514 return &I;
4515 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00004516 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004517 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00004518 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004519
4520 // Try to fold constant and into select arguments.
4521 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004522 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004523 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004524 if (isa<PHINode>(Op0))
4525 if (Instruction *NV = FoldOpIntoPhi(I))
4526 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004527 }
4528
Chris Lattner8d969642003-03-10 23:06:50 +00004529 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00004530 if (X == Op1)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004531 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00004532
Chris Lattner8d969642003-03-10 23:06:50 +00004533 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00004534 if (X == Op0)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004535 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00004536
Chris Lattner318bf792007-03-18 22:51:34 +00004537
4538 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
4539 if (Op1I) {
4540 Value *A, *B;
4541 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
4542 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00004543 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00004544 I.swapOperands();
4545 std::swap(Op0, Op1);
Chris Lattner318bf792007-03-18 22:51:34 +00004546 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00004547 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00004548 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00004549 }
Chris Lattner318bf792007-03-18 22:51:34 +00004550 } else if (match(Op1I, m_Xor(m_Value(A), m_Value(B)))) {
4551 if (Op0 == A) // A^(A^B) == B
4552 return ReplaceInstUsesWith(I, B);
4553 else if (Op0 == B) // A^(B^A) == B
4554 return ReplaceInstUsesWith(I, A);
4555 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
Chris Lattner6abbdf92007-04-01 05:36:37 +00004556 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattner64daab52006-04-01 08:03:55 +00004557 Op1I->swapOperands();
Chris Lattner6abbdf92007-04-01 05:36:37 +00004558 std::swap(A, B);
4559 }
Chris Lattner318bf792007-03-18 22:51:34 +00004560 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattner64daab52006-04-01 08:03:55 +00004561 I.swapOperands(); // Simplified below.
4562 std::swap(Op0, Op1);
4563 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00004564 }
Chris Lattner318bf792007-03-18 22:51:34 +00004565 }
4566
4567 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
4568 if (Op0I) {
4569 Value *A, *B;
4570 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
4571 if (A == Op1) // (B|A)^B == (A|B)^B
4572 std::swap(A, B);
4573 if (B == Op1) { // (A|B)^B == A & ~B
4574 Instruction *NotB =
4575 InsertNewInstBefore(BinaryOperator::createNot(Op1, "tmp"), I);
4576 return BinaryOperator::createAnd(A, NotB);
Chris Lattnercb40a372003-03-10 18:24:17 +00004577 }
Chris Lattner318bf792007-03-18 22:51:34 +00004578 } else if (match(Op0I, m_Xor(m_Value(A), m_Value(B)))) {
4579 if (Op1 == A) // (A^B)^A == B
4580 return ReplaceInstUsesWith(I, B);
4581 else if (Op1 == B) // (B^A)^A == B
4582 return ReplaceInstUsesWith(I, A);
4583 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
4584 if (A == Op1) // (A&B)^A -> (B&A)^A
4585 std::swap(A, B);
4586 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattnerae1ab392006-04-01 22:05:01 +00004587 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner318bf792007-03-18 22:51:34 +00004588 Instruction *N =
4589 InsertNewInstBefore(BinaryOperator::createNot(A, "tmp"), I);
Chris Lattner64daab52006-04-01 08:03:55 +00004590 return BinaryOperator::createAnd(N, Op1);
4591 }
Chris Lattnercb40a372003-03-10 18:24:17 +00004592 }
Chris Lattner318bf792007-03-18 22:51:34 +00004593 }
4594
4595 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
4596 if (Op0I && Op1I && Op0I->isShift() &&
4597 Op0I->getOpcode() == Op1I->getOpcode() &&
4598 Op0I->getOperand(1) == Op1I->getOperand(1) &&
4599 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
4600 Instruction *NewOp =
4601 InsertNewInstBefore(BinaryOperator::createXor(Op0I->getOperand(0),
4602 Op1I->getOperand(0),
4603 Op0I->getName()), I);
4604 return BinaryOperator::create(Op1I->getOpcode(), NewOp,
4605 Op1I->getOperand(1));
4606 }
4607
4608 if (Op0I && Op1I) {
4609 Value *A, *B, *C, *D;
4610 // (A & B)^(A | B) -> A ^ B
4611 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4612 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
4613 if ((A == C && B == D) || (A == D && B == C))
4614 return BinaryOperator::createXor(A, B);
4615 }
4616 // (A | B)^(A & B) -> A ^ B
4617 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
4618 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4619 if ((A == C && B == D) || (A == D && B == C))
4620 return BinaryOperator::createXor(A, B);
4621 }
4622
4623 // (A & B)^(C & D)
4624 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
4625 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4626 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4627 // (X & Y)^(X & Y) -> (Y^Z) & X
4628 Value *X = 0, *Y = 0, *Z = 0;
4629 if (A == C)
4630 X = A, Y = B, Z = D;
4631 else if (A == D)
4632 X = A, Y = B, Z = C;
4633 else if (B == C)
4634 X = B, Y = A, Z = D;
4635 else if (B == D)
4636 X = B, Y = A, Z = C;
4637
4638 if (X) {
4639 Instruction *NewOp =
4640 InsertNewInstBefore(BinaryOperator::createXor(Y, Z, Op0->getName()), I);
4641 return BinaryOperator::createAnd(NewOp, X);
4642 }
4643 }
4644 }
4645
Reid Spencere4d87aa2006-12-23 06:05:41 +00004646 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4647 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4648 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004649 return R;
4650
Chris Lattner6fc205f2006-05-05 06:39:07 +00004651 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00004652 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00004653 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004654 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4655 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00004656 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004657 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004658 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4659 I.getType(), TD) &&
4660 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4661 I.getType(), TD)) {
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004662 Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
4663 Op1C->getOperand(0),
4664 I.getName());
4665 InsertNewInstBefore(NewOp, I);
4666 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4667 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004668 }
Chris Lattner99c65742007-10-24 05:38:08 +00004669 }
Chris Lattner7e708292002-06-25 16:13:24 +00004670 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004671}
4672
Chris Lattnera96879a2004-09-29 17:40:11 +00004673/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4674/// overflowed for this type.
4675static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
Reid Spencere4e40032007-03-21 23:19:50 +00004676 ConstantInt *In2, bool IsSigned = false) {
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004677 Result = cast<ConstantInt>(Add(In1, In2));
Chris Lattnera96879a2004-09-29 17:40:11 +00004678
Reid Spencere4e40032007-03-21 23:19:50 +00004679 if (IsSigned)
4680 if (In2->getValue().isNegative())
4681 return Result->getValue().sgt(In1->getValue());
4682 else
4683 return Result->getValue().slt(In1->getValue());
4684 else
4685 return Result->getValue().ult(In1->getValue());
Chris Lattnera96879a2004-09-29 17:40:11 +00004686}
4687
Chris Lattner574da9b2005-01-13 20:14:25 +00004688/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4689/// code necessary to compute the offset from the base pointer (without adding
4690/// in the base pointer). Return the result as a signed integer of intptr size.
4691static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4692 TargetData &TD = IC.getTargetData();
4693 gep_type_iterator GTI = gep_type_begin(GEP);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004694 const Type *IntPtrTy = TD.getIntPtrType();
4695 Value *Result = Constant::getNullValue(IntPtrTy);
Chris Lattner574da9b2005-01-13 20:14:25 +00004696
4697 // Build a mask for high order bits.
Chris Lattnere62f0212007-04-28 04:52:43 +00004698 unsigned IntPtrWidth = TD.getPointerSize()*8;
4699 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Chris Lattner574da9b2005-01-13 20:14:25 +00004700
Chris Lattner574da9b2005-01-13 20:14:25 +00004701 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
4702 Value *Op = GEP->getOperand(i);
Duncan Sands514ab342007-11-01 20:53:16 +00004703 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattnere62f0212007-04-28 04:52:43 +00004704 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
4705 if (OpC->isZero()) continue;
4706
4707 // Handle a struct index, which adds its field offset to the pointer.
4708 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4709 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
4710
4711 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
4712 Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
Chris Lattner9bc14642007-04-28 00:57:34 +00004713 else
Chris Lattnere62f0212007-04-28 04:52:43 +00004714 Result = IC.InsertNewInstBefore(
4715 BinaryOperator::createAdd(Result,
4716 ConstantInt::get(IntPtrTy, Size),
4717 GEP->getName()+".offs"), I);
4718 continue;
Chris Lattner9bc14642007-04-28 00:57:34 +00004719 }
Chris Lattnere62f0212007-04-28 04:52:43 +00004720
4721 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4722 Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
4723 Scale = ConstantExpr::getMul(OC, Scale);
4724 if (Constant *RC = dyn_cast<Constant>(Result))
4725 Result = ConstantExpr::getAdd(RC, Scale);
4726 else {
4727 // Emit an add instruction.
4728 Result = IC.InsertNewInstBefore(
4729 BinaryOperator::createAdd(Result, Scale,
4730 GEP->getName()+".offs"), I);
Chris Lattner9bc14642007-04-28 00:57:34 +00004731 }
Chris Lattnere62f0212007-04-28 04:52:43 +00004732 continue;
Chris Lattner574da9b2005-01-13 20:14:25 +00004733 }
Chris Lattnere62f0212007-04-28 04:52:43 +00004734 // Convert to correct type.
4735 if (Op->getType() != IntPtrTy) {
4736 if (Constant *OpC = dyn_cast<Constant>(Op))
4737 Op = ConstantExpr::getSExt(OpC, IntPtrTy);
4738 else
4739 Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
4740 Op->getName()+".c"), I);
4741 }
4742 if (Size != 1) {
4743 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4744 if (Constant *OpC = dyn_cast<Constant>(Op))
4745 Op = ConstantExpr::getMul(OpC, Scale);
4746 else // We'll let instcombine(mul) convert this to a shl if possible.
4747 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
4748 GEP->getName()+".idx"), I);
4749 }
4750
4751 // Emit an add instruction.
4752 if (isa<Constant>(Op) && isa<Constant>(Result))
4753 Result = ConstantExpr::getAdd(cast<Constant>(Op),
4754 cast<Constant>(Result));
4755 else
4756 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
4757 GEP->getName()+".offs"), I);
Chris Lattner574da9b2005-01-13 20:14:25 +00004758 }
4759 return Result;
4760}
4761
Reid Spencere4d87aa2006-12-23 06:05:41 +00004762/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner574da9b2005-01-13 20:14:25 +00004763/// else. At this point we know that the GEP is on the LHS of the comparison.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004764Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
4765 ICmpInst::Predicate Cond,
4766 Instruction &I) {
Chris Lattner574da9b2005-01-13 20:14:25 +00004767 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattnere9d782b2005-01-13 22:25:21 +00004768
4769 if (CastInst *CI = dyn_cast<CastInst>(RHS))
4770 if (isa<PointerType>(CI->getOperand(0)->getType()))
4771 RHS = CI->getOperand(0);
4772
Chris Lattner574da9b2005-01-13 20:14:25 +00004773 Value *PtrBase = GEPLHS->getOperand(0);
4774 if (PtrBase == RHS) {
Chris Lattner7c95deb2008-02-05 04:45:32 +00004775 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
4776 // This transformation is valid because we know pointers can't overflow.
4777 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
4778 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
4779 Constant::getNullValue(Offset->getType()));
Chris Lattner574da9b2005-01-13 20:14:25 +00004780 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00004781 // If the base pointers are different, but the indices are the same, just
4782 // compare the base pointer.
4783 if (PtrBase != GEPRHS->getOperand(0)) {
4784 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00004785 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00004786 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00004787 if (IndicesTheSame)
4788 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4789 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4790 IndicesTheSame = false;
4791 break;
4792 }
4793
4794 // If all indices are the same, just compare the base pointers.
4795 if (IndicesTheSame)
Reid Spencere4d87aa2006-12-23 06:05:41 +00004796 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
4797 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera70b66d2005-04-25 20:17:30 +00004798
4799 // Otherwise, the base pointers are different and the indices are
4800 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00004801 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00004802 }
Chris Lattner574da9b2005-01-13 20:14:25 +00004803
Chris Lattnere9d782b2005-01-13 22:25:21 +00004804 // If one of the GEPs has all zero indices, recurse.
4805 bool AllZeros = true;
4806 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4807 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4808 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4809 AllZeros = false;
4810 break;
4811 }
4812 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00004813 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
4814 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00004815
4816 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00004817 AllZeros = true;
4818 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4819 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4820 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4821 AllZeros = false;
4822 break;
4823 }
4824 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00004825 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattnere9d782b2005-01-13 22:25:21 +00004826
Chris Lattner4401c9c2005-01-14 00:20:05 +00004827 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4828 // If the GEPs only differ by one index, compare it.
4829 unsigned NumDifferences = 0; // Keep track of # differences.
4830 unsigned DiffOperand = 0; // The operand that differs.
4831 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4832 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00004833 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4834 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00004835 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00004836 NumDifferences = 2;
4837 break;
4838 } else {
4839 if (NumDifferences++) break;
4840 DiffOperand = i;
4841 }
4842 }
4843
4844 if (NumDifferences == 0) // SAME GEP?
4845 return ReplaceInstUsesWith(I, // No comparison is needed here.
Nick Lewycky455e1762007-09-06 02:40:25 +00004846 ConstantInt::get(Type::Int1Ty,
4847 isTrueWhenEqual(Cond)));
4848
Chris Lattner4401c9c2005-01-14 00:20:05 +00004849 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00004850 Value *LHSV = GEPLHS->getOperand(DiffOperand);
4851 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004852 // Make sure we do a signed comparison here.
4853 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00004854 }
4855 }
4856
Reid Spencere4d87aa2006-12-23 06:05:41 +00004857 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00004858 // the result to fold to a constant!
4859 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4860 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4861 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
4862 Value *L = EmitGEPOffset(GEPLHS, I, *this);
4863 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004864 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner574da9b2005-01-13 20:14:25 +00004865 }
4866 }
4867 return 0;
4868}
4869
Reid Spencere4d87aa2006-12-23 06:05:41 +00004870Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
4871 bool Changed = SimplifyCompare(I);
Chris Lattner8b170942002-08-09 23:47:40 +00004872 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004873
Chris Lattner58e97462007-01-14 19:42:17 +00004874 // Fold trivial predicates.
4875 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
4876 return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
4877 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
4878 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4879
4880 // Simplify 'fcmp pred X, X'
4881 if (Op0 == Op1) {
4882 switch (I.getPredicate()) {
4883 default: assert(0 && "Unknown predicate!");
4884 case FCmpInst::FCMP_UEQ: // True if unordered or equal
4885 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
4886 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
4887 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4888 case FCmpInst::FCMP_OGT: // True if ordered and greater than
4889 case FCmpInst::FCMP_OLT: // True if ordered and less than
4890 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
4891 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4892
4893 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
4894 case FCmpInst::FCMP_ULT: // True if unordered or less than
4895 case FCmpInst::FCMP_UGT: // True if unordered or greater than
4896 case FCmpInst::FCMP_UNE: // True if unordered or not equal
4897 // Canonicalize these to be 'fcmp uno %X, 0.0'.
4898 I.setPredicate(FCmpInst::FCMP_UNO);
4899 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4900 return &I;
4901
4902 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
4903 case FCmpInst::FCMP_OEQ: // True if ordered and equal
4904 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
4905 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
4906 // Canonicalize these to be 'fcmp ord %X, 0.0'.
4907 I.setPredicate(FCmpInst::FCMP_ORD);
4908 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4909 return &I;
4910 }
4911 }
4912
Reid Spencere4d87aa2006-12-23 06:05:41 +00004913 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Reid Spencer4fe16d62007-01-11 18:21:29 +00004914 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Chris Lattnere87597f2004-10-16 18:11:37 +00004915
Reid Spencere4d87aa2006-12-23 06:05:41 +00004916 // Handle fcmp with constant RHS
4917 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4918 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4919 switch (LHSI->getOpcode()) {
4920 case Instruction::PHI:
4921 if (Instruction *NV = FoldOpIntoPhi(I))
4922 return NV;
4923 break;
4924 case Instruction::Select:
4925 // If either operand of the select is a constant, we can fold the
4926 // comparison into the select arms, which will cause one to be
4927 // constant folded and the select turned into a bitwise or.
4928 Value *Op1 = 0, *Op2 = 0;
4929 if (LHSI->hasOneUse()) {
4930 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4931 // Fold the known value into the constant operand.
4932 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4933 // Insert a new FCmp of the other select operand.
4934 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4935 LHSI->getOperand(2), RHSC,
4936 I.getName()), I);
4937 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4938 // Fold the known value into the constant operand.
4939 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4940 // Insert a new FCmp of the other select operand.
4941 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4942 LHSI->getOperand(1), RHSC,
4943 I.getName()), I);
4944 }
4945 }
4946
4947 if (Op1)
4948 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4949 break;
4950 }
4951 }
4952
4953 return Changed ? &I : 0;
4954}
4955
4956Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
4957 bool Changed = SimplifyCompare(I);
4958 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4959 const Type *Ty = Op0->getType();
4960
4961 // icmp X, X
4962 if (Op0 == Op1)
Reid Spencer579dca12007-01-12 04:24:46 +00004963 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4964 isTrueWhenEqual(I)));
Reid Spencere4d87aa2006-12-23 06:05:41 +00004965
4966 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Reid Spencer4fe16d62007-01-11 18:21:29 +00004967 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Christopher Lamb7a0678c2007-12-18 21:32:20 +00004968
Reid Spencere4d87aa2006-12-23 06:05:41 +00004969 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner711b3402004-11-14 07:33:16 +00004970 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanfd939082005-04-21 23:48:37 +00004971 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
4972 isa<ConstantPointerNull>(Op0)) &&
4973 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner711b3402004-11-14 07:33:16 +00004974 isa<ConstantPointerNull>(Op1)))
Reid Spencer579dca12007-01-12 04:24:46 +00004975 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4976 !isTrueWhenEqual(I)));
Chris Lattner8b170942002-08-09 23:47:40 +00004977
Reid Spencere4d87aa2006-12-23 06:05:41 +00004978 // icmp's with boolean values can always be turned into bitwise operations
Reid Spencer4fe16d62007-01-11 18:21:29 +00004979 if (Ty == Type::Int1Ty) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00004980 switch (I.getPredicate()) {
4981 default: assert(0 && "Invalid icmp instruction!");
4982 case ICmpInst::ICMP_EQ: { // icmp eq bool %A, %B -> ~(A^B)
Chris Lattner48595f12004-06-10 02:07:29 +00004983 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner8b170942002-08-09 23:47:40 +00004984 InsertNewInstBefore(Xor, I);
Chris Lattnerde90b762003-11-03 04:25:02 +00004985 return BinaryOperator::createNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00004986 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004987 case ICmpInst::ICMP_NE: // icmp eq bool %A, %B -> A^B
Chris Lattner5dbef222004-08-11 00:50:51 +00004988 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00004989
Reid Spencere4d87aa2006-12-23 06:05:41 +00004990 case ICmpInst::ICMP_UGT:
4991 case ICmpInst::ICMP_SGT:
4992 std::swap(Op0, Op1); // Change icmp gt -> icmp lt
Chris Lattner5dbef222004-08-11 00:50:51 +00004993 // FALL THROUGH
Reid Spencere4d87aa2006-12-23 06:05:41 +00004994 case ICmpInst::ICMP_ULT:
4995 case ICmpInst::ICMP_SLT: { // icmp lt bool A, B -> ~X & Y
Chris Lattner5dbef222004-08-11 00:50:51 +00004996 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4997 InsertNewInstBefore(Not, I);
4998 return BinaryOperator::createAnd(Not, Op1);
4999 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00005000 case ICmpInst::ICMP_UGE:
5001 case ICmpInst::ICMP_SGE:
5002 std::swap(Op0, Op1); // Change icmp ge -> icmp le
Chris Lattner5dbef222004-08-11 00:50:51 +00005003 // FALL THROUGH
Reid Spencere4d87aa2006-12-23 06:05:41 +00005004 case ICmpInst::ICMP_ULE:
5005 case ICmpInst::ICMP_SLE: { // icmp le bool %A, %B -> ~A | B
Chris Lattner5dbef222004-08-11 00:50:51 +00005006 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
5007 InsertNewInstBefore(Not, I);
5008 return BinaryOperator::createOr(Not, Op1);
5009 }
5010 }
Chris Lattner8b170942002-08-09 23:47:40 +00005011 }
5012
Chris Lattner2be51ae2004-06-09 04:24:29 +00005013 // See if we are doing a comparison between a constant and an instruction that
5014 // can be folded into the comparison.
Chris Lattner8b170942002-08-09 23:47:40 +00005015 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Christopher Lamb103e1a32007-12-20 07:21:11 +00005016 Value *A, *B;
5017
Chris Lattnerb6566012008-01-05 01:18:20 +00005018 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5019 if (I.isEquality() && CI->isNullValue() &&
5020 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
5021 // (icmp cond A B) if cond is equality
5022 return new ICmpInst(I.getPredicate(), A, B);
Owen Andersonf5783f82007-12-28 07:42:12 +00005023 }
Christopher Lamb103e1a32007-12-20 07:21:11 +00005024
Reid Spencere4d87aa2006-12-23 06:05:41 +00005025 switch (I.getPredicate()) {
5026 default: break;
5027 case ICmpInst::ICMP_ULT: // A <u MIN -> FALSE
5028 if (CI->isMinValue(false))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005029 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005030 if (CI->isMaxValue(false)) // A <u MAX -> A != MAX
5031 return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
5032 if (isMinValuePlusOne(CI,false)) // A <u MIN+1 -> A == MIN
5033 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
Chris Lattnerba417832007-04-11 06:12:58 +00005034 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
5035 if (CI->isMinValue(true))
5036 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
5037 ConstantInt::getAllOnesValue(Op0->getType()));
5038
Reid Spencere4d87aa2006-12-23 06:05:41 +00005039 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005040
Reid Spencere4d87aa2006-12-23 06:05:41 +00005041 case ICmpInst::ICMP_SLT:
5042 if (CI->isMinValue(true)) // A <s MIN -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005043 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005044 if (CI->isMaxValue(true)) // A <s MAX -> A != MAX
5045 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5046 if (isMinValuePlusOne(CI,true)) // A <s MIN+1 -> A == MIN
5047 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5048 break;
5049
5050 case ICmpInst::ICMP_UGT:
5051 if (CI->isMaxValue(false)) // A >u MAX -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005052 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005053 if (CI->isMinValue(false)) // A >u MIN -> A != MIN
5054 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5055 if (isMaxValueMinusOne(CI, false)) // A >u MAX-1 -> A == MAX
5056 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
Chris Lattnerba417832007-04-11 06:12:58 +00005057
5058 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
5059 if (CI->isMaxValue(true))
5060 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
5061 ConstantInt::getNullValue(Op0->getType()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00005062 break;
5063
5064 case ICmpInst::ICMP_SGT:
5065 if (CI->isMaxValue(true)) // A >s MAX -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005066 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005067 if (CI->isMinValue(true)) // A >s MIN -> A != MIN
5068 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5069 if (isMaxValueMinusOne(CI, true)) // A >s MAX-1 -> A == MAX
5070 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5071 break;
5072
5073 case ICmpInst::ICMP_ULE:
5074 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005075 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005076 if (CI->isMinValue(false)) // A <=u MIN -> A == MIN
5077 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5078 if (isMaxValueMinusOne(CI,false)) // A <=u MAX-1 -> A != MAX
5079 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5080 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005081
Reid Spencere4d87aa2006-12-23 06:05:41 +00005082 case ICmpInst::ICMP_SLE:
5083 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005084 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005085 if (CI->isMinValue(true)) // A <=s MIN -> A == MIN
5086 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5087 if (isMaxValueMinusOne(CI,true)) // A <=s MAX-1 -> A != MAX
5088 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5089 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005090
Reid Spencere4d87aa2006-12-23 06:05:41 +00005091 case ICmpInst::ICMP_UGE:
5092 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005093 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005094 if (CI->isMaxValue(false)) // A >=u MAX -> A == MAX
5095 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5096 if (isMinValuePlusOne(CI,false)) // A >=u MIN-1 -> A != MIN
5097 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5098 break;
5099
5100 case ICmpInst::ICMP_SGE:
5101 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005102 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005103 if (CI->isMaxValue(true)) // A >=s MAX -> A == MAX
5104 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5105 if (isMinValuePlusOne(CI,true)) // A >=s MIN-1 -> A != MIN
5106 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5107 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005108 }
5109
Reid Spencere4d87aa2006-12-23 06:05:41 +00005110 // If we still have a icmp le or icmp ge instruction, turn it into the
5111 // appropriate icmp lt or icmp gt instruction. Since the border cases have
Chris Lattnera96879a2004-09-29 17:40:11 +00005112 // already been handled above, this requires little checking.
5113 //
Reid Spencer2149a9d2007-03-25 19:55:33 +00005114 switch (I.getPredicate()) {
Chris Lattner4241e4d2007-07-15 20:54:51 +00005115 default: break;
5116 case ICmpInst::ICMP_ULE:
5117 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5118 case ICmpInst::ICMP_SLE:
5119 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5120 case ICmpInst::ICMP_UGE:
5121 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5122 case ICmpInst::ICMP_SGE:
5123 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
Reid Spencer2149a9d2007-03-25 19:55:33 +00005124 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005125
5126 // See if we can fold the comparison based on bits known to be zero or one
Chris Lattner4241e4d2007-07-15 20:54:51 +00005127 // in the input. If this comparison is a normal comparison, it demands all
5128 // bits, if it is a sign bit comparison, it only demands the sign bit.
5129
5130 bool UnusedBit;
5131 bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5132
Reid Spencer0460fb32007-03-22 20:36:03 +00005133 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
5134 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
Chris Lattner4241e4d2007-07-15 20:54:51 +00005135 if (SimplifyDemandedBits(Op0,
5136 isSignBit ? APInt::getSignBit(BitWidth)
5137 : APInt::getAllOnesValue(BitWidth),
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005138 KnownZero, KnownOne, 0))
5139 return &I;
5140
5141 // Given the known and unknown bits, compute a range that the LHS could be
5142 // in.
Reid Spencer0460fb32007-03-22 20:36:03 +00005143 if ((KnownOne | KnownZero) != 0) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005144 // Compute the Min, Max and RHS values based on the known bits. For the
5145 // EQ and NE we use unsigned values.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00005146 APInt Min(BitWidth, 0), Max(BitWidth, 0);
5147 const APInt& RHSVal = CI->getValue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00005148 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
Reid Spencer0460fb32007-03-22 20:36:03 +00005149 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
5150 Max);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005151 } else {
Reid Spencer0460fb32007-03-22 20:36:03 +00005152 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
5153 Max);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005154 }
5155 switch (I.getPredicate()) { // LE/GE have been folded already.
5156 default: assert(0 && "Unknown icmp opcode!");
5157 case ICmpInst::ICMP_EQ:
Reid Spencer0460fb32007-03-22 20:36:03 +00005158 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005159 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005160 break;
5161 case ICmpInst::ICMP_NE:
Reid Spencer0460fb32007-03-22 20:36:03 +00005162 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005163 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005164 break;
5165 case ICmpInst::ICMP_ULT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005166 if (Max.ult(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005167 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00005168 if (Min.uge(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005169 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005170 break;
5171 case ICmpInst::ICMP_UGT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005172 if (Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005173 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00005174 if (Max.ule(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005175 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005176 break;
5177 case ICmpInst::ICMP_SLT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005178 if (Max.slt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005179 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer0460fb32007-03-22 20:36:03 +00005180 if (Min.sgt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005181 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005182 break;
5183 case ICmpInst::ICMP_SGT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005184 if (Min.sgt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005185 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00005186 if (Max.sle(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005187 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005188 break;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005189 }
5190 }
5191
Reid Spencere4d87aa2006-12-23 06:05:41 +00005192 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer1628cec2006-10-26 06:15:43 +00005193 // instruction, see if that instruction also has constants so that the
Reid Spencere4d87aa2006-12-23 06:05:41 +00005194 // instruction can be folded into the icmp
Chris Lattner3c6a0d42004-05-25 06:32:08 +00005195 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner01deb9d2007-04-03 17:43:25 +00005196 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
5197 return Res;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005198 }
5199
Chris Lattner01deb9d2007-04-03 17:43:25 +00005200 // Handle icmp with constant (but not simple integer constant) RHS
Chris Lattner6970b662005-04-23 15:31:55 +00005201 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5202 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5203 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00005204 case Instruction::GetElementPtr:
5205 if (RHSC->isNullValue()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005206 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattner9fb25db2005-05-01 04:42:15 +00005207 bool isAllZeros = true;
5208 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5209 if (!isa<Constant>(LHSI->getOperand(i)) ||
5210 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5211 isAllZeros = false;
5212 break;
5213 }
5214 if (isAllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005215 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Chris Lattner9fb25db2005-05-01 04:42:15 +00005216 Constant::getNullValue(LHSI->getOperand(0)->getType()));
5217 }
5218 break;
5219
Chris Lattner6970b662005-04-23 15:31:55 +00005220 case Instruction::PHI:
5221 if (Instruction *NV = FoldOpIntoPhi(I))
5222 return NV;
5223 break;
Chris Lattner4802d902007-04-06 18:57:34 +00005224 case Instruction::Select: {
Chris Lattner6970b662005-04-23 15:31:55 +00005225 // If either operand of the select is a constant, we can fold the
5226 // comparison into the select arms, which will cause one to be
5227 // constant folded and the select turned into a bitwise or.
5228 Value *Op1 = 0, *Op2 = 0;
5229 if (LHSI->hasOneUse()) {
5230 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5231 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005232 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5233 // Insert a new ICmp of the other select operand.
5234 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5235 LHSI->getOperand(2), RHSC,
5236 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00005237 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5238 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005239 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5240 // Insert a new ICmp of the other select operand.
5241 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5242 LHSI->getOperand(1), RHSC,
5243 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00005244 }
5245 }
Jeff Cohen9d809302005-04-23 21:38:35 +00005246
Chris Lattner6970b662005-04-23 15:31:55 +00005247 if (Op1)
5248 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
5249 break;
5250 }
Chris Lattner4802d902007-04-06 18:57:34 +00005251 case Instruction::Malloc:
5252 // If we have (malloc != null), and if the malloc has a single use, we
5253 // can assume it is successful and remove the malloc.
5254 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
5255 AddToWorkList(LHSI);
5256 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5257 !isTrueWhenEqual(I)));
5258 }
5259 break;
5260 }
Chris Lattner6970b662005-04-23 15:31:55 +00005261 }
5262
Reid Spencere4d87aa2006-12-23 06:05:41 +00005263 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Chris Lattner574da9b2005-01-13 20:14:25 +00005264 if (User *GEP = dyn_castGetElementPtr(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005265 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00005266 return NI;
5267 if (User *GEP = dyn_castGetElementPtr(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005268 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5269 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00005270 return NI;
5271
Reid Spencere4d87aa2006-12-23 06:05:41 +00005272 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner57d86372007-01-06 01:45:59 +00005273 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
5274 // now.
5275 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5276 if (isa<PointerType>(Op0->getType()) &&
5277 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattnerde90b762003-11-03 04:25:02 +00005278 // We keep moving the cast from the left operand over to the right
5279 // operand, where it can often be eliminated completely.
Chris Lattner57d86372007-01-06 01:45:59 +00005280 Op0 = CI->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00005281
Chris Lattner57d86372007-01-06 01:45:59 +00005282 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5283 // so eliminate it as well.
5284 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5285 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00005286
Chris Lattnerde90b762003-11-03 04:25:02 +00005287 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005288 if (Op0->getType() != Op1->getType()) {
Chris Lattnerde90b762003-11-03 04:25:02 +00005289 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Reid Spencerd977d862006-12-12 23:36:14 +00005290 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00005291 } else {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005292 // Otherwise, cast the RHS right before the icmp
Chris Lattner6d0339d2008-01-13 22:23:22 +00005293 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
Chris Lattnerde90b762003-11-03 04:25:02 +00005294 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005295 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00005296 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattnerde90b762003-11-03 04:25:02 +00005297 }
Chris Lattner57d86372007-01-06 01:45:59 +00005298 }
5299
5300 if (isa<CastInst>(Op0)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005301 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner68708052003-11-03 05:17:03 +00005302 // This comes up when you have code like
5303 // int X = A < B;
5304 // if (X) ...
5305 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00005306 // with a constant or another cast from the same type.
5307 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005308 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattner484d3cf2005-04-24 06:59:08 +00005309 return R;
Chris Lattner68708052003-11-03 05:17:03 +00005310 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00005311
Chris Lattner65b72ba2006-09-18 04:22:48 +00005312 if (I.isEquality()) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005313 Value *A, *B, *C, *D;
5314 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
5315 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
5316 Value *OtherVal = A == Op1 ? B : A;
5317 return new ICmpInst(I.getPredicate(), OtherVal,
5318 Constant::getNullValue(A->getType()));
5319 }
5320
5321 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5322 // A^c1 == C^c2 --> A == C^(c1^c2)
5323 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
5324 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
5325 if (Op1->hasOneUse()) {
Zhou Sheng4a1822a2007-04-02 13:45:30 +00005326 Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005327 Instruction *Xor = BinaryOperator::createXor(C, NC, "tmp");
5328 return new ICmpInst(I.getPredicate(), A,
5329 InsertNewInstBefore(Xor, I));
5330 }
5331
5332 // A^B == A^D -> B == D
5333 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
5334 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
5335 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
5336 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
5337 }
5338 }
5339
5340 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5341 (A == Op0 || B == Op0)) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00005342 // A == (A^B) -> B == 0
5343 Value *OtherVal = A == Op0 ? B : A;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005344 return new ICmpInst(I.getPredicate(), OtherVal,
5345 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005346 }
5347 if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00005348 // (A-B) == A -> B == 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00005349 return new ICmpInst(I.getPredicate(), B,
5350 Constant::getNullValue(B->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005351 }
5352 if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00005353 // A == (A-B) -> B == 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00005354 return new ICmpInst(I.getPredicate(), B,
5355 Constant::getNullValue(B->getType()));
Chris Lattner26ab9a92006-02-27 01:44:11 +00005356 }
Chris Lattner9c2328e2006-11-14 06:06:06 +00005357
Chris Lattner9c2328e2006-11-14 06:06:06 +00005358 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5359 if (Op0->hasOneUse() && Op1->hasOneUse() &&
5360 match(Op0, m_And(m_Value(A), m_Value(B))) &&
5361 match(Op1, m_And(m_Value(C), m_Value(D)))) {
5362 Value *X = 0, *Y = 0, *Z = 0;
5363
5364 if (A == C) {
5365 X = B; Y = D; Z = A;
5366 } else if (A == D) {
5367 X = B; Y = C; Z = A;
5368 } else if (B == C) {
5369 X = A; Y = D; Z = B;
5370 } else if (B == D) {
5371 X = A; Y = C; Z = B;
5372 }
5373
5374 if (X) { // Build (X^Y) & Z
5375 Op1 = InsertNewInstBefore(BinaryOperator::createXor(X, Y, "tmp"), I);
5376 Op1 = InsertNewInstBefore(BinaryOperator::createAnd(Op1, Z, "tmp"), I);
5377 I.setOperand(0, Op1);
5378 I.setOperand(1, Constant::getNullValue(Op1->getType()));
5379 return &I;
5380 }
5381 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00005382 }
Chris Lattner7e708292002-06-25 16:13:24 +00005383 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005384}
5385
Chris Lattner562ef782007-06-20 23:46:26 +00005386
5387/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
5388/// and CmpRHS are both known to be integer constants.
5389Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
5390 ConstantInt *DivRHS) {
5391 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
5392 const APInt &CmpRHSV = CmpRHS->getValue();
5393
5394 // FIXME: If the operand types don't match the type of the divide
5395 // then don't attempt this transform. The code below doesn't have the
5396 // logic to deal with a signed divide and an unsigned compare (and
5397 // vice versa). This is because (x /s C1) <s C2 produces different
5398 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
5399 // (x /u C1) <u C2. Simply casting the operands and result won't
5400 // work. :( The if statement below tests that condition and bails
5401 // if it finds it.
5402 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
5403 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
5404 return 0;
5405 if (DivRHS->isZero())
Chris Lattner1dbfd482007-06-21 18:11:19 +00005406 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattner562ef782007-06-20 23:46:26 +00005407
5408 // Compute Prod = CI * DivRHS. We are essentially solving an equation
5409 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
5410 // C2 (CI). By solving for X we can turn this into a range check
5411 // instead of computing a divide.
5412 ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
5413
5414 // Determine if the product overflows by seeing if the product is
5415 // not equal to the divide. Make sure we do the same kind of divide
5416 // as in the LHS instruction that we're folding.
5417 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
5418 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
5419
5420 // Get the ICmp opcode
Chris Lattner1dbfd482007-06-21 18:11:19 +00005421 ICmpInst::Predicate Pred = ICI.getPredicate();
Chris Lattner562ef782007-06-20 23:46:26 +00005422
Chris Lattner1dbfd482007-06-21 18:11:19 +00005423 // Figure out the interval that is being checked. For example, a comparison
5424 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
5425 // Compute this interval based on the constants involved and the signedness of
5426 // the compare/divide. This computes a half-open interval, keeping track of
5427 // whether either value in the interval overflows. After analysis each
5428 // overflow variable is set to 0 if it's corresponding bound variable is valid
5429 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
5430 int LoOverflow = 0, HiOverflow = 0;
5431 ConstantInt *LoBound = 0, *HiBound = 0;
5432
5433
Chris Lattner562ef782007-06-20 23:46:26 +00005434 if (!DivIsSigned) { // udiv
Chris Lattner1dbfd482007-06-21 18:11:19 +00005435 // e.g. X/5 op 3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00005436 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00005437 HiOverflow = LoOverflow = ProdOV;
5438 if (!HiOverflow)
5439 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
Dan Gohman76491272008-02-13 22:09:18 +00005440 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Chris Lattner562ef782007-06-20 23:46:26 +00005441 if (CmpRHSV == 0) { // (X / pos) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00005442 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Chris Lattner562ef782007-06-20 23:46:26 +00005443 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
5444 HiBound = DivRHS;
Dan Gohman76491272008-02-13 22:09:18 +00005445 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00005446 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
5447 HiOverflow = LoOverflow = ProdOV;
5448 if (!HiOverflow)
5449 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
Chris Lattner562ef782007-06-20 23:46:26 +00005450 } else { // (X / pos) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00005451 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Chris Lattner562ef782007-06-20 23:46:26 +00005452 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
5453 LoOverflow = AddWithOverflow(LoBound, Prod,
Chris Lattner1dbfd482007-06-21 18:11:19 +00005454 cast<ConstantInt>(DivRHSH), true) ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005455 HiBound = AddOne(Prod);
Chris Lattner1dbfd482007-06-21 18:11:19 +00005456 HiOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005457 }
Dan Gohman76491272008-02-13 22:09:18 +00005458 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Chris Lattner562ef782007-06-20 23:46:26 +00005459 if (CmpRHSV == 0) { // (X / neg) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00005460 // e.g. X/-5 op 0 --> [-4, 5)
Chris Lattner562ef782007-06-20 23:46:26 +00005461 LoBound = AddOne(DivRHS);
5462 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner1dbfd482007-06-21 18:11:19 +00005463 if (HiBound == DivRHS) { // -INTMIN = INTMIN
5464 HiOverflow = 1; // [INTMIN+1, overflow)
5465 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
5466 }
Dan Gohman76491272008-02-13 22:09:18 +00005467 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00005468 // e.g. X/-5 op 3 --> [-19, -14)
5469 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005470 if (!LoOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00005471 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS), true) ?-1:0;
Chris Lattner562ef782007-06-20 23:46:26 +00005472 HiBound = AddOne(Prod);
5473 } else { // (X / neg) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00005474 // e.g. X/-5 op -3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00005475 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00005476 LoOverflow = HiOverflow = ProdOV ? 1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005477 HiBound = Subtract(Prod, DivRHS);
5478 }
5479
Chris Lattner1dbfd482007-06-21 18:11:19 +00005480 // Dividing by a negative swaps the condition. LT <-> GT
5481 Pred = ICmpInst::getSwappedPredicate(Pred);
Chris Lattner562ef782007-06-20 23:46:26 +00005482 }
5483
5484 Value *X = DivI->getOperand(0);
Chris Lattner1dbfd482007-06-21 18:11:19 +00005485 switch (Pred) {
Chris Lattner562ef782007-06-20 23:46:26 +00005486 default: assert(0 && "Unhandled icmp opcode!");
5487 case ICmpInst::ICMP_EQ:
5488 if (LoOverflow && HiOverflow)
5489 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5490 else if (HiOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00005491 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00005492 ICmpInst::ICMP_UGE, X, LoBound);
5493 else if (LoOverflow)
5494 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
5495 ICmpInst::ICMP_ULT, X, HiBound);
5496 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00005497 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00005498 case ICmpInst::ICMP_NE:
5499 if (LoOverflow && HiOverflow)
5500 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5501 else if (HiOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00005502 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00005503 ICmpInst::ICMP_ULT, X, LoBound);
5504 else if (LoOverflow)
5505 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
5506 ICmpInst::ICMP_UGE, X, HiBound);
5507 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00005508 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00005509 case ICmpInst::ICMP_ULT:
5510 case ICmpInst::ICMP_SLT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00005511 if (LoOverflow == +1) // Low bound is greater than input range.
5512 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5513 if (LoOverflow == -1) // Low bound is less than input range.
Chris Lattner562ef782007-06-20 23:46:26 +00005514 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00005515 return new ICmpInst(Pred, X, LoBound);
Chris Lattner562ef782007-06-20 23:46:26 +00005516 case ICmpInst::ICMP_UGT:
5517 case ICmpInst::ICMP_SGT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00005518 if (HiOverflow == +1) // High bound greater than input range.
Chris Lattner562ef782007-06-20 23:46:26 +00005519 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00005520 else if (HiOverflow == -1) // High bound less than input range.
5521 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5522 if (Pred == ICmpInst::ICMP_UGT)
Chris Lattner562ef782007-06-20 23:46:26 +00005523 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
5524 else
5525 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
5526 }
5527}
5528
5529
Chris Lattner01deb9d2007-04-03 17:43:25 +00005530/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
5531///
5532Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
5533 Instruction *LHSI,
5534 ConstantInt *RHS) {
5535 const APInt &RHSV = RHS->getValue();
5536
5537 switch (LHSI->getOpcode()) {
Duncan Sands0091bf22007-04-04 06:42:45 +00005538 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
Chris Lattner01deb9d2007-04-03 17:43:25 +00005539 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
5540 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
5541 // fold the xor.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005542 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
5543 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00005544 Value *CompareVal = LHSI->getOperand(0);
5545
5546 // If the sign bit of the XorCST is not set, there is no change to
5547 // the operation, just stop using the Xor.
5548 if (!XorCST->getValue().isNegative()) {
5549 ICI.setOperand(0, CompareVal);
5550 AddToWorkList(LHSI);
5551 return &ICI;
5552 }
5553
5554 // Was the old condition true if the operand is positive?
5555 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
5556
5557 // If so, the new one isn't.
5558 isTrueIfPositive ^= true;
5559
5560 if (isTrueIfPositive)
5561 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
5562 else
5563 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
5564 }
5565 }
5566 break;
5567 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
5568 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
5569 LHSI->getOperand(0)->hasOneUse()) {
5570 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
5571
5572 // If the LHS is an AND of a truncating cast, we can widen the
5573 // and/compare to be the input width without changing the value
5574 // produced, eliminating a cast.
5575 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
5576 // We can do this transformation if either the AND constant does not
5577 // have its sign bit set or if it is an equality comparison.
5578 // Extending a relational comparison when we're checking the sign
5579 // bit would not work.
5580 if (Cast->hasOneUse() &&
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00005581 (ICI.isEquality() ||
5582 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00005583 uint32_t BitWidth =
5584 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
5585 APInt NewCST = AndCST->getValue();
5586 NewCST.zext(BitWidth);
5587 APInt NewCI = RHSV;
5588 NewCI.zext(BitWidth);
5589 Instruction *NewAnd =
5590 BinaryOperator::createAnd(Cast->getOperand(0),
5591 ConstantInt::get(NewCST),LHSI->getName());
5592 InsertNewInstBefore(NewAnd, ICI);
5593 return new ICmpInst(ICI.getPredicate(), NewAnd,
5594 ConstantInt::get(NewCI));
5595 }
5596 }
5597
5598 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
5599 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
5600 // happens a LOT in code produced by the C front-end, for bitfield
5601 // access.
5602 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
5603 if (Shift && !Shift->isShift())
5604 Shift = 0;
5605
5606 ConstantInt *ShAmt;
5607 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
5608 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
5609 const Type *AndTy = AndCST->getType(); // Type of the and.
5610
5611 // We can fold this as long as we can't shift unknown bits
5612 // into the mask. This can only happen with signed shift
5613 // rights, as they sign-extend.
5614 if (ShAmt) {
5615 bool CanFold = Shift->isLogicalShift();
5616 if (!CanFold) {
5617 // To test for the bad case of the signed shr, see if any
5618 // of the bits shifted in could be tested after the mask.
5619 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
5620 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
5621
5622 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
5623 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
5624 AndCST->getValue()) == 0)
5625 CanFold = true;
5626 }
5627
5628 if (CanFold) {
5629 Constant *NewCst;
5630 if (Shift->getOpcode() == Instruction::Shl)
5631 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
5632 else
5633 NewCst = ConstantExpr::getShl(RHS, ShAmt);
5634
5635 // Check to see if we are shifting out any of the bits being
5636 // compared.
5637 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
5638 // If we shifted bits out, the fold is not going to work out.
5639 // As a special case, check to see if this means that the
5640 // result is always true or false now.
5641 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
5642 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5643 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
5644 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5645 } else {
5646 ICI.setOperand(1, NewCst);
5647 Constant *NewAndCST;
5648 if (Shift->getOpcode() == Instruction::Shl)
5649 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
5650 else
5651 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
5652 LHSI->setOperand(1, NewAndCST);
5653 LHSI->setOperand(0, Shift->getOperand(0));
5654 AddToWorkList(Shift); // Shift is dead.
5655 AddUsesToWorkList(ICI);
5656 return &ICI;
5657 }
5658 }
5659 }
5660
5661 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
5662 // preferable because it allows the C<<Y expression to be hoisted out
5663 // of a loop if Y is invariant and X is not.
5664 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
5665 ICI.isEquality() && !Shift->isArithmeticShift() &&
5666 isa<Instruction>(Shift->getOperand(0))) {
5667 // Compute C << Y.
5668 Value *NS;
5669 if (Shift->getOpcode() == Instruction::LShr) {
5670 NS = BinaryOperator::createShl(AndCST,
5671 Shift->getOperand(1), "tmp");
5672 } else {
5673 // Insert a logical shift.
5674 NS = BinaryOperator::createLShr(AndCST,
5675 Shift->getOperand(1), "tmp");
5676 }
5677 InsertNewInstBefore(cast<Instruction>(NS), ICI);
5678
5679 // Compute X & (C << Y).
5680 Instruction *NewAnd =
5681 BinaryOperator::createAnd(Shift->getOperand(0), NS, LHSI->getName());
5682 InsertNewInstBefore(NewAnd, ICI);
5683
5684 ICI.setOperand(0, NewAnd);
5685 return &ICI;
5686 }
5687 }
5688 break;
5689
Chris Lattnera0141b92007-07-15 20:42:37 +00005690 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
5691 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5692 if (!ShAmt) break;
5693
5694 uint32_t TypeBits = RHSV.getBitWidth();
5695
5696 // Check that the shift amount is in range. If not, don't perform
5697 // undefined shifts. When the shift is visited it will be
5698 // simplified.
5699 if (ShAmt->uge(TypeBits))
5700 break;
5701
5702 if (ICI.isEquality()) {
5703 // If we are comparing against bits always shifted out, the
5704 // comparison cannot succeed.
5705 Constant *Comp =
5706 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
5707 if (Comp != RHS) {// Comparing against a bit that we know is zero.
5708 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5709 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5710 return ReplaceInstUsesWith(ICI, Cst);
5711 }
5712
5713 if (LHSI->hasOneUse()) {
5714 // Otherwise strength reduce the shift into an and.
5715 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
5716 Constant *Mask =
5717 ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
Chris Lattner01deb9d2007-04-03 17:43:25 +00005718
Chris Lattnera0141b92007-07-15 20:42:37 +00005719 Instruction *AndI =
5720 BinaryOperator::createAnd(LHSI->getOperand(0),
5721 Mask, LHSI->getName()+".mask");
5722 Value *And = InsertNewInstBefore(AndI, ICI);
5723 return new ICmpInst(ICI.getPredicate(), And,
5724 ConstantInt::get(RHSV.lshr(ShAmtVal)));
Chris Lattner01deb9d2007-04-03 17:43:25 +00005725 }
5726 }
Chris Lattnera0141b92007-07-15 20:42:37 +00005727
5728 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
5729 bool TrueIfSigned = false;
5730 if (LHSI->hasOneUse() &&
5731 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
5732 // (X << 31) <s 0 --> (X&1) != 0
5733 Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
5734 (TypeBits-ShAmt->getZExtValue()-1));
5735 Instruction *AndI =
5736 BinaryOperator::createAnd(LHSI->getOperand(0),
5737 Mask, LHSI->getName()+".mask");
5738 Value *And = InsertNewInstBefore(AndI, ICI);
5739
5740 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
5741 And, Constant::getNullValue(And->getType()));
5742 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00005743 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00005744 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00005745
5746 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Chris Lattnera0141b92007-07-15 20:42:37 +00005747 case Instruction::AShr: {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00005748 // Only handle equality comparisons of shift-by-constant.
Chris Lattnera0141b92007-07-15 20:42:37 +00005749 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00005750 if (!ShAmt || !ICI.isEquality()) break;
Chris Lattnera0141b92007-07-15 20:42:37 +00005751
Chris Lattner41dc0fc2008-03-21 05:19:58 +00005752 // Check that the shift amount is in range. If not, don't perform
5753 // undefined shifts. When the shift is visited it will be
5754 // simplified.
5755 uint32_t TypeBits = RHSV.getBitWidth();
5756 if (ShAmt->uge(TypeBits))
5757 break;
5758
5759 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattnera0141b92007-07-15 20:42:37 +00005760
Chris Lattner41dc0fc2008-03-21 05:19:58 +00005761 // If we are comparing against bits always shifted out, the
5762 // comparison cannot succeed.
5763 APInt Comp = RHSV << ShAmtVal;
5764 if (LHSI->getOpcode() == Instruction::LShr)
5765 Comp = Comp.lshr(ShAmtVal);
5766 else
5767 Comp = Comp.ashr(ShAmtVal);
5768
5769 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
5770 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5771 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5772 return ReplaceInstUsesWith(ICI, Cst);
5773 }
5774
5775 // Otherwise, check to see if the bits shifted out are known to be zero.
5776 // If so, we can compare against the unshifted value:
5777 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
5778 if (MaskedValueIsZero(LHSI->getOperand(0),
5779 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
5780 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
5781 ConstantExpr::getShl(RHS, ShAmt));
5782 }
Chris Lattnera0141b92007-07-15 20:42:37 +00005783
Chris Lattner41dc0fc2008-03-21 05:19:58 +00005784 if (LHSI->hasOneUse() || RHSV == 0) {
5785 // Otherwise strength reduce the shift into an and.
5786 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
5787 Constant *Mask = ConstantInt::get(Val);
Chris Lattnera0141b92007-07-15 20:42:37 +00005788
Chris Lattner41dc0fc2008-03-21 05:19:58 +00005789 Instruction *AndI =
5790 BinaryOperator::createAnd(LHSI->getOperand(0),
5791 Mask, LHSI->getName()+".mask");
5792 Value *And = InsertNewInstBefore(AndI, ICI);
5793 return new ICmpInst(ICI.getPredicate(), And,
5794 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner01deb9d2007-04-03 17:43:25 +00005795 }
5796 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00005797 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00005798
5799 case Instruction::SDiv:
5800 case Instruction::UDiv:
5801 // Fold: icmp pred ([us]div X, C1), C2 -> range test
5802 // Fold this div into the comparison, producing a range check.
5803 // Determine, based on the divide type, what the range is being
5804 // checked. If there is an overflow on the low or high side, remember
5805 // it, otherwise compute the range [low, hi) bounding the new value.
5806 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner562ef782007-06-20 23:46:26 +00005807 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
5808 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
5809 DivRHS))
5810 return R;
Chris Lattner01deb9d2007-04-03 17:43:25 +00005811 break;
Nick Lewycky5be29202008-02-03 16:33:09 +00005812
5813 case Instruction::Add:
5814 // Fold: icmp pred (add, X, C1), C2
5815
5816 if (!ICI.isEquality()) {
5817 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5818 if (!LHSC) break;
5819 const APInt &LHSV = LHSC->getValue();
5820
5821 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
5822 .subtract(LHSV);
5823
5824 if (ICI.isSignedPredicate()) {
5825 if (CR.getLower().isSignBit()) {
5826 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
5827 ConstantInt::get(CR.getUpper()));
5828 } else if (CR.getUpper().isSignBit()) {
5829 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
5830 ConstantInt::get(CR.getLower()));
5831 }
5832 } else {
5833 if (CR.getLower().isMinValue()) {
5834 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
5835 ConstantInt::get(CR.getUpper()));
5836 } else if (CR.getUpper().isMinValue()) {
5837 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
5838 ConstantInt::get(CR.getLower()));
5839 }
5840 }
5841 }
5842 break;
Chris Lattner01deb9d2007-04-03 17:43:25 +00005843 }
5844
5845 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
5846 if (ICI.isEquality()) {
5847 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5848
5849 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
5850 // the second operand is a constant, simplify a bit.
5851 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
5852 switch (BO->getOpcode()) {
5853 case Instruction::SRem:
5854 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
5855 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
5856 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
5857 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
5858 Instruction *NewRem =
5859 BinaryOperator::createURem(BO->getOperand(0), BO->getOperand(1),
5860 BO->getName());
5861 InsertNewInstBefore(NewRem, ICI);
5862 return new ICmpInst(ICI.getPredicate(), NewRem,
5863 Constant::getNullValue(BO->getType()));
5864 }
5865 }
5866 break;
5867 case Instruction::Add:
5868 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
5869 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
5870 if (BO->hasOneUse())
5871 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
5872 Subtract(RHS, BOp1C));
5873 } else if (RHSV == 0) {
5874 // Replace ((add A, B) != 0) with (A != -B) if A or B is
5875 // efficiently invertible, or if the add has just this one use.
5876 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
5877
5878 if (Value *NegVal = dyn_castNegVal(BOp1))
5879 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
5880 else if (Value *NegVal = dyn_castNegVal(BOp0))
5881 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
5882 else if (BO->hasOneUse()) {
5883 Instruction *Neg = BinaryOperator::createNeg(BOp1);
5884 InsertNewInstBefore(Neg, ICI);
5885 Neg->takeName(BO);
5886 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
5887 }
5888 }
5889 break;
5890 case Instruction::Xor:
5891 // For the xor case, we can xor two constants together, eliminating
5892 // the explicit xor.
5893 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
5894 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
5895 ConstantExpr::getXor(RHS, BOC));
5896
5897 // FALLTHROUGH
5898 case Instruction::Sub:
5899 // Replace (([sub|xor] A, B) != 0) with (A != B)
5900 if (RHSV == 0)
5901 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
5902 BO->getOperand(1));
5903 break;
5904
5905 case Instruction::Or:
5906 // If bits are being or'd in that are not present in the constant we
5907 // are comparing against, then the comparison could never succeed!
5908 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
5909 Constant *NotCI = ConstantExpr::getNot(RHS);
5910 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
5911 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
5912 isICMP_NE));
5913 }
5914 break;
5915
5916 case Instruction::And:
5917 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
5918 // If bits are being compared against that are and'd out, then the
5919 // comparison can never succeed!
5920 if ((RHSV & ~BOC->getValue()) != 0)
5921 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
5922 isICMP_NE));
5923
5924 // If we have ((X & C) == C), turn it into ((X & C) != 0).
5925 if (RHS == BOC && RHSV.isPowerOf2())
5926 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
5927 ICmpInst::ICMP_NE, LHSI,
5928 Constant::getNullValue(RHS->getType()));
5929
5930 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
5931 if (isSignBit(BOC)) {
5932 Value *X = BO->getOperand(0);
5933 Constant *Zero = Constant::getNullValue(X->getType());
5934 ICmpInst::Predicate pred = isICMP_NE ?
5935 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
5936 return new ICmpInst(pred, X, Zero);
5937 }
5938
5939 // ((X & ~7) == 0) --> X < 8
5940 if (RHSV == 0 && isHighOnes(BOC)) {
5941 Value *X = BO->getOperand(0);
5942 Constant *NegX = ConstantExpr::getNeg(BOC);
5943 ICmpInst::Predicate pred = isICMP_NE ?
5944 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
5945 return new ICmpInst(pred, X, NegX);
5946 }
5947 }
5948 default: break;
5949 }
5950 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
5951 // Handle icmp {eq|ne} <intrinsic>, intcst.
5952 if (II->getIntrinsicID() == Intrinsic::bswap) {
5953 AddToWorkList(II);
5954 ICI.setOperand(0, II->getOperand(1));
5955 ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
5956 return &ICI;
5957 }
5958 }
5959 } else { // Not a ICMP_EQ/ICMP_NE
Chris Lattnere34e9a22007-04-14 23:32:02 +00005960 // If the LHS is a cast from an integral value of the same size,
5961 // then since we know the RHS is a constant, try to simlify.
Chris Lattner01deb9d2007-04-03 17:43:25 +00005962 if (CastInst *Cast = dyn_cast<CastInst>(LHSI)) {
5963 Value *CastOp = Cast->getOperand(0);
5964 const Type *SrcTy = CastOp->getType();
5965 uint32_t SrcTySize = SrcTy->getPrimitiveSizeInBits();
5966 if (SrcTy->isInteger() &&
5967 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
5968 // If this is an unsigned comparison, try to make the comparison use
5969 // smaller constant values.
5970 if (ICI.getPredicate() == ICmpInst::ICMP_ULT && RHSV.isSignBit()) {
5971 // X u< 128 => X s> -1
5972 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp,
5973 ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
5974 } else if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
5975 RHSV == APInt::getSignedMaxValue(SrcTySize)) {
5976 // X u> 127 => X s< 0
5977 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp,
5978 Constant::getNullValue(SrcTy));
5979 }
5980 }
5981 }
5982 }
5983 return 0;
5984}
5985
5986/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
5987/// We only handle extending casts so far.
5988///
Reid Spencere4d87aa2006-12-23 06:05:41 +00005989Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
5990 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +00005991 Value *LHSCIOp = LHSCI->getOperand(0);
5992 const Type *SrcTy = LHSCIOp->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00005993 const Type *DestTy = LHSCI->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00005994 Value *RHSCIOp;
5995
Chris Lattner8c756c12007-05-05 22:41:33 +00005996 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
5997 // integer type is the same size as the pointer type.
5998 if (LHSCI->getOpcode() == Instruction::PtrToInt &&
5999 getTargetData().getPointerSizeInBits() ==
6000 cast<IntegerType>(DestTy)->getBitWidth()) {
6001 Value *RHSOp = 0;
6002 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Chris Lattner6f6f5122007-05-06 07:24:03 +00006003 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Chris Lattner8c756c12007-05-05 22:41:33 +00006004 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
6005 RHSOp = RHSC->getOperand(0);
6006 // If the pointer types don't match, insert a bitcast.
6007 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner6d0339d2008-01-13 22:23:22 +00006008 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
Chris Lattner8c756c12007-05-05 22:41:33 +00006009 }
6010
6011 if (RHSOp)
6012 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
6013 }
6014
6015 // The code below only handles extension cast instructions, so far.
6016 // Enforce this.
Reid Spencere4d87aa2006-12-23 06:05:41 +00006017 if (LHSCI->getOpcode() != Instruction::ZExt &&
6018 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattnerb352fa52005-01-17 03:20:02 +00006019 return 0;
6020
Reid Spencere4d87aa2006-12-23 06:05:41 +00006021 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
6022 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattner484d3cf2005-04-24 06:59:08 +00006023
Reid Spencere4d87aa2006-12-23 06:05:41 +00006024 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00006025 // Not an extension from the same type?
6026 RHSCIOp = CI->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006027 if (RHSCIOp->getType() != LHSCIOp->getType())
6028 return 0;
Chris Lattnera5c5e772007-01-13 23:11:38 +00006029
Nick Lewycky4189a532008-01-28 03:48:02 +00006030 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Chris Lattnera5c5e772007-01-13 23:11:38 +00006031 // and the other is a zext), then we can't handle this.
6032 if (CI->getOpcode() != LHSCI->getOpcode())
6033 return 0;
6034
Nick Lewycky4189a532008-01-28 03:48:02 +00006035 // Deal with equality cases early.
6036 if (ICI.isEquality())
6037 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6038
6039 // A signed comparison of sign extended values simplifies into a
6040 // signed comparison.
6041 if (isSignedCmp && isSignedExt)
6042 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6043
6044 // The other three cases all fold into an unsigned comparison.
6045 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer6731d5c2004-11-28 21:31:15 +00006046 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00006047
Reid Spencere4d87aa2006-12-23 06:05:41 +00006048 // If we aren't dealing with a constant on the RHS, exit early
6049 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
6050 if (!CI)
6051 return 0;
6052
6053 // Compute the constant that would happen if we truncated to SrcTy then
6054 // reextended to DestTy.
6055 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
6056 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
6057
6058 // If the re-extended constant didn't change...
6059 if (Res2 == CI) {
6060 // Make sure that sign of the Cmp and the sign of the Cast are the same.
6061 // For example, we might have:
6062 // %A = sext short %X to uint
6063 // %B = icmp ugt uint %A, 1330
6064 // It is incorrect to transform this into
6065 // %B = icmp ugt short %X, 1330
6066 // because %A may have negative value.
6067 //
6068 // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
6069 // OR operation is EQ/NE.
Reid Spencer4fe16d62007-01-11 18:21:29 +00006070 if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
Reid Spencere4d87aa2006-12-23 06:05:41 +00006071 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
6072 else
6073 return 0;
6074 }
6075
6076 // The re-extended constant changed so the constant cannot be represented
6077 // in the shorter type. Consequently, we cannot emit a simple comparison.
6078
6079 // First, handle some easy cases. We know the result cannot be equal at this
6080 // point so handle the ICI.isEquality() cases
6081 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006082 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006083 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006084 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006085
6086 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
6087 // should have been folded away previously and not enter in here.
6088 Value *Result;
6089 if (isSignedCmp) {
6090 // We're performing a signed comparison.
Reid Spencer0460fb32007-03-22 20:36:03 +00006091 if (cast<ConstantInt>(CI)->getValue().isNegative())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006092 Result = ConstantInt::getFalse(); // X < (small) --> false
Reid Spencere4d87aa2006-12-23 06:05:41 +00006093 else
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006094 Result = ConstantInt::getTrue(); // X < (large) --> true
Reid Spencere4d87aa2006-12-23 06:05:41 +00006095 } else {
6096 // We're performing an unsigned comparison.
6097 if (isSignedExt) {
6098 // We're performing an unsigned comp with a sign extended value.
6099 // This is true if the input is >= 0. [aka >s -1]
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006100 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006101 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
6102 NegOne, ICI.getName()), ICI);
6103 } else {
6104 // Unsigned extend & unsigned compare -> always true.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006105 Result = ConstantInt::getTrue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00006106 }
6107 }
6108
6109 // Finally, return the value computed.
6110 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
6111 ICI.getPredicate() == ICmpInst::ICMP_SLT) {
6112 return ReplaceInstUsesWith(ICI, Result);
6113 } else {
6114 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
6115 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
6116 "ICmp should be folded!");
6117 if (Constant *CI = dyn_cast<Constant>(Result))
6118 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
6119 else
6120 return BinaryOperator::createNot(Result);
6121 }
Chris Lattner484d3cf2005-04-24 06:59:08 +00006122}
Chris Lattner3f5b8772002-05-06 16:14:14 +00006123
Reid Spencer832254e2007-02-02 02:16:23 +00006124Instruction *InstCombiner::visitShl(BinaryOperator &I) {
6125 return commonShiftTransforms(I);
6126}
6127
6128Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
6129 return commonShiftTransforms(I);
6130}
6131
6132Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner348f6652007-12-06 01:59:46 +00006133 if (Instruction *R = commonShiftTransforms(I))
6134 return R;
6135
6136 Value *Op0 = I.getOperand(0);
6137
6138 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
6139 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
6140 if (CSI->isAllOnesValue())
6141 return ReplaceInstUsesWith(I, CSI);
6142
6143 // See if we can turn a signed shr into an unsigned shr.
6144 if (MaskedValueIsZero(Op0,
6145 APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
6146 return BinaryOperator::createLShr(Op0, I.getOperand(1));
6147
6148 return 0;
Reid Spencer832254e2007-02-02 02:16:23 +00006149}
6150
6151Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
6152 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00006153 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00006154
6155 // shl X, 0 == X and shr X, 0 == X
6156 // shl 0, X == 0 and shr 0, X == 0
Reid Spencer832254e2007-02-02 02:16:23 +00006157 if (Op1 == Constant::getNullValue(Op1->getType()) ||
Chris Lattner233f7dc2002-08-12 21:17:25 +00006158 Op0 == Constant::getNullValue(Op0->getType()))
6159 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006160
Reid Spencere4d87aa2006-12-23 06:05:41 +00006161 if (isa<UndefValue>(Op0)) {
6162 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00006163 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006164 else // undef << X -> 0, undef >>u X -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00006165 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6166 }
6167 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006168 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
6169 return ReplaceInstUsesWith(I, Op0);
6170 else // X << undef, X >>u undef -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00006171 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00006172 }
6173
Chris Lattner2eefe512004-04-09 19:05:30 +00006174 // Try to fold constant and into select arguments.
6175 if (isa<Constant>(Op0))
6176 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00006177 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00006178 return R;
6179
Reid Spencerb83eb642006-10-20 07:07:24 +00006180 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00006181 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
6182 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006183 return 0;
6184}
6185
Reid Spencerb83eb642006-10-20 07:07:24 +00006186Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00006187 BinaryOperator &I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006188 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006189
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006190 // See if we can simplify any instructions used by the instruction whose sole
6191 // purpose is to compute bits we don't care about.
Reid Spencerb35ae032007-03-23 18:46:34 +00006192 uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
6193 APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
6194 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006195 KnownZero, KnownOne))
6196 return &I;
6197
Chris Lattner4d5542c2006-01-06 07:12:35 +00006198 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
6199 // of a signed value.
6200 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00006201 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00006202 if (I.getOpcode() != Instruction::AShr)
Chris Lattner4d5542c2006-01-06 07:12:35 +00006203 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
6204 else {
Chris Lattner0737c242007-02-02 05:29:55 +00006205 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00006206 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00006207 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006208 }
6209
6210 // ((X*C1) << C2) == (X * (C1 << C2))
6211 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
6212 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
6213 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
6214 return BinaryOperator::createMul(BO->getOperand(0),
6215 ConstantExpr::getShl(BOOp, Op1));
6216
6217 // Try to fold constant and into select arguments.
6218 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
6219 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6220 return R;
6221 if (isa<PHINode>(Op0))
6222 if (Instruction *NV = FoldOpIntoPhi(I))
6223 return NV;
6224
Chris Lattner8999dd32007-12-22 09:07:47 +00006225 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
6226 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
6227 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
6228 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
6229 // place. Don't try to do this transformation in this case. Also, we
6230 // require that the input operand is a shift-by-constant so that we have
6231 // confidence that the shifts will get folded together. We could do this
6232 // xform in more cases, but it is unlikely to be profitable.
6233 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
6234 isa<ConstantInt>(TrOp->getOperand(1))) {
6235 // Okay, we'll do this xform. Make the shift of shift.
6236 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
6237 Instruction *NSh = BinaryOperator::create(I.getOpcode(), TrOp, ShAmt,
6238 I.getName());
6239 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
6240
6241 // For logical shifts, the truncation has the effect of making the high
6242 // part of the register be zeros. Emulate this by inserting an AND to
6243 // clear the top bits as needed. This 'and' will usually be zapped by
6244 // other xforms later if dead.
6245 unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
6246 unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
6247 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
6248
6249 // The mask we constructed says what the trunc would do if occurring
6250 // between the shifts. We want to know the effect *after* the second
6251 // shift. We know that it is a logical shift by a constant, so adjust the
6252 // mask as appropriate.
6253 if (I.getOpcode() == Instruction::Shl)
6254 MaskV <<= Op1->getZExtValue();
6255 else {
6256 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
6257 MaskV = MaskV.lshr(Op1->getZExtValue());
6258 }
6259
6260 Instruction *And = BinaryOperator::createAnd(NSh, ConstantInt::get(MaskV),
6261 TI->getName());
6262 InsertNewInstBefore(And, I); // shift1 & 0x00FF
6263
6264 // Return the value truncated to the interesting size.
6265 return new TruncInst(And, I.getType());
6266 }
6267 }
6268
Chris Lattner4d5542c2006-01-06 07:12:35 +00006269 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00006270 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
6271 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
6272 Value *V1, *V2;
6273 ConstantInt *CC;
6274 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00006275 default: break;
6276 case Instruction::Add:
6277 case Instruction::And:
6278 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00006279 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00006280 // These operators commute.
6281 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00006282 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
6283 match(Op0BO->getOperand(1),
Chris Lattner4d5542c2006-01-06 07:12:35 +00006284 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Reid Spencercc46cdb2007-02-02 14:08:20 +00006285 Instruction *YS = BinaryOperator::createShl(
Chris Lattner4d5542c2006-01-06 07:12:35 +00006286 Op0BO->getOperand(0), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00006287 Op0BO->getName());
6288 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006289 Instruction *X =
6290 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
6291 Op0BO->getOperand(1)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006292 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00006293 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Zhou Sheng90b96812007-03-30 05:45:18 +00006294 return BinaryOperator::createAnd(X, ConstantInt::get(
6295 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00006296 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006297
Chris Lattner150f12a2005-09-18 06:30:59 +00006298 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00006299 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00006300 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00006301 match(Op0BOOp1,
6302 m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
Chris Lattner3c698492007-03-05 00:11:19 +00006303 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
6304 V2 == Op1) {
Reid Spencercc46cdb2007-02-02 14:08:20 +00006305 Instruction *YS = BinaryOperator::createShl(
Reid Spencer832254e2007-02-02 02:16:23 +00006306 Op0BO->getOperand(0), Op1,
6307 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006308 InsertNewInstBefore(YS, I); // (Y << C)
6309 Instruction *XM =
Chris Lattner4d5542c2006-01-06 07:12:35 +00006310 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00006311 V1->getName()+".mask");
6312 InsertNewInstBefore(XM, I); // X & (CC << C)
6313
6314 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
6315 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00006316 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006317
Reid Spencera07cb7d2007-02-02 14:41:37 +00006318 // FALL THROUGH.
6319 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00006320 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00006321 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6322 match(Op0BO->getOperand(0),
Chris Lattner4d5542c2006-01-06 07:12:35 +00006323 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Reid Spencercc46cdb2007-02-02 14:08:20 +00006324 Instruction *YS = BinaryOperator::createShl(
Reid Spencer832254e2007-02-02 02:16:23 +00006325 Op0BO->getOperand(1), Op1,
6326 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006327 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006328 Instruction *X =
Chris Lattner13d4ab42006-05-31 21:14:00 +00006329 BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006330 Op0BO->getOperand(0)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006331 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00006332 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Zhou Sheng90b96812007-03-30 05:45:18 +00006333 return BinaryOperator::createAnd(X, ConstantInt::get(
6334 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00006335 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006336
Chris Lattner13d4ab42006-05-31 21:14:00 +00006337 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00006338 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6339 match(Op0BO->getOperand(0),
6340 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner4d5542c2006-01-06 07:12:35 +00006341 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006342 cast<BinaryOperator>(Op0BO->getOperand(0))
6343 ->getOperand(0)->hasOneUse()) {
Reid Spencercc46cdb2007-02-02 14:08:20 +00006344 Instruction *YS = BinaryOperator::createShl(
Reid Spencer832254e2007-02-02 02:16:23 +00006345 Op0BO->getOperand(1), Op1,
6346 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006347 InsertNewInstBefore(YS, I); // (Y << C)
6348 Instruction *XM =
Chris Lattner4d5542c2006-01-06 07:12:35 +00006349 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00006350 V1->getName()+".mask");
6351 InsertNewInstBefore(XM, I); // X & (CC << C)
6352
Chris Lattner13d4ab42006-05-31 21:14:00 +00006353 return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00006354 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006355
Chris Lattner11021cb2005-09-18 05:12:10 +00006356 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00006357 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006358 }
6359
6360
6361 // If the operand is an bitwise operator with a constant RHS, and the
6362 // shift is the only use, we can pull it out of the shift.
6363 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
6364 bool isValid = true; // Valid only for And, Or, Xor
6365 bool highBitSet = false; // Transform if high bit of constant set?
6366
6367 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00006368 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00006369 case Instruction::Add:
6370 isValid = isLeftShift;
6371 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00006372 case Instruction::Or:
6373 case Instruction::Xor:
6374 highBitSet = false;
6375 break;
6376 case Instruction::And:
6377 highBitSet = true;
6378 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006379 }
6380
6381 // If this is a signed shift right, and the high bit is modified
6382 // by the logical operation, do not perform the transformation.
6383 // The highBitSet boolean indicates the value of the high bit of
6384 // the constant which would cause it to be modified for this
6385 // operation.
6386 //
Chris Lattnerc95ba442007-12-06 06:25:04 +00006387 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Shenge9e03f62007-03-28 15:02:20 +00006388 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006389
6390 if (isValid) {
6391 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
6392
6393 Instruction *NewShift =
Chris Lattner6934a042007-02-11 01:23:03 +00006394 BinaryOperator::create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00006395 InsertNewInstBefore(NewShift, I);
Chris Lattner6934a042007-02-11 01:23:03 +00006396 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00006397
6398 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
6399 NewRHS);
6400 }
6401 }
6402 }
6403 }
6404
Chris Lattnerad0124c2006-01-06 07:52:12 +00006405 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00006406 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
6407 if (ShiftOp && !ShiftOp->isShift())
6408 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00006409
Reid Spencerb83eb642006-10-20 07:07:24 +00006410 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00006411 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00006412 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
6413 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00006414 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
6415 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
6416 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00006417
Zhou Sheng4351c642007-04-02 08:20:41 +00006418 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Reid Spencerb35ae032007-03-23 18:46:34 +00006419 if (AmtSum > TypeBits)
6420 AmtSum = TypeBits;
Chris Lattnerb87056f2007-02-05 00:57:54 +00006421
6422 const IntegerType *Ty = cast<IntegerType>(I.getType());
6423
6424 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00006425 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattnerb87056f2007-02-05 00:57:54 +00006426 return BinaryOperator::create(I.getOpcode(), X,
6427 ConstantInt::get(Ty, AmtSum));
6428 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
6429 I.getOpcode() == Instruction::AShr) {
6430 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
6431 return BinaryOperator::createLShr(X, ConstantInt::get(Ty, AmtSum));
6432 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
6433 I.getOpcode() == Instruction::LShr) {
6434 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
6435 Instruction *Shift =
6436 BinaryOperator::createAShr(X, ConstantInt::get(Ty, AmtSum));
6437 InsertNewInstBefore(Shift, I);
6438
Zhou Shenge9e03f62007-03-28 15:02:20 +00006439 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Reid Spencerb35ae032007-03-23 18:46:34 +00006440 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00006441 }
6442
Chris Lattnerb87056f2007-02-05 00:57:54 +00006443 // Okay, if we get here, one shift must be left, and the other shift must be
6444 // right. See if the amounts are equal.
6445 if (ShiftAmt1 == ShiftAmt2) {
6446 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
6447 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00006448 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Reid Spencerb35ae032007-03-23 18:46:34 +00006449 return BinaryOperator::createAnd(X, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006450 }
6451 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
6452 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00006453 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Reid Spencerb35ae032007-03-23 18:46:34 +00006454 return BinaryOperator::createAnd(X, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006455 }
6456 // We can simplify ((X << C) >>s C) into a trunc + sext.
6457 // NOTE: we could do this for any C, but that would make 'unusual' integer
6458 // types. For now, just stick to ones well-supported by the code
6459 // generators.
6460 const Type *SExtType = 0;
6461 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00006462 case 1 :
6463 case 8 :
6464 case 16 :
6465 case 32 :
6466 case 64 :
6467 case 128:
6468 SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
6469 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00006470 default: break;
6471 }
6472 if (SExtType) {
6473 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
6474 InsertNewInstBefore(NewTrunc, I);
6475 return new SExtInst(NewTrunc, Ty);
6476 }
6477 // Otherwise, we can't handle it yet.
6478 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00006479 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00006480
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006481 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006482 if (I.getOpcode() == Instruction::Shl) {
6483 assert(ShiftOp->getOpcode() == Instruction::LShr ||
6484 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnere8d56c52006-01-07 01:32:28 +00006485 Instruction *Shift =
Chris Lattnerb87056f2007-02-05 00:57:54 +00006486 BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00006487 InsertNewInstBefore(Shift, I);
6488
Reid Spencer55702aa2007-03-25 21:11:44 +00006489 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
6490 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00006491 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00006492
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006493 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006494 if (I.getOpcode() == Instruction::LShr) {
6495 assert(ShiftOp->getOpcode() == Instruction::Shl);
6496 Instruction *Shift =
6497 BinaryOperator::createLShr(X, ConstantInt::get(Ty, ShiftDiff));
6498 InsertNewInstBefore(Shift, I);
Chris Lattnerad0124c2006-01-06 07:52:12 +00006499
Reid Spencerd5e30f02007-03-26 17:18:58 +00006500 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Reid Spencerb35ae032007-03-23 18:46:34 +00006501 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00006502 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00006503
6504 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
6505 } else {
6506 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00006507 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00006508
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006509 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006510 if (I.getOpcode() == Instruction::Shl) {
6511 assert(ShiftOp->getOpcode() == Instruction::LShr ||
6512 ShiftOp->getOpcode() == Instruction::AShr);
6513 Instruction *Shift =
6514 BinaryOperator::create(ShiftOp->getOpcode(), X,
6515 ConstantInt::get(Ty, ShiftDiff));
6516 InsertNewInstBefore(Shift, I);
6517
Reid Spencer55702aa2007-03-25 21:11:44 +00006518 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Reid Spencerb35ae032007-03-23 18:46:34 +00006519 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006520 }
6521
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006522 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006523 if (I.getOpcode() == Instruction::LShr) {
6524 assert(ShiftOp->getOpcode() == Instruction::Shl);
6525 Instruction *Shift =
6526 BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
6527 InsertNewInstBefore(Shift, I);
6528
Reid Spencer68d27cf2007-03-26 23:45:51 +00006529 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Reid Spencerb35ae032007-03-23 18:46:34 +00006530 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006531 }
6532
6533 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00006534 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00006535 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00006536 return 0;
6537}
6538
Chris Lattnera1be5662002-05-02 17:06:02 +00006539
Chris Lattnercfd65102005-10-29 04:36:15 +00006540/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
6541/// expression. If so, decompose it, returning some value X, such that Val is
6542/// X*Scale+Offset.
6543///
6544static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Jeff Cohen86796be2007-04-04 16:58:57 +00006545 int &Offset) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00006546 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00006547 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00006548 Offset = CI->getZExtValue();
Chris Lattner6a94de22007-10-12 05:30:59 +00006549 Scale = 0;
Reid Spencerc5b206b2006-12-31 05:48:39 +00006550 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattner6a94de22007-10-12 05:30:59 +00006551 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
6552 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
6553 if (I->getOpcode() == Instruction::Shl) {
6554 // This is a value scaled by '1 << the shift amt'.
6555 Scale = 1U << RHS->getZExtValue();
6556 Offset = 0;
6557 return I->getOperand(0);
6558 } else if (I->getOpcode() == Instruction::Mul) {
6559 // This value is scaled by 'RHS'.
6560 Scale = RHS->getZExtValue();
6561 Offset = 0;
6562 return I->getOperand(0);
6563 } else if (I->getOpcode() == Instruction::Add) {
6564 // We have X+C. Check to see if we really have (X*C2)+C1,
6565 // where C1 is divisible by C2.
6566 unsigned SubScale;
6567 Value *SubVal =
6568 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
6569 Offset += RHS->getZExtValue();
6570 Scale = SubScale;
6571 return SubVal;
Chris Lattnercfd65102005-10-29 04:36:15 +00006572 }
6573 }
6574 }
6575
6576 // Otherwise, we can't look past this.
6577 Scale = 1;
6578 Offset = 0;
6579 return Val;
6580}
6581
6582
Chris Lattnerb3f83972005-10-24 06:03:58 +00006583/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
6584/// try to eliminate the cast by moving the type information into the alloc.
Chris Lattnerd3e28342007-04-27 17:44:50 +00006585Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Chris Lattnerb3f83972005-10-24 06:03:58 +00006586 AllocationInst &AI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00006587 const PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattnerb3f83972005-10-24 06:03:58 +00006588
Chris Lattnerb53c2382005-10-24 06:22:12 +00006589 // Remove any uses of AI that are dead.
6590 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner535014f2007-02-15 22:52:10 +00006591
Chris Lattnerb53c2382005-10-24 06:22:12 +00006592 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
6593 Instruction *User = cast<Instruction>(*UI++);
6594 if (isInstructionTriviallyDead(User)) {
6595 while (UI != E && *UI == User)
6596 ++UI; // If this instruction uses AI more than once, don't break UI.
6597
Chris Lattnerb53c2382005-10-24 06:22:12 +00006598 ++NumDeadInst;
Bill Wendlingb7427032006-11-26 09:46:52 +00006599 DOUT << "IC: DCE: " << *User;
Chris Lattnerf22a5c62007-03-02 19:59:19 +00006600 EraseInstFromFunction(*User);
Chris Lattnerb53c2382005-10-24 06:22:12 +00006601 }
6602 }
6603
Chris Lattnerb3f83972005-10-24 06:03:58 +00006604 // Get the type really allocated and the type casted to.
6605 const Type *AllocElTy = AI.getAllocatedType();
6606 const Type *CastElTy = PTy->getElementType();
6607 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00006608
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00006609 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
6610 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00006611 if (CastElTyAlign < AllocElTyAlign) return 0;
6612
Chris Lattner39387a52005-10-24 06:35:18 +00006613 // If the allocation has multiple uses, only promote it if we are strictly
6614 // increasing the alignment of the resultant allocation. If we keep it the
6615 // same, we open the door to infinite loops of various kinds.
6616 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
6617
Duncan Sands514ab342007-11-01 20:53:16 +00006618 uint64_t AllocElTySize = TD->getABITypeSize(AllocElTy);
6619 uint64_t CastElTySize = TD->getABITypeSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00006620 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00006621
Chris Lattner455fcc82005-10-29 03:19:53 +00006622 // See if we can satisfy the modulus by pulling a scale out of the array
6623 // size argument.
Jeff Cohen86796be2007-04-04 16:58:57 +00006624 unsigned ArraySizeScale;
6625 int ArrayOffset;
Chris Lattnercfd65102005-10-29 04:36:15 +00006626 Value *NumElements = // See if the array size is a decomposable linear expr.
6627 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
6628
Chris Lattner455fcc82005-10-29 03:19:53 +00006629 // If we can now satisfy the modulus, by using a non-1 scale, we really can
6630 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00006631 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
6632 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00006633
Chris Lattner455fcc82005-10-29 03:19:53 +00006634 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
6635 Value *Amt = 0;
6636 if (Scale == 1) {
6637 Amt = NumElements;
6638 } else {
Reid Spencerb83eb642006-10-20 07:07:24 +00006639 // If the allocation size is constant, form a constant mul expression
Reid Spencerc5b206b2006-12-31 05:48:39 +00006640 Amt = ConstantInt::get(Type::Int32Ty, Scale);
6641 if (isa<ConstantInt>(NumElements))
Zhou Sheng4a1822a2007-04-02 13:45:30 +00006642 Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
Reid Spencerb83eb642006-10-20 07:07:24 +00006643 // otherwise multiply the amount and the number of elements
Chris Lattner455fcc82005-10-29 03:19:53 +00006644 else if (Scale != 1) {
6645 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
6646 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattner8142b0a2005-10-27 06:12:00 +00006647 }
Chris Lattner0ddac2a2005-10-27 05:53:56 +00006648 }
6649
Jeff Cohen86796be2007-04-04 16:58:57 +00006650 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
6651 Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
Chris Lattnercfd65102005-10-29 04:36:15 +00006652 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
6653 Amt = InsertNewInstBefore(Tmp, AI);
6654 }
6655
Chris Lattnerb3f83972005-10-24 06:03:58 +00006656 AllocationInst *New;
6657 if (isa<MallocInst>(AI))
Chris Lattner6934a042007-02-11 01:23:03 +00006658 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00006659 else
Chris Lattner6934a042007-02-11 01:23:03 +00006660 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00006661 InsertNewInstBefore(New, AI);
Chris Lattner6934a042007-02-11 01:23:03 +00006662 New->takeName(&AI);
Chris Lattner39387a52005-10-24 06:35:18 +00006663
6664 // If the allocation has multiple uses, insert a cast and change all things
6665 // that used it to use the new cast. This will also hack on CI, but it will
6666 // die soon.
6667 if (!AI.hasOneUse()) {
6668 AddUsesToWorkList(AI);
Reid Spencer3da59db2006-11-27 01:05:10 +00006669 // New is the allocation instruction, pointer typed. AI is the original
6670 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
6671 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner39387a52005-10-24 06:35:18 +00006672 InsertNewInstBefore(NewCast, AI);
6673 AI.replaceAllUsesWith(NewCast);
6674 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00006675 return ReplaceInstUsesWith(CI, New);
6676}
6677
Chris Lattner70074e02006-05-13 02:06:03 +00006678/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerc739cd62007-03-03 05:27:34 +00006679/// and return it as type Ty without inserting any new casts and without
6680/// changing the computed value. This is used by code that tries to decide
6681/// whether promoting or shrinking integer operations to wider or smaller types
6682/// will allow us to eliminate a truncate or extend.
6683///
6684/// This is a truncation operation if Ty is smaller than V->getType(), or an
6685/// extension operation if Ty is larger.
6686static bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
Chris Lattner951626b2007-08-02 06:11:14 +00006687 unsigned CastOpc, int &NumCastsRemoved) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00006688 // We can always evaluate constants in another type.
6689 if (isa<ConstantInt>(V))
6690 return true;
Chris Lattner70074e02006-05-13 02:06:03 +00006691
6692 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006693 if (!I) return false;
6694
6695 const IntegerType *OrigTy = cast<IntegerType>(V->getType());
Chris Lattner70074e02006-05-13 02:06:03 +00006696
Chris Lattner951626b2007-08-02 06:11:14 +00006697 // If this is an extension or truncate, we can often eliminate it.
6698 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
6699 // If this is a cast from the destination type, we can trivially eliminate
6700 // it, and this will remove a cast overall.
6701 if (I->getOperand(0)->getType() == Ty) {
6702 // If the first operand is itself a cast, and is eliminable, do not count
6703 // this as an eliminable cast. We would prefer to eliminate those two
6704 // casts first.
6705 if (!isa<CastInst>(I->getOperand(0)))
6706 ++NumCastsRemoved;
6707 return true;
6708 }
6709 }
6710
6711 // We can't extend or shrink something that has multiple uses: doing so would
6712 // require duplicating the instruction in general, which isn't profitable.
6713 if (!I->hasOneUse()) return false;
6714
Chris Lattner70074e02006-05-13 02:06:03 +00006715 switch (I->getOpcode()) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00006716 case Instruction::Add:
6717 case Instruction::Sub:
Chris Lattner70074e02006-05-13 02:06:03 +00006718 case Instruction::And:
6719 case Instruction::Or:
6720 case Instruction::Xor:
6721 // These operators can all arbitrarily be extended or truncated.
Chris Lattner951626b2007-08-02 06:11:14 +00006722 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6723 NumCastsRemoved) &&
6724 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
6725 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006726
Nick Lewyckye6b0c002008-01-22 05:08:48 +00006727 case Instruction::Mul:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00006728 // A multiply can be truncated by truncating its operands.
6729 return Ty->getBitWidth() < OrigTy->getBitWidth() &&
6730 CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6731 NumCastsRemoved) &&
6732 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
6733 NumCastsRemoved);
6734
Chris Lattner46b96052006-11-29 07:18:39 +00006735 case Instruction::Shl:
Chris Lattnerc739cd62007-03-03 05:27:34 +00006736 // If we are truncating the result of this SHL, and if it's a shift of a
6737 // constant amount, we can always perform a SHL in a smaller type.
6738 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00006739 uint32_t BitWidth = Ty->getBitWidth();
6740 if (BitWidth < OrigTy->getBitWidth() &&
6741 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattner951626b2007-08-02 06:11:14 +00006742 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6743 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006744 }
6745 break;
6746 case Instruction::LShr:
Chris Lattnerc739cd62007-03-03 05:27:34 +00006747 // If this is a truncate of a logical shr, we can truncate it to a smaller
6748 // lshr iff we know that the bits we would otherwise be shifting in are
6749 // already zeros.
6750 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00006751 uint32_t OrigBitWidth = OrigTy->getBitWidth();
6752 uint32_t BitWidth = Ty->getBitWidth();
6753 if (BitWidth < OrigBitWidth &&
Chris Lattnerc739cd62007-03-03 05:27:34 +00006754 MaskedValueIsZero(I->getOperand(0),
Zhou Sheng302748d2007-03-30 17:20:39 +00006755 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
6756 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattner951626b2007-08-02 06:11:14 +00006757 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6758 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006759 }
6760 }
Chris Lattner46b96052006-11-29 07:18:39 +00006761 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00006762 case Instruction::ZExt:
6763 case Instruction::SExt:
Chris Lattner951626b2007-08-02 06:11:14 +00006764 case Instruction::Trunc:
6765 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner5543a852007-08-02 17:23:38 +00006766 // can safely replace it. Note that replacing it does not reduce the number
6767 // of casts in the input.
6768 if (I->getOpcode() == CastOpc)
Chris Lattner70074e02006-05-13 02:06:03 +00006769 return true;
Chris Lattner50d9d772007-09-10 23:46:29 +00006770
Reid Spencer3da59db2006-11-27 01:05:10 +00006771 break;
6772 default:
Chris Lattner70074e02006-05-13 02:06:03 +00006773 // TODO: Can handle more cases here.
6774 break;
6775 }
6776
6777 return false;
6778}
6779
6780/// EvaluateInDifferentType - Given an expression that
6781/// CanEvaluateInDifferentType returns true for, actually insert the code to
6782/// evaluate the expression.
Reid Spencerc55b2432006-12-13 18:21:21 +00006783Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerc739cd62007-03-03 05:27:34 +00006784 bool isSigned) {
Chris Lattner70074e02006-05-13 02:06:03 +00006785 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencerc55b2432006-12-13 18:21:21 +00006786 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Chris Lattner70074e02006-05-13 02:06:03 +00006787
6788 // Otherwise, it must be an instruction.
6789 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00006790 Instruction *Res = 0;
Chris Lattner70074e02006-05-13 02:06:03 +00006791 switch (I->getOpcode()) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00006792 case Instruction::Add:
6793 case Instruction::Sub:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00006794 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00006795 case Instruction::And:
6796 case Instruction::Or:
Chris Lattnerc739cd62007-03-03 05:27:34 +00006797 case Instruction::Xor:
Chris Lattner46b96052006-11-29 07:18:39 +00006798 case Instruction::AShr:
6799 case Instruction::LShr:
6800 case Instruction::Shl: {
Reid Spencerc55b2432006-12-13 18:21:21 +00006801 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006802 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
6803 Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
6804 LHS, RHS, I->getName());
Chris Lattner46b96052006-11-29 07:18:39 +00006805 break;
6806 }
Reid Spencer3da59db2006-11-27 01:05:10 +00006807 case Instruction::Trunc:
6808 case Instruction::ZExt:
6809 case Instruction::SExt:
Reid Spencer3da59db2006-11-27 01:05:10 +00006810 // If the source type of the cast is the type we're trying for then we can
Chris Lattner951626b2007-08-02 06:11:14 +00006811 // just return the source. There's no need to insert it because it is not
6812 // new.
Chris Lattner70074e02006-05-13 02:06:03 +00006813 if (I->getOperand(0)->getType() == Ty)
6814 return I->getOperand(0);
6815
Chris Lattner951626b2007-08-02 06:11:14 +00006816 // Otherwise, must be the same type of case, so just reinsert a new one.
6817 Res = CastInst::create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
6818 Ty, I->getName());
6819 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00006820 default:
Chris Lattner70074e02006-05-13 02:06:03 +00006821 // TODO: Can handle more cases here.
6822 assert(0 && "Unreachable!");
6823 break;
6824 }
6825
6826 return InsertNewInstBefore(Res, *I);
6827}
6828
Reid Spencer3da59db2006-11-27 01:05:10 +00006829/// @brief Implement the transforms common to all CastInst visitors.
6830Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00006831 Value *Src = CI.getOperand(0);
6832
Dan Gohman23d9d272007-05-11 21:10:54 +00006833 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
Reid Spencer3da59db2006-11-27 01:05:10 +00006834 // eliminate it now.
Chris Lattner6e7ba452005-01-01 16:22:27 +00006835 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00006836 if (Instruction::CastOps opc =
6837 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
6838 // The first cast (CSrc) is eliminable so we need to fix up or replace
6839 // the second cast (CI). CSrc will then have a good chance of being dead.
6840 return CastInst::create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner8fd217c2002-08-02 20:00:25 +00006841 }
6842 }
Chris Lattnera710ddc2004-05-25 04:29:21 +00006843
Reid Spencer3da59db2006-11-27 01:05:10 +00006844 // If we are casting a select then fold the cast into the select
Chris Lattner6e7ba452005-01-01 16:22:27 +00006845 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
6846 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
6847 return NV;
Reid Spencer3da59db2006-11-27 01:05:10 +00006848
6849 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner4e998b22004-09-29 05:07:12 +00006850 if (isa<PHINode>(Src))
6851 if (Instruction *NV = FoldOpIntoPhi(CI))
6852 return NV;
Chris Lattner9fb92132006-04-12 18:09:35 +00006853
Reid Spencer3da59db2006-11-27 01:05:10 +00006854 return 0;
6855}
6856
Chris Lattnerd3e28342007-04-27 17:44:50 +00006857/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
6858Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
6859 Value *Src = CI.getOperand(0);
6860
Chris Lattnerd3e28342007-04-27 17:44:50 +00006861 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner9bc14642007-04-28 00:57:34 +00006862 // If casting the result of a getelementptr instruction with no offset, turn
6863 // this into a cast of the original pointer!
Chris Lattnerd3e28342007-04-27 17:44:50 +00006864 if (GEP->hasAllZeroIndices()) {
6865 // Changing the cast operand is usually not a good idea but it is safe
6866 // here because the pointer operand is being replaced with another
6867 // pointer operand so the opcode doesn't need to change.
Chris Lattner9bc14642007-04-28 00:57:34 +00006868 AddToWorkList(GEP);
Chris Lattnerd3e28342007-04-27 17:44:50 +00006869 CI.setOperand(0, GEP->getOperand(0));
6870 return &CI;
6871 }
Chris Lattner9bc14642007-04-28 00:57:34 +00006872
6873 // If the GEP has a single use, and the base pointer is a bitcast, and the
6874 // GEP computes a constant offset, see if we can convert these three
6875 // instructions into fewer. This typically happens with unions and other
6876 // non-type-safe code.
6877 if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
6878 if (GEP->hasAllConstantIndices()) {
6879 // We are guaranteed to get a constant from EmitGEPOffset.
6880 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
6881 int64_t Offset = OffsetV->getSExtValue();
6882
6883 // Get the base pointer input of the bitcast, and the type it points to.
6884 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
6885 const Type *GEPIdxTy =
6886 cast<PointerType>(OrigBase->getType())->getElementType();
6887 if (GEPIdxTy->isSized()) {
6888 SmallVector<Value*, 8> NewIndices;
6889
Chris Lattnerc42e2262007-05-05 01:59:31 +00006890 // Start with the index over the outer type. Note that the type size
6891 // might be zero (even if the offset isn't zero) if the indexed type
6892 // is something like [0 x {int, int}]
Chris Lattner9bc14642007-04-28 00:57:34 +00006893 const Type *IntPtrTy = TD->getIntPtrType();
Chris Lattnerc42e2262007-05-05 01:59:31 +00006894 int64_t FirstIdx = 0;
Duncan Sands514ab342007-11-01 20:53:16 +00006895 if (int64_t TySize = TD->getABITypeSize(GEPIdxTy)) {
Chris Lattnerc42e2262007-05-05 01:59:31 +00006896 FirstIdx = Offset/TySize;
6897 Offset %= TySize;
Chris Lattner9bc14642007-04-28 00:57:34 +00006898
Chris Lattnerc42e2262007-05-05 01:59:31 +00006899 // Handle silly modulus not returning values values [0..TySize).
6900 if (Offset < 0) {
6901 --FirstIdx;
6902 Offset += TySize;
6903 assert(Offset >= 0);
6904 }
Chris Lattnerd717c182007-05-05 22:32:24 +00006905 assert((uint64_t)Offset < (uint64_t)TySize &&"Out of range offset");
Chris Lattner9bc14642007-04-28 00:57:34 +00006906 }
6907
6908 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner9bc14642007-04-28 00:57:34 +00006909
6910 // Index into the types. If we fail, set OrigBase to null.
6911 while (Offset) {
6912 if (const StructType *STy = dyn_cast<StructType>(GEPIdxTy)) {
6913 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattner6b6aef82007-05-15 00:16:00 +00006914 if (Offset < (int64_t)SL->getSizeInBytes()) {
6915 unsigned Elt = SL->getElementContainingOffset(Offset);
6916 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
Chris Lattner9bc14642007-04-28 00:57:34 +00006917
Chris Lattner6b6aef82007-05-15 00:16:00 +00006918 Offset -= SL->getElementOffset(Elt);
6919 GEPIdxTy = STy->getElementType(Elt);
6920 } else {
6921 // Otherwise, we can't index into this, bail out.
6922 Offset = 0;
6923 OrigBase = 0;
6924 }
Chris Lattner9bc14642007-04-28 00:57:34 +00006925 } else if (isa<ArrayType>(GEPIdxTy) || isa<VectorType>(GEPIdxTy)) {
6926 const SequentialType *STy = cast<SequentialType>(GEPIdxTy);
Duncan Sands514ab342007-11-01 20:53:16 +00006927 if (uint64_t EltSize = TD->getABITypeSize(STy->getElementType())){
Chris Lattner6b6aef82007-05-15 00:16:00 +00006928 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
6929 Offset %= EltSize;
6930 } else {
6931 NewIndices.push_back(ConstantInt::get(IntPtrTy, 0));
6932 }
Chris Lattner9bc14642007-04-28 00:57:34 +00006933 GEPIdxTy = STy->getElementType();
6934 } else {
6935 // Otherwise, we can't index into this, bail out.
6936 Offset = 0;
6937 OrigBase = 0;
6938 }
6939 }
6940 if (OrigBase) {
6941 // If we were able to index down into an element, create the GEP
6942 // and bitcast the result. This eliminates one bitcast, potentially
6943 // two.
David Greeneb8f74792007-09-04 15:46:09 +00006944 Instruction *NGEP = new GetElementPtrInst(OrigBase,
6945 NewIndices.begin(),
6946 NewIndices.end(), "");
Chris Lattner9bc14642007-04-28 00:57:34 +00006947 InsertNewInstBefore(NGEP, CI);
6948 NGEP->takeName(GEP);
6949
Chris Lattner9bc14642007-04-28 00:57:34 +00006950 if (isa<BitCastInst>(CI))
6951 return new BitCastInst(NGEP, CI.getType());
6952 assert(isa<PtrToIntInst>(CI));
6953 return new PtrToIntInst(NGEP, CI.getType());
6954 }
6955 }
6956 }
6957 }
Chris Lattnerd3e28342007-04-27 17:44:50 +00006958 }
6959
6960 return commonCastTransforms(CI);
6961}
6962
6963
6964
Chris Lattnerc739cd62007-03-03 05:27:34 +00006965/// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
6966/// integer types. This function implements the common transforms for all those
Reid Spencer3da59db2006-11-27 01:05:10 +00006967/// cases.
6968/// @brief Implement the transforms common to CastInst with integer operands
6969Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
6970 if (Instruction *Result = commonCastTransforms(CI))
6971 return Result;
6972
6973 Value *Src = CI.getOperand(0);
6974 const Type *SrcTy = Src->getType();
6975 const Type *DestTy = CI.getType();
Zhou Sheng4351c642007-04-02 08:20:41 +00006976 uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
6977 uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00006978
Reid Spencer3da59db2006-11-27 01:05:10 +00006979 // See if we can simplify any instructions used by the LHS whose sole
6980 // purpose is to compute bits we don't care about.
Reid Spencerad6676e2007-03-22 20:56:53 +00006981 APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
6982 if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
Reid Spencer3da59db2006-11-27 01:05:10 +00006983 KnownZero, KnownOne))
6984 return &CI;
6985
6986 // If the source isn't an instruction or has more than one use then we
6987 // can't do anything more.
Reid Spencere4d87aa2006-12-23 06:05:41 +00006988 Instruction *SrcI = dyn_cast<Instruction>(Src);
6989 if (!SrcI || !Src->hasOneUse())
Reid Spencer3da59db2006-11-27 01:05:10 +00006990 return 0;
6991
Chris Lattnerc739cd62007-03-03 05:27:34 +00006992 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00006993 int NumCastsRemoved = 0;
Chris Lattnerc739cd62007-03-03 05:27:34 +00006994 if (!isa<BitCastInst>(CI) &&
6995 CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
Chris Lattner951626b2007-08-02 06:11:14 +00006996 CI.getOpcode(), NumCastsRemoved)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00006997 // If this cast is a truncate, evaluting in a different type always
Chris Lattner951626b2007-08-02 06:11:14 +00006998 // eliminates the cast, so it is always a win. If this is a zero-extension,
6999 // we need to do an AND to maintain the clear top-part of the computation,
7000 // so we require that the input have eliminated at least one cast. If this
7001 // is a sign extension, we insert two new casts (to do the extension) so we
Reid Spencer3da59db2006-11-27 01:05:10 +00007002 // require that two casts have been eliminated.
Chris Lattnerc739cd62007-03-03 05:27:34 +00007003 bool DoXForm;
7004 switch (CI.getOpcode()) {
7005 default:
7006 // All the others use floating point so we shouldn't actually
7007 // get here because of the check above.
7008 assert(0 && "Unknown cast type");
7009 case Instruction::Trunc:
7010 DoXForm = true;
7011 break;
7012 case Instruction::ZExt:
7013 DoXForm = NumCastsRemoved >= 1;
7014 break;
7015 case Instruction::SExt:
7016 DoXForm = NumCastsRemoved >= 2;
7017 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007018 }
7019
7020 if (DoXForm) {
Reid Spencerc55b2432006-12-13 18:21:21 +00007021 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
7022 CI.getOpcode() == Instruction::SExt);
Reid Spencer3da59db2006-11-27 01:05:10 +00007023 assert(Res->getType() == DestTy);
7024 switch (CI.getOpcode()) {
7025 default: assert(0 && "Unknown cast type!");
7026 case Instruction::Trunc:
7027 case Instruction::BitCast:
7028 // Just replace this cast with the result.
7029 return ReplaceInstUsesWith(CI, Res);
7030 case Instruction::ZExt: {
7031 // We need to emit an AND to clear the high bits.
7032 assert(SrcBitSize < DestBitSize && "Not a zext?");
Chris Lattnercd1d6d52007-04-02 05:48:58 +00007033 Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
7034 SrcBitSize));
Reid Spencer3da59db2006-11-27 01:05:10 +00007035 return BinaryOperator::createAnd(Res, C);
7036 }
7037 case Instruction::SExt:
7038 // We need to emit a cast to truncate, then a cast to sext.
7039 return CastInst::create(Instruction::SExt,
Reid Spencer17212df2006-12-12 09:18:51 +00007040 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
7041 CI), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00007042 }
7043 }
7044 }
7045
7046 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
7047 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
7048
7049 switch (SrcI->getOpcode()) {
7050 case Instruction::Add:
7051 case Instruction::Mul:
7052 case Instruction::And:
7053 case Instruction::Or:
7054 case Instruction::Xor:
Chris Lattner01deb9d2007-04-03 17:43:25 +00007055 // If we are discarding information, rewrite.
Reid Spencer3da59db2006-11-27 01:05:10 +00007056 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
7057 // Don't insert two casts if they cannot be eliminated. We allow
7058 // two casts to be inserted if the sizes are the same. This could
7059 // only be converting signedness, which is a noop.
7060 if (DestBitSize == SrcBitSize ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00007061 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
7062 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer7eb76382006-12-13 17:19:09 +00007063 Instruction::CastOps opcode = CI.getOpcode();
Reid Spencer17212df2006-12-12 09:18:51 +00007064 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7065 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
7066 return BinaryOperator::create(
7067 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00007068 }
7069 }
7070
7071 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
7072 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
7073 SrcI->getOpcode() == Instruction::Xor &&
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007074 Op1 == ConstantInt::getTrue() &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00007075 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Reid Spencer17212df2006-12-12 09:18:51 +00007076 Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007077 return BinaryOperator::createXor(New, ConstantInt::get(CI.getType(), 1));
7078 }
7079 break;
7080 case Instruction::SDiv:
7081 case Instruction::UDiv:
7082 case Instruction::SRem:
7083 case Instruction::URem:
7084 // If we are just changing the sign, rewrite.
7085 if (DestBitSize == SrcBitSize) {
7086 // Don't insert two casts if they cannot be eliminated. We allow
7087 // two casts to be inserted if the sizes are the same. This could
7088 // only be converting signedness, which is a noop.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007089 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
7090 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer17212df2006-12-12 09:18:51 +00007091 Value *Op0c = InsertOperandCastBefore(Instruction::BitCast,
7092 Op0, DestTy, SrcI);
7093 Value *Op1c = InsertOperandCastBefore(Instruction::BitCast,
7094 Op1, DestTy, SrcI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007095 return BinaryOperator::create(
7096 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7097 }
7098 }
7099 break;
7100
7101 case Instruction::Shl:
7102 // Allow changing the sign of the source operand. Do not allow
7103 // changing the size of the shift, UNLESS the shift amount is a
7104 // constant. We must not change variable sized shifts to a smaller
7105 // size, because it is undefined to shift more bits out than exist
7106 // in the value.
7107 if (DestBitSize == SrcBitSize ||
7108 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
Reid Spencer17212df2006-12-12 09:18:51 +00007109 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
7110 Instruction::BitCast : Instruction::Trunc);
7111 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
Reid Spencer832254e2007-02-02 02:16:23 +00007112 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
Reid Spencercc46cdb2007-02-02 14:08:20 +00007113 return BinaryOperator::createShl(Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00007114 }
7115 break;
7116 case Instruction::AShr:
7117 // If this is a signed shr, and if all bits shifted in are about to be
7118 // truncated off, turn it into an unsigned shr to allow greater
7119 // simplifications.
7120 if (DestBitSize < SrcBitSize &&
7121 isa<ConstantInt>(Op1)) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007122 uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
Reid Spencer3da59db2006-11-27 01:05:10 +00007123 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
7124 // Insert the new logical shift right.
Reid Spencercc46cdb2007-02-02 14:08:20 +00007125 return BinaryOperator::createLShr(Op0, Op1);
Reid Spencer3da59db2006-11-27 01:05:10 +00007126 }
7127 }
7128 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007129 }
7130 return 0;
7131}
7132
Chris Lattner8a9f5712007-04-11 06:57:46 +00007133Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007134 if (Instruction *Result = commonIntCastTransforms(CI))
7135 return Result;
7136
7137 Value *Src = CI.getOperand(0);
7138 const Type *Ty = CI.getType();
Zhou Sheng4351c642007-04-02 08:20:41 +00007139 uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
7140 uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007141
7142 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
7143 switch (SrcI->getOpcode()) {
7144 default: break;
7145 case Instruction::LShr:
7146 // We can shrink lshr to something smaller if we know the bits shifted in
7147 // are already zeros.
7148 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007149 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007150
7151 // Get a mask for the bits shifting in.
Zhou Shenge82fca02007-03-28 09:19:01 +00007152 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
Reid Spencer17212df2006-12-12 09:18:51 +00007153 Value* SrcIOp0 = SrcI->getOperand(0);
7154 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007155 if (ShAmt >= DestBitWidth) // All zeros.
7156 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
7157
7158 // Okay, we can shrink this. Truncate the input, then return a new
7159 // shift.
Reid Spencer832254e2007-02-02 02:16:23 +00007160 Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
7161 Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
7162 Ty, CI);
Reid Spencercc46cdb2007-02-02 14:08:20 +00007163 return BinaryOperator::createLShr(V1, V2);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007164 }
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007165 } else { // This is a variable shr.
7166
7167 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
7168 // more LLVM instructions, but allows '1 << Y' to be hoisted if
7169 // loop-invariant and CSE'd.
Reid Spencer4fe16d62007-01-11 18:21:29 +00007170 if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007171 Value *One = ConstantInt::get(SrcI->getType(), 1);
7172
Reid Spencer832254e2007-02-02 02:16:23 +00007173 Value *V = InsertNewInstBefore(
Reid Spencercc46cdb2007-02-02 14:08:20 +00007174 BinaryOperator::createShl(One, SrcI->getOperand(1),
Reid Spencer832254e2007-02-02 02:16:23 +00007175 "tmp"), CI);
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007176 V = InsertNewInstBefore(BinaryOperator::createAnd(V,
7177 SrcI->getOperand(0),
7178 "tmp"), CI);
7179 Value *Zero = Constant::getNullValue(V->getType());
Reid Spencere4d87aa2006-12-23 06:05:41 +00007180 return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007181 }
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007182 }
7183 break;
7184 }
7185 }
7186
7187 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007188}
7189
Chris Lattner8a9f5712007-04-11 06:57:46 +00007190Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007191 // If one of the common conversion will work ..
7192 if (Instruction *Result = commonIntCastTransforms(CI))
7193 return Result;
7194
7195 Value *Src = CI.getOperand(0);
7196
7197 // If this is a cast of a cast
7198 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00007199 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
7200 // types and if the sizes are just right we can convert this into a logical
7201 // 'and' which will be much cheaper than the pair of casts.
7202 if (isa<TruncInst>(CSrc)) {
7203 // Get the sizes of the types involved
7204 Value *A = CSrc->getOperand(0);
Zhou Sheng4351c642007-04-02 08:20:41 +00007205 uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
7206 uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
7207 uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00007208 // If we're actually extending zero bits and the trunc is a no-op
7209 if (MidSize < DstSize && SrcSize == DstSize) {
7210 // Replace both of the casts with an And of the type mask.
Zhou Shenge82fca02007-03-28 09:19:01 +00007211 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Reid Spencerad6676e2007-03-22 20:56:53 +00007212 Constant *AndConst = ConstantInt::get(AndValue);
Reid Spencer3da59db2006-11-27 01:05:10 +00007213 Instruction *And =
7214 BinaryOperator::createAnd(CSrc->getOperand(0), AndConst);
7215 // Unfortunately, if the type changed, we need to cast it back.
7216 if (And->getType() != CI.getType()) {
7217 And->setName(CSrc->getName()+".mask");
7218 InsertNewInstBefore(And, CI);
Reid Spencerd977d862006-12-12 23:36:14 +00007219 And = CastInst::createIntegerCast(And, CI.getType(), false/*ZExt*/);
Reid Spencer3da59db2006-11-27 01:05:10 +00007220 }
7221 return And;
7222 }
7223 }
7224 }
7225
Chris Lattner66bc3252007-04-11 05:45:39 +00007226 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
7227 // If we are just checking for a icmp eq of a single bit and zext'ing it
7228 // to an integer, then shift the bit to the appropriate place and then
7229 // cast to integer to avoid the comparison.
7230 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
Chris Lattnerba417832007-04-11 06:12:58 +00007231 const APInt &Op1CV = Op1C->getValue();
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00007232
7233 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
7234 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
7235 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7236 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
7237 Value *In = ICI->getOperand(0);
7238 Value *Sh = ConstantInt::get(In->getType(),
7239 In->getType()->getPrimitiveSizeInBits()-1);
7240 In = InsertNewInstBefore(BinaryOperator::createLShr(In, Sh,
Chris Lattnere34e9a22007-04-14 23:32:02 +00007241 In->getName()+".lobit"),
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00007242 CI);
7243 if (In->getType() != CI.getType())
7244 In = CastInst::createIntegerCast(In, CI.getType(),
7245 false/*ZExt*/, "tmp", &CI);
7246
7247 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
7248 Constant *One = ConstantInt::get(In->getType(), 1);
7249 In = InsertNewInstBefore(BinaryOperator::createXor(In, One,
Chris Lattnere34e9a22007-04-14 23:32:02 +00007250 In->getName()+".not"),
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00007251 CI);
7252 }
7253
7254 return ReplaceInstUsesWith(CI, In);
7255 }
7256
7257
7258
Chris Lattnerba417832007-04-11 06:12:58 +00007259 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
7260 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7261 // zext (X == 1) to i32 --> X iff X has only the low bit set.
7262 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
7263 // zext (X != 0) to i32 --> X iff X has only the low bit set.
7264 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
7265 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
7266 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
Chris Lattner66bc3252007-04-11 05:45:39 +00007267 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
7268 // This only works for EQ and NE
7269 ICI->isEquality()) {
7270 // If Op1C some other power of two, convert:
7271 uint32_t BitWidth = Op1C->getType()->getBitWidth();
7272 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
7273 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
7274 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
7275
7276 APInt KnownZeroMask(~KnownZero);
7277 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
7278 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
7279 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
7280 // (X&4) == 2 --> false
7281 // (X&4) != 2 --> true
7282 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
7283 Res = ConstantExpr::getZExt(Res, CI.getType());
7284 return ReplaceInstUsesWith(CI, Res);
7285 }
7286
7287 uint32_t ShiftAmt = KnownZeroMask.logBase2();
7288 Value *In = ICI->getOperand(0);
7289 if (ShiftAmt) {
7290 // Perform a logical shr by shiftamt.
7291 // Insert the shift to put the result in the low bit.
7292 In = InsertNewInstBefore(
7293 BinaryOperator::createLShr(In,
7294 ConstantInt::get(In->getType(), ShiftAmt),
7295 In->getName()+".lobit"), CI);
7296 }
7297
7298 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
7299 Constant *One = ConstantInt::get(In->getType(), 1);
7300 In = BinaryOperator::createXor(In, One, "tmp");
7301 InsertNewInstBefore(cast<Instruction>(In), CI);
7302 }
7303
7304 if (CI.getType() == In->getType())
7305 return ReplaceInstUsesWith(CI, In);
7306 else
7307 return CastInst::createIntegerCast(In, CI.getType(), false/*ZExt*/);
7308 }
7309 }
7310 }
7311 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007312 return 0;
7313}
7314
Chris Lattner8a9f5712007-04-11 06:57:46 +00007315Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattnerba417832007-04-11 06:12:58 +00007316 if (Instruction *I = commonIntCastTransforms(CI))
7317 return I;
7318
Chris Lattner8a9f5712007-04-11 06:57:46 +00007319 Value *Src = CI.getOperand(0);
7320
7321 // sext (x <s 0) -> ashr x, 31 -> all ones if signed
7322 // sext (x >s -1) -> ashr x, 31 -> all ones if not signed
7323 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
7324 // If we are just checking for a icmp eq of a single bit and zext'ing it
7325 // to an integer, then shift the bit to the appropriate place and then
7326 // cast to integer to avoid the comparison.
7327 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7328 const APInt &Op1CV = Op1C->getValue();
7329
7330 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
7331 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
7332 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7333 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
7334 Value *In = ICI->getOperand(0);
7335 Value *Sh = ConstantInt::get(In->getType(),
7336 In->getType()->getPrimitiveSizeInBits()-1);
7337 In = InsertNewInstBefore(BinaryOperator::createAShr(In, Sh,
Chris Lattnere34e9a22007-04-14 23:32:02 +00007338 In->getName()+".lobit"),
Chris Lattner8a9f5712007-04-11 06:57:46 +00007339 CI);
7340 if (In->getType() != CI.getType())
7341 In = CastInst::createIntegerCast(In, CI.getType(),
7342 true/*SExt*/, "tmp", &CI);
7343
7344 if (ICI->getPredicate() == ICmpInst::ICMP_SGT)
7345 In = InsertNewInstBefore(BinaryOperator::createNot(In,
7346 In->getName()+".not"), CI);
7347
7348 return ReplaceInstUsesWith(CI, In);
7349 }
7350 }
7351 }
7352
Chris Lattnerba417832007-04-11 06:12:58 +00007353 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007354}
7355
Chris Lattnerb7530652008-01-27 05:29:54 +00007356/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
7357/// in the specified FP type without changing its value.
7358static Constant *FitsInFPType(ConstantFP *CFP, const Type *FPTy,
7359 const fltSemantics &Sem) {
7360 APFloat F = CFP->getValueAPF();
7361 if (F.convert(Sem, APFloat::rmNearestTiesToEven) == APFloat::opOK)
7362 return ConstantFP::get(FPTy, F);
7363 return 0;
7364}
7365
7366/// LookThroughFPExtensions - If this is an fp extension instruction, look
7367/// through it until we get the source value.
7368static Value *LookThroughFPExtensions(Value *V) {
7369 if (Instruction *I = dyn_cast<Instruction>(V))
7370 if (I->getOpcode() == Instruction::FPExt)
7371 return LookThroughFPExtensions(I->getOperand(0));
7372
7373 // If this value is a constant, return the constant in the smallest FP type
7374 // that can accurately represent it. This allows us to turn
7375 // (float)((double)X+2.0) into x+2.0f.
7376 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
7377 if (CFP->getType() == Type::PPC_FP128Ty)
7378 return V; // No constant folding of this.
7379 // See if the value can be truncated to float and then reextended.
7380 if (Value *V = FitsInFPType(CFP, Type::FloatTy, APFloat::IEEEsingle))
7381 return V;
7382 if (CFP->getType() == Type::DoubleTy)
7383 return V; // Won't shrink.
7384 if (Value *V = FitsInFPType(CFP, Type::DoubleTy, APFloat::IEEEdouble))
7385 return V;
7386 // Don't try to shrink to various long double types.
7387 }
7388
7389 return V;
7390}
7391
7392Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
7393 if (Instruction *I = commonCastTransforms(CI))
7394 return I;
7395
7396 // If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are
7397 // smaller than the destination type, we can eliminate the truncate by doing
7398 // the add as the smaller type. This applies to add/sub/mul/div as well as
7399 // many builtins (sqrt, etc).
7400 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
7401 if (OpI && OpI->hasOneUse()) {
7402 switch (OpI->getOpcode()) {
7403 default: break;
7404 case Instruction::Add:
7405 case Instruction::Sub:
7406 case Instruction::Mul:
7407 case Instruction::FDiv:
7408 case Instruction::FRem:
7409 const Type *SrcTy = OpI->getType();
7410 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
7411 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
7412 if (LHSTrunc->getType() != SrcTy &&
7413 RHSTrunc->getType() != SrcTy) {
7414 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
7415 // If the source types were both smaller than the destination type of
7416 // the cast, do this xform.
7417 if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
7418 RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
7419 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
7420 CI.getType(), CI);
7421 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
7422 CI.getType(), CI);
7423 return BinaryOperator::create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
7424 }
7425 }
7426 break;
7427 }
7428 }
7429 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007430}
7431
7432Instruction *InstCombiner::visitFPExt(CastInst &CI) {
7433 return commonCastTransforms(CI);
7434}
7435
7436Instruction *InstCombiner::visitFPToUI(CastInst &CI) {
Reid Spencer44c030a2006-11-30 23:13:36 +00007437 return commonCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007438}
7439
7440Instruction *InstCombiner::visitFPToSI(CastInst &CI) {
Reid Spencer44c030a2006-11-30 23:13:36 +00007441 return commonCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007442}
7443
7444Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
7445 return commonCastTransforms(CI);
7446}
7447
7448Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
7449 return commonCastTransforms(CI);
7450}
7451
7452Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007453 return commonPointerCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007454}
7455
Chris Lattnerf9d9e452008-01-08 07:23:51 +00007456Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
7457 if (Instruction *I = commonCastTransforms(CI))
7458 return I;
7459
7460 const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
7461 if (!DestPointee->isSized()) return 0;
7462
7463 // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
7464 ConstantInt *Cst;
7465 Value *X;
7466 if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
7467 m_ConstantInt(Cst)))) {
7468 // If the source and destination operands have the same type, see if this
7469 // is a single-index GEP.
7470 if (X->getType() == CI.getType()) {
7471 // Get the size of the pointee type.
Bill Wendlingb9d4f8d2008-03-14 05:12:19 +00007472 uint64_t Size = TD->getABITypeSize(DestPointee);
Chris Lattnerf9d9e452008-01-08 07:23:51 +00007473
7474 // Convert the constant to intptr type.
7475 APInt Offset = Cst->getValue();
7476 Offset.sextOrTrunc(TD->getPointerSizeInBits());
7477
7478 // If Offset is evenly divisible by Size, we can do this xform.
7479 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7480 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
7481 return new GetElementPtrInst(X, ConstantInt::get(Offset));
7482 }
7483 }
7484 // TODO: Could handle other cases, e.g. where add is indexing into field of
7485 // struct etc.
7486 } else if (CI.getOperand(0)->hasOneUse() &&
7487 match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
7488 // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
7489 // "inttoptr+GEP" instead of "add+intptr".
7490
7491 // Get the size of the pointee type.
7492 uint64_t Size = TD->getABITypeSize(DestPointee);
7493
7494 // Convert the constant to intptr type.
7495 APInt Offset = Cst->getValue();
7496 Offset.sextOrTrunc(TD->getPointerSizeInBits());
7497
7498 // If Offset is evenly divisible by Size, we can do this xform.
7499 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7500 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
7501
7502 Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
7503 "tmp"), CI);
7504 return new GetElementPtrInst(P, ConstantInt::get(Offset), "tmp");
7505 }
7506 }
7507 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007508}
7509
Chris Lattnerd3e28342007-04-27 17:44:50 +00007510Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007511 // If the operands are integer typed then apply the integer transforms,
7512 // otherwise just apply the common ones.
7513 Value *Src = CI.getOperand(0);
7514 const Type *SrcTy = Src->getType();
7515 const Type *DestTy = CI.getType();
7516
Chris Lattner42a75512007-01-15 02:27:26 +00007517 if (SrcTy->isInteger() && DestTy->isInteger()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007518 if (Instruction *Result = commonIntCastTransforms(CI))
7519 return Result;
Chris Lattnerd3e28342007-04-27 17:44:50 +00007520 } else if (isa<PointerType>(SrcTy)) {
7521 if (Instruction *I = commonPointerCastTransforms(CI))
7522 return I;
Reid Spencer3da59db2006-11-27 01:05:10 +00007523 } else {
7524 if (Instruction *Result = commonCastTransforms(CI))
7525 return Result;
7526 }
7527
7528
7529 // Get rid of casts from one type to the same type. These are useless and can
7530 // be replaced by the operand.
7531 if (DestTy == Src->getType())
7532 return ReplaceInstUsesWith(CI, Src);
7533
Reid Spencer3da59db2006-11-27 01:05:10 +00007534 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007535 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
7536 const Type *DstElTy = DstPTy->getElementType();
7537 const Type *SrcElTy = SrcPTy->getElementType();
7538
7539 // If we are casting a malloc or alloca to a pointer to a type of the same
7540 // size, rewrite the allocation instruction to allocate the "right" type.
7541 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
7542 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
7543 return V;
7544
Chris Lattnerd717c182007-05-05 22:32:24 +00007545 // If the source and destination are pointers, and this cast is equivalent
7546 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
Chris Lattnerd3e28342007-04-27 17:44:50 +00007547 // This can enhance SROA and other transforms that want type-safe pointers.
7548 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
7549 unsigned NumZeros = 0;
7550 while (SrcElTy != DstElTy &&
7551 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
7552 SrcElTy->getNumContainedTypes() /* not "{}" */) {
7553 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
7554 ++NumZeros;
7555 }
Chris Lattner4e998b22004-09-29 05:07:12 +00007556
Chris Lattnerd3e28342007-04-27 17:44:50 +00007557 // If we found a path from the src to dest, create the getelementptr now.
7558 if (SrcElTy == DstElTy) {
7559 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Chuck Rose IIIc331d302007-09-05 20:36:41 +00007560 return new GetElementPtrInst(Src, Idxs.begin(), Idxs.end(), "",
7561 ((Instruction*) NULL));
Chris Lattner9fb92132006-04-12 18:09:35 +00007562 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007563 }
Chris Lattner24c8e382003-07-24 17:35:25 +00007564
Reid Spencer3da59db2006-11-27 01:05:10 +00007565 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
7566 if (SVI->hasOneUse()) {
7567 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
7568 // a bitconvert to a vector with the same # elts.
Reid Spencer9d6565a2007-02-15 02:26:10 +00007569 if (isa<VectorType>(DestTy) &&
7570 cast<VectorType>(DestTy)->getNumElements() ==
Reid Spencer3da59db2006-11-27 01:05:10 +00007571 SVI->getType()->getNumElements()) {
7572 CastInst *Tmp;
7573 // If either of the operands is a cast from CI.getType(), then
7574 // evaluating the shuffle in the casted destination's type will allow
7575 // us to eliminate at least one cast.
7576 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
7577 Tmp->getOperand(0)->getType() == DestTy) ||
7578 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
7579 Tmp->getOperand(0)->getType() == DestTy)) {
Reid Spencer17212df2006-12-12 09:18:51 +00007580 Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
7581 SVI->getOperand(0), DestTy, &CI);
7582 Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
7583 SVI->getOperand(1), DestTy, &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007584 // Return a new shuffle vector. Use the same element ID's, as we
7585 // know the vector types match #elts.
7586 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner01575b72006-05-25 23:24:33 +00007587 }
7588 }
7589 }
7590 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00007591 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00007592}
7593
Chris Lattnere576b912004-04-09 23:46:01 +00007594/// GetSelectFoldableOperands - We want to turn code that looks like this:
7595/// %C = or %A, %B
7596/// %D = select %cond, %C, %A
7597/// into:
7598/// %C = select %cond, %B, 0
7599/// %D = or %A, %C
7600///
7601/// Assuming that the specified instruction is an operand to the select, return
7602/// a bitmask indicating which operands of this instruction are foldable if they
7603/// equal the other incoming value of the select.
7604///
7605static unsigned GetSelectFoldableOperands(Instruction *I) {
7606 switch (I->getOpcode()) {
7607 case Instruction::Add:
7608 case Instruction::Mul:
7609 case Instruction::And:
7610 case Instruction::Or:
7611 case Instruction::Xor:
7612 return 3; // Can fold through either operand.
7613 case Instruction::Sub: // Can only fold on the amount subtracted.
7614 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencer3822ff52006-11-08 06:47:33 +00007615 case Instruction::LShr:
7616 case Instruction::AShr:
Misha Brukmanfd939082005-04-21 23:48:37 +00007617 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00007618 default:
7619 return 0; // Cannot fold
7620 }
7621}
7622
7623/// GetSelectFoldableConstant - For the same transformation as the previous
7624/// function, return the identity constant that goes into the select.
7625static Constant *GetSelectFoldableConstant(Instruction *I) {
7626 switch (I->getOpcode()) {
7627 default: assert(0 && "This cannot happen!"); abort();
7628 case Instruction::Add:
7629 case Instruction::Sub:
7630 case Instruction::Or:
7631 case Instruction::Xor:
Chris Lattnere576b912004-04-09 23:46:01 +00007632 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00007633 case Instruction::LShr:
7634 case Instruction::AShr:
Reid Spencer832254e2007-02-02 02:16:23 +00007635 return Constant::getNullValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00007636 case Instruction::And:
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00007637 return Constant::getAllOnesValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00007638 case Instruction::Mul:
7639 return ConstantInt::get(I->getType(), 1);
7640 }
7641}
7642
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007643/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
7644/// have the same opcode and only one use each. Try to simplify this.
7645Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
7646 Instruction *FI) {
7647 if (TI->getNumOperands() == 1) {
7648 // If this is a non-volatile load or a cast from the same type,
7649 // merge.
Reid Spencer3da59db2006-11-27 01:05:10 +00007650 if (TI->isCast()) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007651 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
7652 return 0;
7653 } else {
7654 return 0; // unknown unary op.
7655 }
Misha Brukmanfd939082005-04-21 23:48:37 +00007656
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007657 // Fold this by inserting a select from the input values.
7658 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
7659 FI->getOperand(0), SI.getName()+".v");
7660 InsertNewInstBefore(NewSI, SI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007661 return CastInst::create(Instruction::CastOps(TI->getOpcode()), NewSI,
7662 TI->getType());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007663 }
7664
Reid Spencer832254e2007-02-02 02:16:23 +00007665 // Only handle binary operators here.
7666 if (!isa<BinaryOperator>(TI))
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007667 return 0;
7668
7669 // Figure out if the operations have any operands in common.
7670 Value *MatchOp, *OtherOpT, *OtherOpF;
7671 bool MatchIsOpZero;
7672 if (TI->getOperand(0) == FI->getOperand(0)) {
7673 MatchOp = TI->getOperand(0);
7674 OtherOpT = TI->getOperand(1);
7675 OtherOpF = FI->getOperand(1);
7676 MatchIsOpZero = true;
7677 } else if (TI->getOperand(1) == FI->getOperand(1)) {
7678 MatchOp = TI->getOperand(1);
7679 OtherOpT = TI->getOperand(0);
7680 OtherOpF = FI->getOperand(0);
7681 MatchIsOpZero = false;
7682 } else if (!TI->isCommutative()) {
7683 return 0;
7684 } else if (TI->getOperand(0) == FI->getOperand(1)) {
7685 MatchOp = TI->getOperand(0);
7686 OtherOpT = TI->getOperand(1);
7687 OtherOpF = FI->getOperand(0);
7688 MatchIsOpZero = true;
7689 } else if (TI->getOperand(1) == FI->getOperand(0)) {
7690 MatchOp = TI->getOperand(1);
7691 OtherOpT = TI->getOperand(0);
7692 OtherOpF = FI->getOperand(1);
7693 MatchIsOpZero = true;
7694 } else {
7695 return 0;
7696 }
7697
7698 // If we reach here, they do have operations in common.
7699 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
7700 OtherOpF, SI.getName()+".v");
7701 InsertNewInstBefore(NewSI, SI);
7702
7703 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
7704 if (MatchIsOpZero)
7705 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
7706 else
7707 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007708 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00007709 assert(0 && "Shouldn't get here");
7710 return 0;
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007711}
7712
Chris Lattner3d69f462004-03-12 05:52:32 +00007713Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00007714 Value *CondVal = SI.getCondition();
7715 Value *TrueVal = SI.getTrueValue();
7716 Value *FalseVal = SI.getFalseValue();
7717
7718 // select true, X, Y -> X
7719 // select false, X, Y -> Y
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007720 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencer579dca12007-01-12 04:24:46 +00007721 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00007722
7723 // select C, X, X -> X
7724 if (TrueVal == FalseVal)
7725 return ReplaceInstUsesWith(SI, TrueVal);
7726
Chris Lattnere87597f2004-10-16 18:11:37 +00007727 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
7728 return ReplaceInstUsesWith(SI, FalseVal);
7729 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
7730 return ReplaceInstUsesWith(SI, TrueVal);
7731 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
7732 if (isa<Constant>(TrueVal))
7733 return ReplaceInstUsesWith(SI, TrueVal);
7734 else
7735 return ReplaceInstUsesWith(SI, FalseVal);
7736 }
7737
Reid Spencer4fe16d62007-01-11 18:21:29 +00007738 if (SI.getType() == Type::Int1Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00007739 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00007740 if (C->getZExtValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00007741 // Change: A = select B, true, C --> A = or B, C
Chris Lattner48595f12004-06-10 02:07:29 +00007742 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00007743 } else {
7744 // Change: A = select B, false, C --> A = and !B, C
7745 Value *NotCond =
7746 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
7747 "not."+CondVal->getName()), SI);
Chris Lattner48595f12004-06-10 02:07:29 +00007748 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00007749 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00007750 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00007751 if (C->getZExtValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00007752 // Change: A = select B, C, false --> A = and B, C
Chris Lattner48595f12004-06-10 02:07:29 +00007753 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00007754 } else {
7755 // Change: A = select B, C, true --> A = or !B, C
7756 Value *NotCond =
7757 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
7758 "not."+CondVal->getName()), SI);
Chris Lattner48595f12004-06-10 02:07:29 +00007759 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00007760 }
7761 }
Chris Lattnercfa59752007-11-25 21:27:53 +00007762
7763 // select a, b, a -> a&b
7764 // select a, a, b -> a|b
7765 if (CondVal == TrueVal)
7766 return BinaryOperator::createOr(CondVal, FalseVal);
7767 else if (CondVal == FalseVal)
7768 return BinaryOperator::createAnd(CondVal, TrueVal);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007769 }
Chris Lattner0c199a72004-04-08 04:43:23 +00007770
Chris Lattner2eefe512004-04-09 19:05:30 +00007771 // Selecting between two integer constants?
7772 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
7773 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattnerba417832007-04-11 06:12:58 +00007774 // select C, 1, 0 -> zext C to int
Reid Spencer2ec619a2007-03-23 21:24:59 +00007775 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007776 return CastInst::create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer2ec619a2007-03-23 21:24:59 +00007777 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattnerba417832007-04-11 06:12:58 +00007778 // select C, 0, 1 -> zext !C to int
Chris Lattner2eefe512004-04-09 19:05:30 +00007779 Value *NotCond =
7780 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00007781 "not."+CondVal->getName()), SI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007782 return CastInst::create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00007783 }
Chris Lattnerba417832007-04-11 06:12:58 +00007784
7785 // FIXME: Turn select 0/-1 and -1/0 into sext from condition!
Chris Lattner457dd822004-06-09 07:59:58 +00007786
Reid Spencere4d87aa2006-12-23 06:05:41 +00007787 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattnerb8456462006-09-20 04:44:59 +00007788
Reid Spencere4d87aa2006-12-23 06:05:41 +00007789 // (x <s 0) ? -1 : 0 -> ashr x, 31
Reid Spencer2ec619a2007-03-23 21:24:59 +00007790 if (TrueValC->isAllOnesValue() && FalseValC->isZero())
Chris Lattnerb8456462006-09-20 04:44:59 +00007791 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
Chris Lattnerba417832007-04-11 06:12:58 +00007792 if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
Chris Lattnerb8456462006-09-20 04:44:59 +00007793 // The comparison constant and the result are not neccessarily the
Reid Spencer3da59db2006-11-27 01:05:10 +00007794 // same width. Make an all-ones value by inserting a AShr.
Chris Lattnerb8456462006-09-20 04:44:59 +00007795 Value *X = IC->getOperand(0);
Zhou Sheng4351c642007-04-02 08:20:41 +00007796 uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
Reid Spencer832254e2007-02-02 02:16:23 +00007797 Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
7798 Instruction *SRA = BinaryOperator::create(Instruction::AShr, X,
7799 ShAmt, "ones");
Chris Lattnerb8456462006-09-20 04:44:59 +00007800 InsertNewInstBefore(SRA, SI);
7801
Reid Spencer3da59db2006-11-27 01:05:10 +00007802 // Finally, convert to the type of the select RHS. We figure out
7803 // if this requires a SExt, Trunc or BitCast based on the sizes.
7804 Instruction::CastOps opc = Instruction::BitCast;
Zhou Sheng4351c642007-04-02 08:20:41 +00007805 uint32_t SRASize = SRA->getType()->getPrimitiveSizeInBits();
7806 uint32_t SISize = SI.getType()->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00007807 if (SRASize < SISize)
7808 opc = Instruction::SExt;
7809 else if (SRASize > SISize)
7810 opc = Instruction::Trunc;
7811 return CastInst::create(opc, SRA, SI.getType());
Chris Lattnerb8456462006-09-20 04:44:59 +00007812 }
7813 }
7814
7815
7816 // If one of the constants is zero (we know they can't both be) and we
Chris Lattnerba417832007-04-11 06:12:58 +00007817 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattnerb8456462006-09-20 04:44:59 +00007818 // non-constant value, eliminate this whole mess. This corresponds to
7819 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer2ec619a2007-03-23 21:24:59 +00007820 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattner65b72ba2006-09-18 04:22:48 +00007821 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00007822 cast<Constant>(IC->getOperand(1))->isNullValue())
7823 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
7824 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00007825 isa<ConstantInt>(ICA->getOperand(1)) &&
7826 (ICA->getOperand(1) == TrueValC ||
7827 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00007828 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
7829 // Okay, now we know that everything is set up, we just don't
Reid Spencere4d87aa2006-12-23 06:05:41 +00007830 // know whether we have a icmp_ne or icmp_eq and whether the
7831 // true or false val is the zero.
Reid Spencer2ec619a2007-03-23 21:24:59 +00007832 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencere4d87aa2006-12-23 06:05:41 +00007833 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner457dd822004-06-09 07:59:58 +00007834 Value *V = ICA;
7835 if (ShouldNotVal)
7836 V = InsertNewInstBefore(BinaryOperator::create(
7837 Instruction::Xor, V, ICA->getOperand(1)), SI);
7838 return ReplaceInstUsesWith(SI, V);
7839 }
Chris Lattnerb8456462006-09-20 04:44:59 +00007840 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00007841 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00007842
7843 // See if we are selecting two values based on a comparison of the two values.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007844 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
7845 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattnerd76956d2004-04-10 22:21:27 +00007846 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen5a2174f2007-10-03 17:45:27 +00007847 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
7848 // This is not safe in general for floating point:
7849 // consider X== -0, Y== +0.
7850 // It becomes safe if either operand is a nonzero constant.
7851 ConstantFP *CFPt, *CFPf;
7852 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
7853 !CFPt->getValueAPF().isZero()) ||
7854 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
7855 !CFPf->getValueAPF().isZero()))
Chris Lattnerd76956d2004-04-10 22:21:27 +00007856 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen5a2174f2007-10-03 17:45:27 +00007857 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00007858 // Transform (X != Y) ? X : Y -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00007859 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattnerd76956d2004-04-10 22:21:27 +00007860 return ReplaceInstUsesWith(SI, TrueVal);
7861 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7862
Reid Spencere4d87aa2006-12-23 06:05:41 +00007863 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattnerd76956d2004-04-10 22:21:27 +00007864 // Transform (X == Y) ? Y : X -> X
Dale Johannesen5a2174f2007-10-03 17:45:27 +00007865 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
7866 // This is not safe in general for floating point:
7867 // consider X== -0, Y== +0.
7868 // It becomes safe if either operand is a nonzero constant.
7869 ConstantFP *CFPt, *CFPf;
7870 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
7871 !CFPt->getValueAPF().isZero()) ||
7872 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
7873 !CFPf->getValueAPF().isZero()))
7874 return ReplaceInstUsesWith(SI, FalseVal);
7875 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00007876 // Transform (X != Y) ? Y : X -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00007877 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
7878 return ReplaceInstUsesWith(SI, TrueVal);
7879 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7880 }
7881 }
7882
7883 // See if we are selecting two values based on a comparison of the two values.
7884 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
7885 if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
7886 // Transform (X == Y) ? X : Y -> Y
7887 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
7888 return ReplaceInstUsesWith(SI, FalseVal);
7889 // Transform (X != Y) ? X : Y -> X
7890 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
7891 return ReplaceInstUsesWith(SI, TrueVal);
7892 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7893
7894 } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
7895 // Transform (X == Y) ? Y : X -> X
7896 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
7897 return ReplaceInstUsesWith(SI, FalseVal);
7898 // Transform (X != Y) ? Y : X -> Y
7899 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
Chris Lattnerfbede522004-04-11 01:39:19 +00007900 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerd76956d2004-04-10 22:21:27 +00007901 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7902 }
7903 }
Misha Brukmanfd939082005-04-21 23:48:37 +00007904
Chris Lattner87875da2005-01-13 22:52:24 +00007905 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
7906 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
7907 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattner87875da2005-01-13 22:52:24 +00007908 Instruction *AddOp = 0, *SubOp = 0;
7909
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007910 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
7911 if (TI->getOpcode() == FI->getOpcode())
7912 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
7913 return IV;
7914
7915 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
7916 // even legal for FP.
Chris Lattner87875da2005-01-13 22:52:24 +00007917 if (TI->getOpcode() == Instruction::Sub &&
7918 FI->getOpcode() == Instruction::Add) {
7919 AddOp = FI; SubOp = TI;
7920 } else if (FI->getOpcode() == Instruction::Sub &&
7921 TI->getOpcode() == Instruction::Add) {
7922 AddOp = TI; SubOp = FI;
7923 }
7924
7925 if (AddOp) {
7926 Value *OtherAddOp = 0;
7927 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
7928 OtherAddOp = AddOp->getOperand(1);
7929 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
7930 OtherAddOp = AddOp->getOperand(0);
7931 }
7932
7933 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00007934 // So at this point we know we have (Y -> OtherAddOp):
7935 // select C, (add X, Y), (sub X, Z)
7936 Value *NegVal; // Compute -Z
7937 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
7938 NegVal = ConstantExpr::getNeg(C);
7939 } else {
7940 NegVal = InsertNewInstBefore(
7941 BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00007942 }
Chris Lattner97f37a42006-02-24 18:05:58 +00007943
7944 Value *NewTrueOp = OtherAddOp;
7945 Value *NewFalseOp = NegVal;
7946 if (AddOp != TI)
7947 std::swap(NewTrueOp, NewFalseOp);
7948 Instruction *NewSel =
7949 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
7950
7951 NewSel = InsertNewInstBefore(NewSel, SI);
7952 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00007953 }
7954 }
7955 }
Misha Brukmanfd939082005-04-21 23:48:37 +00007956
Chris Lattnere576b912004-04-09 23:46:01 +00007957 // See if we can fold the select into one of our operands.
Chris Lattner42a75512007-01-15 02:27:26 +00007958 if (SI.getType()->isInteger()) {
Chris Lattnere576b912004-04-09 23:46:01 +00007959 // See the comment above GetSelectFoldableOperands for a description of the
7960 // transformation we are doing here.
7961 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
7962 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
7963 !isa<Constant>(FalseVal))
7964 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
7965 unsigned OpToFold = 0;
7966 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
7967 OpToFold = 1;
7968 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
7969 OpToFold = 2;
7970 }
7971
7972 if (OpToFold) {
7973 Constant *C = GetSelectFoldableConstant(TVI);
Chris Lattnere576b912004-04-09 23:46:01 +00007974 Instruction *NewSel =
Chris Lattner6934a042007-02-11 01:23:03 +00007975 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C);
Chris Lattnere576b912004-04-09 23:46:01 +00007976 InsertNewInstBefore(NewSel, SI);
Chris Lattner6934a042007-02-11 01:23:03 +00007977 NewSel->takeName(TVI);
Chris Lattnere576b912004-04-09 23:46:01 +00007978 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
7979 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
Chris Lattnere576b912004-04-09 23:46:01 +00007980 else {
7981 assert(0 && "Unknown instruction!!");
7982 }
7983 }
7984 }
Chris Lattnera96879a2004-09-29 17:40:11 +00007985
Chris Lattnere576b912004-04-09 23:46:01 +00007986 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
7987 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
7988 !isa<Constant>(TrueVal))
7989 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
7990 unsigned OpToFold = 0;
7991 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
7992 OpToFold = 1;
7993 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
7994 OpToFold = 2;
7995 }
7996
7997 if (OpToFold) {
7998 Constant *C = GetSelectFoldableConstant(FVI);
Chris Lattnere576b912004-04-09 23:46:01 +00007999 Instruction *NewSel =
Chris Lattner6934a042007-02-11 01:23:03 +00008000 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold));
Chris Lattnere576b912004-04-09 23:46:01 +00008001 InsertNewInstBefore(NewSel, SI);
Chris Lattner6934a042007-02-11 01:23:03 +00008002 NewSel->takeName(FVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008003 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
8004 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
Reid Spencer832254e2007-02-02 02:16:23 +00008005 else
Chris Lattnere576b912004-04-09 23:46:01 +00008006 assert(0 && "Unknown instruction!!");
Chris Lattnere576b912004-04-09 23:46:01 +00008007 }
8008 }
8009 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00008010
8011 if (BinaryOperator::isNot(CondVal)) {
8012 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
8013 SI.setOperand(1, FalseVal);
8014 SI.setOperand(2, TrueVal);
8015 return &SI;
8016 }
8017
Chris Lattner3d69f462004-03-12 05:52:32 +00008018 return 0;
8019}
8020
Chris Lattnerf2369f22007-08-09 19:05:49 +00008021/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
8022/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
8023/// and it is more than the alignment of the ultimate object, see if we can
8024/// increase the alignment of the ultimate object, making this check succeed.
8025static unsigned GetOrEnforceKnownAlignment(Value *V, TargetData *TD,
8026 unsigned PrefAlign = 0) {
Chris Lattner95a959d2006-03-06 20:18:44 +00008027 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
8028 unsigned Align = GV->getAlignment();
Andrew Lenharthb410df92007-11-08 18:45:15 +00008029 if (Align == 0 && TD && GV->getType()->getElementType()->isSized())
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00008030 Align = TD->getPrefTypeAlignment(GV->getType()->getElementType());
Chris Lattnerf2369f22007-08-09 19:05:49 +00008031
8032 // If there is a large requested alignment and we can, bump up the alignment
8033 // of the global.
8034 if (PrefAlign > Align && GV->hasInitializer()) {
8035 GV->setAlignment(PrefAlign);
8036 Align = PrefAlign;
8037 }
Chris Lattner95a959d2006-03-06 20:18:44 +00008038 return Align;
8039 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
8040 unsigned Align = AI->getAlignment();
8041 if (Align == 0 && TD) {
8042 if (isa<AllocaInst>(AI))
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00008043 Align = TD->getPrefTypeAlignment(AI->getType()->getElementType());
Chris Lattner95a959d2006-03-06 20:18:44 +00008044 else if (isa<MallocInst>(AI)) {
8045 // Malloc returns maximally aligned memory.
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00008046 Align = TD->getABITypeAlignment(AI->getType()->getElementType());
Chris Lattner58092e32007-01-20 22:35:55 +00008047 Align =
8048 std::max(Align,
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00008049 (unsigned)TD->getABITypeAlignment(Type::DoubleTy));
Chris Lattner58092e32007-01-20 22:35:55 +00008050 Align =
8051 std::max(Align,
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00008052 (unsigned)TD->getABITypeAlignment(Type::Int64Ty));
Chris Lattner95a959d2006-03-06 20:18:44 +00008053 }
8054 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00008055
8056 // If there is a requested alignment and if this is an alloca, round up. We
8057 // don't do this for malloc, because some systems can't respect the request.
8058 if (PrefAlign > Align && isa<AllocaInst>(AI)) {
8059 AI->setAlignment(PrefAlign);
8060 Align = PrefAlign;
8061 }
Chris Lattner95a959d2006-03-06 20:18:44 +00008062 return Align;
Reid Spencer3da59db2006-11-27 01:05:10 +00008063 } else if (isa<BitCastInst>(V) ||
Chris Lattner51c26e92006-03-07 01:28:57 +00008064 (isa<ConstantExpr>(V) &&
Reid Spencer3da59db2006-11-27 01:05:10 +00008065 cast<ConstantExpr>(V)->getOpcode() == Instruction::BitCast)) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00008066 return GetOrEnforceKnownAlignment(cast<User>(V)->getOperand(0),
8067 TD, PrefAlign);
Chris Lattner9bc14642007-04-28 00:57:34 +00008068 } else if (User *GEPI = dyn_castGetElementPtr(V)) {
Chris Lattner95a959d2006-03-06 20:18:44 +00008069 // If all indexes are zero, it is just the alignment of the base pointer.
8070 bool AllZeroOperands = true;
8071 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
8072 if (!isa<Constant>(GEPI->getOperand(i)) ||
8073 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
8074 AllZeroOperands = false;
8075 break;
8076 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00008077
8078 if (AllZeroOperands) {
8079 // Treat this like a bitcast.
8080 return GetOrEnforceKnownAlignment(GEPI->getOperand(0), TD, PrefAlign);
8081 }
8082
8083 unsigned BaseAlignment = GetOrEnforceKnownAlignment(GEPI->getOperand(0),TD);
8084 if (BaseAlignment == 0) return 0;
8085
Chris Lattner95a959d2006-03-06 20:18:44 +00008086 // Otherwise, if the base alignment is >= the alignment we expect for the
8087 // base pointer type, then we know that the resultant pointer is aligned at
8088 // least as much as its type requires.
8089 if (!TD) return 0;
8090
8091 const Type *BasePtrTy = GEPI->getOperand(0)->getType();
Chris Lattner58092e32007-01-20 22:35:55 +00008092 const PointerType *PtrTy = cast<PointerType>(BasePtrTy);
Lauro Ramos Venancioc7d11142007-07-31 20:13:21 +00008093 unsigned Align = TD->getABITypeAlignment(PtrTy->getElementType());
8094 if (Align <= BaseAlignment) {
Chris Lattner51c26e92006-03-07 01:28:57 +00008095 const Type *GEPTy = GEPI->getType();
Chris Lattner58092e32007-01-20 22:35:55 +00008096 const PointerType *GEPPtrTy = cast<PointerType>(GEPTy);
Lauro Ramos Venancioc7d11142007-07-31 20:13:21 +00008097 Align = std::min(Align, (unsigned)
8098 TD->getABITypeAlignment(GEPPtrTy->getElementType()));
8099 return Align;
Chris Lattner51c26e92006-03-07 01:28:57 +00008100 }
Chris Lattner95a959d2006-03-06 20:18:44 +00008101 return 0;
8102 }
8103 return 0;
8104}
8105
Chris Lattnerf497b022008-01-13 23:50:23 +00008106Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
8107 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1), TD);
8108 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2), TD);
8109 unsigned MinAlign = std::min(DstAlign, SrcAlign);
8110 unsigned CopyAlign = MI->getAlignment()->getZExtValue();
8111
8112 if (CopyAlign < MinAlign) {
8113 MI->setAlignment(ConstantInt::get(Type::Int32Ty, MinAlign));
8114 return MI;
8115 }
8116
8117 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
8118 // load/store.
8119 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
8120 if (MemOpLength == 0) return 0;
8121
Chris Lattner37ac6082008-01-14 00:28:35 +00008122 // Source and destination pointer types are always "i8*" for intrinsic. See
8123 // if the size is something we can handle with a single primitive load/store.
8124 // A single load+store correctly handles overlapping memory in the memmove
8125 // case.
Chris Lattnerf497b022008-01-13 23:50:23 +00008126 unsigned Size = MemOpLength->getZExtValue();
8127 if (Size == 0 || Size > 8 || (Size&(Size-1)))
Chris Lattner37ac6082008-01-14 00:28:35 +00008128 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattnerf497b022008-01-13 23:50:23 +00008129
Chris Lattner37ac6082008-01-14 00:28:35 +00008130 // Use an integer load+store unless we can find something better.
Chris Lattnerf497b022008-01-13 23:50:23 +00008131 Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
Chris Lattner37ac6082008-01-14 00:28:35 +00008132
8133 // Memcpy forces the use of i8* for the source and destination. That means
8134 // that if you're using memcpy to move one double around, you'll get a cast
8135 // from double* to i8*. We'd much rather use a double load+store rather than
8136 // an i64 load+store, here because this improves the odds that the source or
8137 // dest address will be promotable. See if we can find a better type than the
8138 // integer datatype.
8139 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
8140 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
8141 if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
8142 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
8143 // down through these levels if so.
8144 while (!SrcETy->isFirstClassType()) {
8145 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
8146 if (STy->getNumElements() == 1)
8147 SrcETy = STy->getElementType(0);
8148 else
8149 break;
8150 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
8151 if (ATy->getNumElements() == 1)
8152 SrcETy = ATy->getElementType();
8153 else
8154 break;
8155 } else
8156 break;
8157 }
8158
8159 if (SrcETy->isFirstClassType())
8160 NewPtrTy = PointerType::getUnqual(SrcETy);
8161 }
8162 }
8163
8164
Chris Lattnerf497b022008-01-13 23:50:23 +00008165 // If the memcpy/memmove provides better alignment info than we can
8166 // infer, use it.
8167 SrcAlign = std::max(SrcAlign, CopyAlign);
8168 DstAlign = std::max(DstAlign, CopyAlign);
8169
8170 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
8171 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
Chris Lattner37ac6082008-01-14 00:28:35 +00008172 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
8173 InsertNewInstBefore(L, *MI);
8174 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
8175
8176 // Set the size of the copy to 0, it will be deleted on the next iteration.
8177 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
8178 return MI;
Chris Lattnerf497b022008-01-13 23:50:23 +00008179}
Chris Lattner3d69f462004-03-12 05:52:32 +00008180
Chris Lattner8b0ea312006-01-13 20:11:04 +00008181/// visitCallInst - CallInst simplification. This mostly only handles folding
8182/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
8183/// the heavy lifting.
8184///
Chris Lattner9fe38862003-06-19 17:00:31 +00008185Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattner8b0ea312006-01-13 20:11:04 +00008186 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
8187 if (!II) return visitCallSite(&CI);
8188
Chris Lattner7bcc0e72004-02-28 05:22:00 +00008189 // Intrinsics cannot occur in an invoke, so handle them here instead of in
8190 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00008191 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00008192 bool Changed = false;
8193
8194 // memmove/cpy/set of zero bytes is a noop.
8195 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
8196 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
8197
Chris Lattner35b9e482004-10-12 04:52:52 +00008198 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +00008199 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +00008200 // Replace the instruction with just byte operations. We would
8201 // transform other cases to loads/stores, but we don't know if
8202 // alignment is sufficient.
8203 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00008204 }
8205
Chris Lattner35b9e482004-10-12 04:52:52 +00008206 // If we have a memmove and the source operation is a constant global,
8207 // then the source and dest pointers can't alias, so we can change this
8208 // into a call to memcpy.
Chris Lattnerf497b022008-01-13 23:50:23 +00008209 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00008210 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
8211 if (GVSrc->isConstant()) {
8212 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner6d0339d2008-01-13 22:23:22 +00008213 Intrinsic::ID MemCpyID;
8214 if (CI.getOperand(3)->getType() == Type::Int32Ty)
8215 MemCpyID = Intrinsic::memcpy_i32;
Chris Lattner21959392006-03-03 01:34:17 +00008216 else
Chris Lattner6d0339d2008-01-13 22:23:22 +00008217 MemCpyID = Intrinsic::memcpy_i64;
8218 CI.setOperand(0, Intrinsic::getDeclaration(M, MemCpyID));
Chris Lattner35b9e482004-10-12 04:52:52 +00008219 Changed = true;
8220 }
Chris Lattner95a959d2006-03-06 20:18:44 +00008221 }
Chris Lattner35b9e482004-10-12 04:52:52 +00008222
Chris Lattner95a959d2006-03-06 20:18:44 +00008223 // If we can determine a pointer alignment that is bigger than currently
8224 // set, update the alignment.
8225 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
Chris Lattnerf497b022008-01-13 23:50:23 +00008226 if (Instruction *I = SimplifyMemTransfer(MI))
8227 return I;
Chris Lattner95a959d2006-03-06 20:18:44 +00008228 } else if (isa<MemSetInst>(MI)) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00008229 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest(), TD);
Reid Spencerb83eb642006-10-20 07:07:24 +00008230 if (MI->getAlignment()->getZExtValue() < Alignment) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00008231 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
Chris Lattner95a959d2006-03-06 20:18:44 +00008232 Changed = true;
8233 }
8234 }
8235
Chris Lattner8b0ea312006-01-13 20:11:04 +00008236 if (Changed) return II;
Chris Lattnera728ddc2006-01-13 21:28:09 +00008237 } else {
8238 switch (II->getIntrinsicID()) {
8239 default: break;
Chris Lattner82ed58f2006-04-02 05:30:25 +00008240 case Intrinsic::ppc_altivec_lvx:
8241 case Intrinsic::ppc_altivec_lvxl:
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00008242 case Intrinsic::x86_sse_loadu_ps:
8243 case Intrinsic::x86_sse2_loadu_pd:
8244 case Intrinsic::x86_sse2_loadu_dq:
8245 // Turn PPC lvx -> load if the pointer is known aligned.
8246 // Turn X86 loadups -> load if the pointer is known aligned.
Chris Lattnerf2369f22007-08-09 19:05:49 +00008247 if (GetOrEnforceKnownAlignment(II->getOperand(1), TD, 16) >= 16) {
Chris Lattner6d0339d2008-01-13 22:23:22 +00008248 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
8249 PointerType::getUnqual(II->getType()),
8250 CI);
Chris Lattner82ed58f2006-04-02 05:30:25 +00008251 return new LoadInst(Ptr);
8252 }
8253 break;
8254 case Intrinsic::ppc_altivec_stvx:
8255 case Intrinsic::ppc_altivec_stvxl:
8256 // Turn stvx -> store if the pointer is known aligned.
Chris Lattnerf2369f22007-08-09 19:05:49 +00008257 if (GetOrEnforceKnownAlignment(II->getOperand(2), TD, 16) >= 16) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00008258 const Type *OpPtrTy =
8259 PointerType::getUnqual(II->getOperand(1)->getType());
Chris Lattner6d0339d2008-01-13 22:23:22 +00008260 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
Chris Lattner82ed58f2006-04-02 05:30:25 +00008261 return new StoreInst(II->getOperand(1), Ptr);
8262 }
8263 break;
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00008264 case Intrinsic::x86_sse_storeu_ps:
8265 case Intrinsic::x86_sse2_storeu_pd:
8266 case Intrinsic::x86_sse2_storeu_dq:
8267 case Intrinsic::x86_sse2_storel_dq:
8268 // Turn X86 storeu -> store if the pointer is known aligned.
Chris Lattnerf2369f22007-08-09 19:05:49 +00008269 if (GetOrEnforceKnownAlignment(II->getOperand(1), TD, 16) >= 16) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00008270 const Type *OpPtrTy =
8271 PointerType::getUnqual(II->getOperand(2)->getType());
Chris Lattner6d0339d2008-01-13 22:23:22 +00008272 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00008273 return new StoreInst(II->getOperand(2), Ptr);
8274 }
8275 break;
Chris Lattner867b99f2006-10-05 06:55:50 +00008276
8277 case Intrinsic::x86_sse_cvttss2si: {
8278 // These intrinsics only demands the 0th element of its input vector. If
8279 // we can simplify the input based on that, do so now.
8280 uint64_t UndefElts;
8281 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
8282 UndefElts)) {
8283 II->setOperand(1, V);
8284 return II;
8285 }
8286 break;
8287 }
8288
Chris Lattnere2ed0572006-04-06 19:19:17 +00008289 case Intrinsic::ppc_altivec_vperm:
8290 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
Reid Spencer9d6565a2007-02-15 02:26:10 +00008291 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
Chris Lattnere2ed0572006-04-06 19:19:17 +00008292 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
8293
8294 // Check that all of the elements are integer constants or undefs.
8295 bool AllEltsOk = true;
8296 for (unsigned i = 0; i != 16; ++i) {
8297 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
8298 !isa<UndefValue>(Mask->getOperand(i))) {
8299 AllEltsOk = false;
8300 break;
8301 }
8302 }
8303
8304 if (AllEltsOk) {
8305 // Cast the input vectors to byte vectors.
Chris Lattner6d0339d2008-01-13 22:23:22 +00008306 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
8307 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
Chris Lattnere2ed0572006-04-06 19:19:17 +00008308 Value *Result = UndefValue::get(Op0->getType());
8309
8310 // Only extract each element once.
8311 Value *ExtractedElts[32];
8312 memset(ExtractedElts, 0, sizeof(ExtractedElts));
8313
8314 for (unsigned i = 0; i != 16; ++i) {
8315 if (isa<UndefValue>(Mask->getOperand(i)))
8316 continue;
Chris Lattnere34e9a22007-04-14 23:32:02 +00008317 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
Chris Lattnere2ed0572006-04-06 19:19:17 +00008318 Idx &= 31; // Match the hardware behavior.
8319
8320 if (ExtractedElts[Idx] == 0) {
8321 Instruction *Elt =
Chris Lattner867b99f2006-10-05 06:55:50 +00008322 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00008323 InsertNewInstBefore(Elt, CI);
8324 ExtractedElts[Idx] = Elt;
8325 }
8326
8327 // Insert this value into the result vector.
Chris Lattner867b99f2006-10-05 06:55:50 +00008328 Result = new InsertElementInst(Result, ExtractedElts[Idx], i,"tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00008329 InsertNewInstBefore(cast<Instruction>(Result), CI);
8330 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008331 return CastInst::create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00008332 }
8333 }
8334 break;
8335
Chris Lattnera728ddc2006-01-13 21:28:09 +00008336 case Intrinsic::stackrestore: {
8337 // If the save is right next to the restore, remove the restore. This can
8338 // happen when variable allocas are DCE'd.
8339 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
8340 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
8341 BasicBlock::iterator BI = SS;
8342 if (&*++BI == II)
8343 return EraseInstFromFunction(CI);
8344 }
8345 }
8346
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00008347 // Scan down this block to see if there is another stack restore in the
8348 // same block without an intervening call/alloca.
8349 BasicBlock::iterator BI = II;
Chris Lattnera728ddc2006-01-13 21:28:09 +00008350 TerminatorInst *TI = II->getParent()->getTerminator();
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00008351 bool CannotRemove = false;
8352 for (++BI; &*BI != TI; ++BI) {
8353 if (isa<AllocaInst>(BI)) {
8354 CannotRemove = true;
8355 break;
8356 }
8357 if (isa<CallInst>(BI)) {
8358 if (!isa<IntrinsicInst>(BI)) {
Chris Lattnera728ddc2006-01-13 21:28:09 +00008359 CannotRemove = true;
8360 break;
8361 }
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00008362 // If there is a stackrestore below this one, remove this one.
Chris Lattnera728ddc2006-01-13 21:28:09 +00008363 return EraseInstFromFunction(CI);
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00008364 }
Chris Lattnera728ddc2006-01-13 21:28:09 +00008365 }
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00008366
8367 // If the stack restore is in a return/unwind block and if there are no
8368 // allocas or calls between the restore and the return, nuke the restore.
8369 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
8370 return EraseInstFromFunction(CI);
Chris Lattnera728ddc2006-01-13 21:28:09 +00008371 break;
8372 }
8373 }
Chris Lattner35b9e482004-10-12 04:52:52 +00008374 }
8375
Chris Lattner8b0ea312006-01-13 20:11:04 +00008376 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +00008377}
8378
8379// InvokeInst simplification
8380//
8381Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +00008382 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +00008383}
8384
Chris Lattnera44d8a22003-10-07 22:32:43 +00008385// visitCallSite - Improvements for call and invoke instructions.
8386//
8387Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +00008388 bool Changed = false;
8389
8390 // If the callee is a constexpr cast of a function, attempt to move the cast
8391 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +00008392 if (transformConstExprCastCall(CS)) return 0;
8393
Chris Lattner6c266db2003-10-07 22:54:13 +00008394 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +00008395
Chris Lattner08b22ec2005-05-13 07:09:09 +00008396 if (Function *CalleeF = dyn_cast<Function>(Callee))
8397 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
8398 Instruction *OldCall = CS.getInstruction();
8399 // If the call and callee calling conventions don't match, this call must
8400 // be unreachable, as the call is undefined.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008401 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00008402 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
8403 OldCall);
Chris Lattner08b22ec2005-05-13 07:09:09 +00008404 if (!OldCall->use_empty())
8405 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
8406 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
8407 return EraseInstFromFunction(*OldCall);
8408 return 0;
8409 }
8410
Chris Lattner17be6352004-10-18 02:59:09 +00008411 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
8412 // This instruction is not reachable, just remove it. We insert a store to
8413 // undef so that we know that this code is not reachable, despite the fact
8414 // that we can't modify the CFG here.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008415 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00008416 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
Chris Lattner17be6352004-10-18 02:59:09 +00008417 CS.getInstruction());
8418
8419 if (!CS.getInstruction()->use_empty())
8420 CS.getInstruction()->
8421 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
8422
8423 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
8424 // Don't break the CFG, insert a dummy cond branch.
8425 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008426 ConstantInt::getTrue(), II);
Chris Lattnere87597f2004-10-16 18:11:37 +00008427 }
Chris Lattner17be6352004-10-18 02:59:09 +00008428 return EraseInstFromFunction(*CS.getInstruction());
8429 }
Chris Lattnere87597f2004-10-16 18:11:37 +00008430
Duncan Sandscdb6d922007-09-17 10:26:40 +00008431 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
8432 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
8433 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
8434 return transformCallThroughTrampoline(CS);
8435
Chris Lattner6c266db2003-10-07 22:54:13 +00008436 const PointerType *PTy = cast<PointerType>(Callee->getType());
8437 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
8438 if (FTy->isVarArg()) {
8439 // See if we can optimize any arguments passed through the varargs area of
8440 // the call.
8441 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
8442 E = CS.arg_end(); I != E; ++I)
8443 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
8444 // If this cast does not effect the value passed through the varargs
8445 // area, we can eliminate the use of the cast.
8446 Value *Op = CI->getOperand(0);
Reid Spencer3da59db2006-11-27 01:05:10 +00008447 if (CI->isLosslessCast()) {
Chris Lattner6c266db2003-10-07 22:54:13 +00008448 *I = Op;
8449 Changed = true;
8450 }
8451 }
8452 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008453
Duncan Sandsf0c33542007-12-19 21:13:37 +00008454 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sandsece2c042007-12-16 15:51:49 +00008455 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsf0c33542007-12-19 21:13:37 +00008456 CS.setDoesNotThrow();
Duncan Sandsece2c042007-12-16 15:51:49 +00008457 Changed = true;
8458 }
8459
Chris Lattner6c266db2003-10-07 22:54:13 +00008460 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +00008461}
8462
Chris Lattner9fe38862003-06-19 17:00:31 +00008463// transformConstExprCastCall - If the callee is a constexpr cast of a function,
8464// attempt to move the cast to the arguments of the call/invoke.
8465//
8466bool InstCombiner::transformConstExprCastCall(CallSite CS) {
8467 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
8468 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +00008469 if (CE->getOpcode() != Instruction::BitCast ||
8470 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +00008471 return false;
Reid Spencer8863f182004-07-18 00:38:32 +00008472 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +00008473 Instruction *Caller = CS.getInstruction();
Chris Lattner58d74912008-03-12 17:45:29 +00008474 const PAListPtr &CallerPAL = CS.getParamAttrs();
Chris Lattner9fe38862003-06-19 17:00:31 +00008475
8476 // Okay, this is a cast from a function to a different type. Unless doing so
8477 // would cause a type conversion of one of our arguments, change this call to
8478 // be a direct call with arguments casted to the appropriate types.
8479 //
8480 const FunctionType *FT = Callee->getFunctionType();
8481 const Type *OldRetTy = Caller->getType();
8482
Devang Patel75e6f022008-03-11 18:04:06 +00008483 if (isa<StructType>(FT->getReturnType()))
8484 return false; // TODO: Handle multiple return values.
8485
Chris Lattnerf78616b2004-01-14 06:06:08 +00008486 // Check to see if we are changing the return type...
8487 if (OldRetTy != FT->getReturnType()) {
Reid Spencer5cbf9852007-01-30 20:08:39 +00008488 if (Callee->isDeclaration() && !Caller->use_empty() &&
Chris Lattner46013f42007-01-06 19:53:32 +00008489 // Conversion is ok if changing from pointer to int of same size.
8490 !(isa<PointerType>(FT->getReturnType()) &&
8491 TD->getIntPtrType() == OldRetTy))
Chris Lattnerec479922007-01-06 02:09:32 +00008492 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +00008493
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008494 if (!Caller->use_empty() &&
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008495 // void -> non-void is handled specially
Duncan Sandse1e520f2008-01-13 08:02:44 +00008496 FT->getReturnType() != Type::VoidTy &&
8497 !CastInst::isCastable(FT->getReturnType(), OldRetTy))
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008498 return false; // Cannot transform this return value.
8499
Chris Lattner58d74912008-03-12 17:45:29 +00008500 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
8501 ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
Duncan Sands6c3470e2008-01-07 17:16:06 +00008502 if (RAttrs & ParamAttr::typeIncompatible(FT->getReturnType()))
8503 return false; // Attribute not compatible with transformed value.
8504 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008505
Chris Lattnerf78616b2004-01-14 06:06:08 +00008506 // If the callsite is an invoke instruction, and the return value is used by
8507 // a PHI node in a successor, we cannot change the return type of the call
8508 // because there is no place to put the cast instruction (without breaking
8509 // the critical edge). Bail out in this case.
8510 if (!Caller->use_empty())
8511 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
8512 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
8513 UI != E; ++UI)
8514 if (PHINode *PN = dyn_cast<PHINode>(*UI))
8515 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00008516 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +00008517 return false;
8518 }
Chris Lattner9fe38862003-06-19 17:00:31 +00008519
8520 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
8521 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +00008522
Chris Lattner9fe38862003-06-19 17:00:31 +00008523 CallSite::arg_iterator AI = CS.arg_begin();
8524 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
8525 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +00008526 const Type *ActTy = (*AI)->getType();
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008527
8528 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008529 return false; // Cannot transform this parameter value.
8530
Chris Lattner58d74912008-03-12 17:45:29 +00008531 if (CallerPAL.getParamAttrs(i + 1) & ParamAttr::typeIncompatible(ParamTy))
8532 return false; // Attribute not compatible with transformed value.
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008533
Reid Spencer3da59db2006-11-27 01:05:10 +00008534 ConstantInt *c = dyn_cast<ConstantInt>(*AI);
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008535 // Some conversions are safe even if we do not have a body.
8536 // Either we can cast directly, or we can upconvert the argument
Chris Lattnerec479922007-01-06 02:09:32 +00008537 bool isConvertible = ActTy == ParamTy ||
Chris Lattner46013f42007-01-06 19:53:32 +00008538 (isa<PointerType>(ParamTy) && isa<PointerType>(ActTy)) ||
Chris Lattner42a75512007-01-15 02:27:26 +00008539 (ParamTy->isInteger() && ActTy->isInteger() &&
Reid Spencerabaa8ca2007-01-08 16:32:00 +00008540 ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()) ||
8541 (c && ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()
Zhou Sheng0fc50952007-03-25 05:01:29 +00008542 && c->getValue().isStrictlyPositive());
Reid Spencer5cbf9852007-01-30 20:08:39 +00008543 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +00008544 }
8545
8546 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +00008547 Callee->isDeclaration())
Chris Lattner58d74912008-03-12 17:45:29 +00008548 return false; // Do not delete arguments unless we have a function body.
Chris Lattner9fe38862003-06-19 17:00:31 +00008549
Chris Lattner58d74912008-03-12 17:45:29 +00008550 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
8551 !CallerPAL.isEmpty())
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008552 // In this case we have more arguments than the new function type, but we
Duncan Sandse1e520f2008-01-13 08:02:44 +00008553 // won't be dropping them. Check that these extra arguments have attributes
8554 // that are compatible with being a vararg call argument.
Chris Lattner58d74912008-03-12 17:45:29 +00008555 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
8556 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sandse1e520f2008-01-13 08:02:44 +00008557 break;
Chris Lattner58d74912008-03-12 17:45:29 +00008558 ParameterAttributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Duncan Sandse1e520f2008-01-13 08:02:44 +00008559 if (PAttrs & ParamAttr::VarArgsIncompatible)
8560 return false;
8561 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008562
Chris Lattner9fe38862003-06-19 17:00:31 +00008563 // Okay, we decided that this is a safe thing to do: go ahead and start
8564 // inserting cast instructions as necessary...
8565 std::vector<Value*> Args;
8566 Args.reserve(NumActualArgs);
Chris Lattner58d74912008-03-12 17:45:29 +00008567 SmallVector<ParamAttrsWithIndex, 8> attrVec;
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008568 attrVec.reserve(NumCommonArgs);
8569
8570 // Get any return attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00008571 ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008572
8573 // If the return value is not being used, the type may not be compatible
8574 // with the existing attributes. Wipe out any problematic attributes.
Duncan Sands6c3470e2008-01-07 17:16:06 +00008575 RAttrs &= ~ParamAttr::typeIncompatible(FT->getReturnType());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008576
8577 // Add the new return attributes.
8578 if (RAttrs)
8579 attrVec.push_back(ParamAttrsWithIndex::get(0, RAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +00008580
8581 AI = CS.arg_begin();
8582 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
8583 const Type *ParamTy = FT->getParamType(i);
8584 if ((*AI)->getType() == ParamTy) {
8585 Args.push_back(*AI);
8586 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +00008587 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +00008588 false, ParamTy, false);
Reid Spencer8a903db2006-12-18 08:47:13 +00008589 CastInst *NewCast = CastInst::create(opcode, *AI, ParamTy, "tmp");
Reid Spencer3da59db2006-11-27 01:05:10 +00008590 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner9fe38862003-06-19 17:00:31 +00008591 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008592
8593 // Add any parameter attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00008594 if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008595 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +00008596 }
8597
8598 // If the function takes more arguments than the call was taking, add them
8599 // now...
8600 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
8601 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
8602
8603 // If we are removing arguments to the function, emit an obnoxious warning...
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00008604 if (FT->getNumParams() < NumActualArgs) {
Chris Lattner9fe38862003-06-19 17:00:31 +00008605 if (!FT->isVarArg()) {
Bill Wendlinge8156192006-12-07 01:30:32 +00008606 cerr << "WARNING: While resolving call to function '"
8607 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +00008608 } else {
8609 // Add all of the arguments in their promoted form to the arg list...
8610 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
8611 const Type *PTy = getPromotedType((*AI)->getType());
8612 if (PTy != (*AI)->getType()) {
8613 // Must promote to pass through va_arg area!
Reid Spencerc5b206b2006-12-31 05:48:39 +00008614 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
8615 PTy, false);
Reid Spencer8a903db2006-12-18 08:47:13 +00008616 Instruction *Cast = CastInst::create(opcode, *AI, PTy, "tmp");
Chris Lattner9fe38862003-06-19 17:00:31 +00008617 InsertNewInstBefore(Cast, *Caller);
8618 Args.push_back(Cast);
8619 } else {
8620 Args.push_back(*AI);
8621 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008622
Duncan Sandse1e520f2008-01-13 08:02:44 +00008623 // Add any parameter attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00008624 if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
Duncan Sandse1e520f2008-01-13 08:02:44 +00008625 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
8626 }
Chris Lattner9fe38862003-06-19 17:00:31 +00008627 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00008628 }
Chris Lattner9fe38862003-06-19 17:00:31 +00008629
8630 if (FT->getReturnType() == Type::VoidTy)
Chris Lattner6934a042007-02-11 01:23:03 +00008631 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +00008632
Chris Lattner58d74912008-03-12 17:45:29 +00008633 const PAListPtr &NewCallerPAL = PAListPtr::get(attrVec.begin(),attrVec.end());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008634
Chris Lattner9fe38862003-06-19 17:00:31 +00008635 Instruction *NC;
8636 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00008637 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
David Greenef1355a52007-08-27 19:04:21 +00008638 Args.begin(), Args.end(), Caller->getName(), Caller);
Reid Spencered3fa852007-07-30 19:53:57 +00008639 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008640 cast<InvokeInst>(NC)->setParamAttrs(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +00008641 } else {
Chris Lattner684b22d2007-08-02 16:53:43 +00008642 NC = new CallInst(Callee, Args.begin(), Args.end(),
8643 Caller->getName(), Caller);
Duncan Sandsdc024672007-11-27 13:23:08 +00008644 CallInst *CI = cast<CallInst>(Caller);
8645 if (CI->isTailCall())
Chris Lattnera9e92112005-05-06 06:48:21 +00008646 cast<CallInst>(NC)->setTailCall();
Duncan Sandsdc024672007-11-27 13:23:08 +00008647 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008648 cast<CallInst>(NC)->setParamAttrs(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +00008649 }
8650
Chris Lattner6934a042007-02-11 01:23:03 +00008651 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +00008652 Value *NV = NC;
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008653 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Chris Lattner9fe38862003-06-19 17:00:31 +00008654 if (NV->getType() != Type::VoidTy) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00008655 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008656 OldRetTy, false);
8657 NV = NC = CastInst::create(opcode, NC, OldRetTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +00008658
8659 // If this is an invoke instruction, we should insert it after the first
8660 // non-phi, instruction in the normal successor block.
8661 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
8662 BasicBlock::iterator I = II->getNormalDest()->begin();
8663 while (isa<PHINode>(I)) ++I;
8664 InsertNewInstBefore(NC, *I);
8665 } else {
8666 // Otherwise, it's a call, just insert cast right after the call instr
8667 InsertNewInstBefore(NC, *Caller);
8668 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00008669 AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00008670 } else {
Chris Lattnerc30bda72004-10-17 21:22:38 +00008671 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +00008672 }
8673 }
8674
8675 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
8676 Caller->replaceAllUsesWith(NV);
Chris Lattnerf22a5c62007-03-02 19:59:19 +00008677 Caller->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +00008678 RemoveFromWorkList(Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00008679 return true;
8680}
8681
Duncan Sandscdb6d922007-09-17 10:26:40 +00008682// transformCallThroughTrampoline - Turn a call to a function created by the
8683// init_trampoline intrinsic into a direct call to the underlying function.
8684//
8685Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
8686 Value *Callee = CS.getCalledValue();
8687 const PointerType *PTy = cast<PointerType>(Callee->getType());
8688 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Chris Lattner58d74912008-03-12 17:45:29 +00008689 const PAListPtr &Attrs = CS.getParamAttrs();
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008690
8691 // If the call already has the 'nest' attribute somewhere then give up -
8692 // otherwise 'nest' would occur twice after splicing in the chain.
Chris Lattner58d74912008-03-12 17:45:29 +00008693 if (Attrs.hasAttrSomewhere(ParamAttr::Nest))
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008694 return 0;
Duncan Sandscdb6d922007-09-17 10:26:40 +00008695
8696 IntrinsicInst *Tramp =
8697 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
8698
8699 Function *NestF =
8700 cast<Function>(IntrinsicInst::StripPointerCasts(Tramp->getOperand(2)));
8701 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
8702 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
8703
Chris Lattner58d74912008-03-12 17:45:29 +00008704 const PAListPtr &NestAttrs = NestF->getParamAttrs();
8705 if (!NestAttrs.isEmpty()) {
Duncan Sandscdb6d922007-09-17 10:26:40 +00008706 unsigned NestIdx = 1;
8707 const Type *NestTy = 0;
Dale Johannesen0d51e7e2008-02-19 21:38:47 +00008708 ParameterAttributes NestAttr = ParamAttr::None;
Duncan Sandscdb6d922007-09-17 10:26:40 +00008709
8710 // Look for a parameter marked with the 'nest' attribute.
8711 for (FunctionType::param_iterator I = NestFTy->param_begin(),
8712 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Chris Lattner58d74912008-03-12 17:45:29 +00008713 if (NestAttrs.paramHasAttr(NestIdx, ParamAttr::Nest)) {
Duncan Sandscdb6d922007-09-17 10:26:40 +00008714 // Record the parameter type and any other attributes.
8715 NestTy = *I;
Chris Lattner58d74912008-03-12 17:45:29 +00008716 NestAttr = NestAttrs.getParamAttrs(NestIdx);
Duncan Sandscdb6d922007-09-17 10:26:40 +00008717 break;
8718 }
8719
8720 if (NestTy) {
8721 Instruction *Caller = CS.getInstruction();
8722 std::vector<Value*> NewArgs;
8723 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
8724
Chris Lattner58d74912008-03-12 17:45:29 +00008725 SmallVector<ParamAttrsWithIndex, 8> NewAttrs;
8726 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008727
Duncan Sandscdb6d922007-09-17 10:26:40 +00008728 // Insert the nest argument into the call argument list, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008729 // mean appending it. Likewise for attributes.
8730
8731 // Add any function result attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00008732 if (ParameterAttributes Attr = Attrs.getParamAttrs(0))
8733 NewAttrs.push_back(ParamAttrsWithIndex::get(0, Attr));
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008734
Duncan Sandscdb6d922007-09-17 10:26:40 +00008735 {
8736 unsigned Idx = 1;
8737 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
8738 do {
8739 if (Idx == NestIdx) {
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008740 // Add the chain argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +00008741 Value *NestVal = Tramp->getOperand(3);
8742 if (NestVal->getType() != NestTy)
8743 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
8744 NewArgs.push_back(NestVal);
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008745 NewAttrs.push_back(ParamAttrsWithIndex::get(NestIdx, NestAttr));
Duncan Sandscdb6d922007-09-17 10:26:40 +00008746 }
8747
8748 if (I == E)
8749 break;
8750
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008751 // Add the original argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +00008752 NewArgs.push_back(*I);
Chris Lattner58d74912008-03-12 17:45:29 +00008753 if (ParameterAttributes Attr = Attrs.getParamAttrs(Idx))
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008754 NewAttrs.push_back
8755 (ParamAttrsWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sandscdb6d922007-09-17 10:26:40 +00008756
8757 ++Idx, ++I;
8758 } while (1);
8759 }
8760
8761 // The trampoline may have been bitcast to a bogus type (FTy).
8762 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008763 // with the chain parameter inserted.
Duncan Sandscdb6d922007-09-17 10:26:40 +00008764
Duncan Sandscdb6d922007-09-17 10:26:40 +00008765 std::vector<const Type*> NewTypes;
Duncan Sandscdb6d922007-09-17 10:26:40 +00008766 NewTypes.reserve(FTy->getNumParams()+1);
8767
Duncan Sandscdb6d922007-09-17 10:26:40 +00008768 // Insert the chain's type into the list of parameter types, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008769 // mean appending it.
Duncan Sandscdb6d922007-09-17 10:26:40 +00008770 {
8771 unsigned Idx = 1;
8772 FunctionType::param_iterator I = FTy->param_begin(),
8773 E = FTy->param_end();
8774
8775 do {
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008776 if (Idx == NestIdx)
8777 // Add the chain's type.
Duncan Sandscdb6d922007-09-17 10:26:40 +00008778 NewTypes.push_back(NestTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +00008779
8780 if (I == E)
8781 break;
8782
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008783 // Add the original type.
Duncan Sandscdb6d922007-09-17 10:26:40 +00008784 NewTypes.push_back(*I);
Duncan Sandscdb6d922007-09-17 10:26:40 +00008785
8786 ++Idx, ++I;
8787 } while (1);
8788 }
8789
8790 // Replace the trampoline call with a direct call. Let the generic
8791 // code sort out any function type mismatches.
8792 FunctionType *NewFTy =
Duncan Sandsdc024672007-11-27 13:23:08 +00008793 FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
Christopher Lamb43ad6b32007-12-17 01:12:55 +00008794 Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
8795 NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
Chris Lattner58d74912008-03-12 17:45:29 +00008796 const PAListPtr &NewPAL = PAListPtr::get(NewAttrs.begin(),NewAttrs.end());
Duncan Sandscdb6d922007-09-17 10:26:40 +00008797
8798 Instruction *NewCaller;
8799 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
8800 NewCaller = new InvokeInst(NewCallee,
8801 II->getNormalDest(), II->getUnwindDest(),
8802 NewArgs.begin(), NewArgs.end(),
8803 Caller->getName(), Caller);
8804 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Duncan Sandsdc024672007-11-27 13:23:08 +00008805 cast<InvokeInst>(NewCaller)->setParamAttrs(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +00008806 } else {
8807 NewCaller = new CallInst(NewCallee, NewArgs.begin(), NewArgs.end(),
8808 Caller->getName(), Caller);
8809 if (cast<CallInst>(Caller)->isTailCall())
8810 cast<CallInst>(NewCaller)->setTailCall();
8811 cast<CallInst>(NewCaller)->
8812 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Duncan Sandsdc024672007-11-27 13:23:08 +00008813 cast<CallInst>(NewCaller)->setParamAttrs(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +00008814 }
8815 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
8816 Caller->replaceAllUsesWith(NewCaller);
8817 Caller->eraseFromParent();
8818 RemoveFromWorkList(Caller);
8819 return 0;
8820 }
8821 }
8822
8823 // Replace the trampoline call with a direct call. Since there is no 'nest'
8824 // parameter, there is no need to adjust the argument list. Let the generic
8825 // code sort out any function type mismatches.
8826 Constant *NewCallee =
8827 NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
8828 CS.setCalledFunction(NewCallee);
8829 return CS.getInstruction();
8830}
8831
Chris Lattner7da52b22006-11-01 04:51:18 +00008832/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
8833/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
8834/// and a single binop.
8835Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
8836 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Reid Spencer832254e2007-02-02 02:16:23 +00008837 assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
8838 isa<CmpInst>(FirstInst));
Chris Lattner7da52b22006-11-01 04:51:18 +00008839 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00008840 Value *LHSVal = FirstInst->getOperand(0);
8841 Value *RHSVal = FirstInst->getOperand(1);
8842
8843 const Type *LHSType = LHSVal->getType();
8844 const Type *RHSType = RHSVal->getType();
Chris Lattner7da52b22006-11-01 04:51:18 +00008845
8846 // Scan to see if all operands are the same opcode, all have one use, and all
8847 // kill their operands (i.e. the operands have one use).
Chris Lattnera90a24c2006-11-01 04:55:47 +00008848 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
Chris Lattner7da52b22006-11-01 04:51:18 +00008849 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnera90a24c2006-11-01 04:55:47 +00008850 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00008851 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattner9c080502006-11-01 07:43:41 +00008852 // types or GEP's with different index types.
8853 I->getOperand(0)->getType() != LHSType ||
8854 I->getOperand(1)->getType() != RHSType)
Chris Lattner7da52b22006-11-01 04:51:18 +00008855 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +00008856
8857 // If they are CmpInst instructions, check their predicates
8858 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
8859 if (cast<CmpInst>(I)->getPredicate() !=
8860 cast<CmpInst>(FirstInst)->getPredicate())
8861 return 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00008862
8863 // Keep track of which operand needs a phi node.
8864 if (I->getOperand(0) != LHSVal) LHSVal = 0;
8865 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattner7da52b22006-11-01 04:51:18 +00008866 }
8867
Chris Lattner53738a42006-11-08 19:42:28 +00008868 // Otherwise, this is safe to transform, determine if it is profitable.
8869
8870 // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
8871 // Indexes are often folded into load/store instructions, so we don't want to
8872 // hide them behind a phi.
8873 if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
8874 return 0;
8875
Chris Lattner7da52b22006-11-01 04:51:18 +00008876 Value *InLHS = FirstInst->getOperand(0);
Chris Lattner7da52b22006-11-01 04:51:18 +00008877 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner53738a42006-11-08 19:42:28 +00008878 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00008879 if (LHSVal == 0) {
8880 NewLHS = new PHINode(LHSType, FirstInst->getOperand(0)->getName()+".pn");
8881 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
8882 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +00008883 InsertNewInstBefore(NewLHS, PN);
8884 LHSVal = NewLHS;
8885 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00008886
8887 if (RHSVal == 0) {
8888 NewRHS = new PHINode(RHSType, FirstInst->getOperand(1)->getName()+".pn");
8889 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
8890 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +00008891 InsertNewInstBefore(NewRHS, PN);
8892 RHSVal = NewRHS;
8893 }
8894
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00008895 // Add all operands to the new PHIs.
8896 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
8897 if (NewLHS) {
8898 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
8899 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
8900 }
8901 if (NewRHS) {
8902 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
8903 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
8904 }
8905 }
8906
Chris Lattner7da52b22006-11-01 04:51:18 +00008907 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattner9c080502006-11-01 07:43:41 +00008908 return BinaryOperator::create(BinOp->getOpcode(), LHSVal, RHSVal);
Reid Spencere4d87aa2006-12-23 06:05:41 +00008909 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
8910 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
8911 RHSVal);
Chris Lattner9c080502006-11-01 07:43:41 +00008912 else {
8913 assert(isa<GetElementPtrInst>(FirstInst));
8914 return new GetElementPtrInst(LHSVal, RHSVal);
8915 }
Chris Lattner7da52b22006-11-01 04:51:18 +00008916}
8917
Chris Lattner76c73142006-11-01 07:13:54 +00008918/// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
8919/// of the block that defines it. This means that it must be obvious the value
8920/// of the load is not changed from the point of the load to the end of the
8921/// block it is in.
Chris Lattnerfd905ca2007-02-01 22:30:07 +00008922///
8923/// Finally, it is safe, but not profitable, to sink a load targetting a
8924/// non-address-taken alloca. Doing so will cause us to not promote the alloca
8925/// to a register.
Chris Lattner76c73142006-11-01 07:13:54 +00008926static bool isSafeToSinkLoad(LoadInst *L) {
8927 BasicBlock::iterator BBI = L, E = L->getParent()->end();
8928
8929 for (++BBI; BBI != E; ++BBI)
8930 if (BBI->mayWriteToMemory())
8931 return false;
Chris Lattnerfd905ca2007-02-01 22:30:07 +00008932
8933 // Check for non-address taken alloca. If not address-taken already, it isn't
8934 // profitable to do this xform.
8935 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
8936 bool isAddressTaken = false;
8937 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
8938 UI != E; ++UI) {
8939 if (isa<LoadInst>(UI)) continue;
8940 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
8941 // If storing TO the alloca, then the address isn't taken.
8942 if (SI->getOperand(1) == AI) continue;
8943 }
8944 isAddressTaken = true;
8945 break;
8946 }
8947
8948 if (!isAddressTaken)
8949 return false;
8950 }
8951
Chris Lattner76c73142006-11-01 07:13:54 +00008952 return true;
8953}
8954
Chris Lattner9fe38862003-06-19 17:00:31 +00008955
Chris Lattnerbac32862004-11-14 19:13:23 +00008956// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
8957// operator and they all are only used by the PHI, PHI together their
8958// inputs, and do the operation once, to the result of the PHI.
8959Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
8960 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
8961
8962 // Scan the instruction, looking for input operations that can be folded away.
8963 // If all input operands to the phi are the same instruction (e.g. a cast from
8964 // the same type or "+42") we can pull the operation through the PHI, reducing
8965 // code size and simplifying code.
8966 Constant *ConstantOp = 0;
8967 const Type *CastSrcTy = 0;
Chris Lattner76c73142006-11-01 07:13:54 +00008968 bool isVolatile = false;
Chris Lattnerbac32862004-11-14 19:13:23 +00008969 if (isa<CastInst>(FirstInst)) {
8970 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer832254e2007-02-02 02:16:23 +00008971 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00008972 // Can fold binop, compare or shift here if the RHS is a constant,
8973 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattnerbac32862004-11-14 19:13:23 +00008974 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattner7da52b22006-11-01 04:51:18 +00008975 if (ConstantOp == 0)
8976 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner76c73142006-11-01 07:13:54 +00008977 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
8978 isVolatile = LI->isVolatile();
8979 // We can't sink the load if the loaded value could be modified between the
8980 // load and the PHI.
8981 if (LI->getParent() != PN.getIncomingBlock(0) ||
8982 !isSafeToSinkLoad(LI))
8983 return 0;
Chris Lattner9c080502006-11-01 07:43:41 +00008984 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner53738a42006-11-08 19:42:28 +00008985 if (FirstInst->getNumOperands() == 2)
Chris Lattner9c080502006-11-01 07:43:41 +00008986 return FoldPHIArgBinOpIntoPHI(PN);
8987 // Can't handle general GEPs yet.
8988 return 0;
Chris Lattnerbac32862004-11-14 19:13:23 +00008989 } else {
8990 return 0; // Cannot fold this operation.
8991 }
8992
8993 // Check to see if all arguments are the same operation.
8994 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
8995 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
8996 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencere4d87aa2006-12-23 06:05:41 +00008997 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattnerbac32862004-11-14 19:13:23 +00008998 return 0;
8999 if (CastSrcTy) {
9000 if (I->getOperand(0)->getType() != CastSrcTy)
9001 return 0; // Cast operation must match.
Chris Lattner76c73142006-11-01 07:13:54 +00009002 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00009003 // We can't sink the load if the loaded value could be modified between
9004 // the load and the PHI.
Chris Lattner76c73142006-11-01 07:13:54 +00009005 if (LI->isVolatile() != isVolatile ||
9006 LI->getParent() != PN.getIncomingBlock(i) ||
9007 !isSafeToSinkLoad(LI))
9008 return 0;
Chris Lattnerbac32862004-11-14 19:13:23 +00009009 } else if (I->getOperand(1) != ConstantOp) {
9010 return 0;
9011 }
9012 }
9013
9014 // Okay, they are all the same operation. Create a new PHI node of the
9015 // correct type, and PHI together all of the LHS's of the instructions.
9016 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
9017 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +00009018 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +00009019
9020 Value *InVal = FirstInst->getOperand(0);
9021 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00009022
9023 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +00009024 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9025 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9026 if (NewInVal != InVal)
9027 InVal = 0;
9028 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
9029 }
9030
9031 Value *PhiVal;
9032 if (InVal) {
9033 // The new PHI unions all of the same values together. This is really
9034 // common, so we handle it intelligently here for compile-time speed.
9035 PhiVal = InVal;
9036 delete NewPN;
9037 } else {
9038 InsertNewInstBefore(NewPN, PN);
9039 PhiVal = NewPN;
9040 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009041
Chris Lattnerbac32862004-11-14 19:13:23 +00009042 // Insert and return the new operation.
Reid Spencer3da59db2006-11-27 01:05:10 +00009043 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
9044 return CastInst::create(FirstCI->getOpcode(), PhiVal, PN.getType());
Reid Spencer3ed469c2006-11-02 20:25:50 +00009045 else if (isa<LoadInst>(FirstInst))
Chris Lattner76c73142006-11-01 07:13:54 +00009046 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattnerbac32862004-11-14 19:13:23 +00009047 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattnerb5893442004-11-14 19:29:34 +00009048 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Reid Spencere4d87aa2006-12-23 06:05:41 +00009049 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
9050 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(),
9051 PhiVal, ConstantOp);
Chris Lattnerbac32862004-11-14 19:13:23 +00009052 else
Reid Spencer832254e2007-02-02 02:16:23 +00009053 assert(0 && "Unknown operation");
Jeff Cohenca5183d2007-03-05 00:00:42 +00009054 return 0;
Chris Lattnerbac32862004-11-14 19:13:23 +00009055}
Chris Lattnera1be5662002-05-02 17:06:02 +00009056
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009057/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
9058/// that is dead.
Chris Lattner0e5444b2007-03-26 20:40:50 +00009059static bool DeadPHICycle(PHINode *PN,
9060 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009061 if (PN->use_empty()) return true;
9062 if (!PN->hasOneUse()) return false;
9063
9064 // Remember this node, and if we find the cycle, return.
Chris Lattner0e5444b2007-03-26 20:40:50 +00009065 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009066 return true;
Chris Lattner92103de2007-08-28 04:23:55 +00009067
9068 // Don't scan crazily complex things.
9069 if (PotentiallyDeadPHIs.size() == 16)
9070 return false;
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009071
9072 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
9073 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +00009074
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009075 return false;
9076}
9077
Chris Lattnercf5008a2007-11-06 21:52:06 +00009078/// PHIsEqualValue - Return true if this phi node is always equal to
9079/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
9080/// z = some value; x = phi (y, z); y = phi (x, z)
9081static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
9082 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
9083 // See if we already saw this PHI node.
9084 if (!ValueEqualPHIs.insert(PN))
9085 return true;
9086
9087 // Don't scan crazily complex things.
9088 if (ValueEqualPHIs.size() == 16)
9089 return false;
9090
9091 // Scan the operands to see if they are either phi nodes or are equal to
9092 // the value.
9093 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
9094 Value *Op = PN->getIncomingValue(i);
9095 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
9096 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
9097 return false;
9098 } else if (Op != NonPhiInVal)
9099 return false;
9100 }
9101
9102 return true;
9103}
9104
9105
Chris Lattner473945d2002-05-06 18:06:38 +00009106// PHINode simplification
9107//
Chris Lattner7e708292002-06-25 16:13:24 +00009108Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +00009109 // If LCSSA is around, don't mess with Phi nodes
Chris Lattnerf964f322007-03-04 04:27:24 +00009110 if (MustPreserveLCSSA) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +00009111
Owen Anderson7e057142006-07-10 22:03:18 +00009112 if (Value *V = PN.hasConstantValue())
9113 return ReplaceInstUsesWith(PN, V);
9114
Owen Anderson7e057142006-07-10 22:03:18 +00009115 // If all PHI operands are the same operation, pull them through the PHI,
9116 // reducing code size.
9117 if (isa<Instruction>(PN.getIncomingValue(0)) &&
9118 PN.getIncomingValue(0)->hasOneUse())
9119 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
9120 return Result;
9121
9122 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
9123 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
9124 // PHI)... break the cycle.
Chris Lattnerff9f13a2007-01-15 07:30:06 +00009125 if (PN.hasOneUse()) {
9126 Instruction *PHIUser = cast<Instruction>(PN.use_back());
9127 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattner0e5444b2007-03-26 20:40:50 +00009128 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Anderson7e057142006-07-10 22:03:18 +00009129 PotentiallyDeadPHIs.insert(&PN);
9130 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
9131 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9132 }
Chris Lattnerff9f13a2007-01-15 07:30:06 +00009133
9134 // If this phi has a single use, and if that use just computes a value for
9135 // the next iteration of a loop, delete the phi. This occurs with unused
9136 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
9137 // common case here is good because the only other things that catch this
9138 // are induction variable analysis (sometimes) and ADCE, which is only run
9139 // late.
9140 if (PHIUser->hasOneUse() &&
9141 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
9142 PHIUser->use_back() == &PN) {
9143 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9144 }
9145 }
Owen Anderson7e057142006-07-10 22:03:18 +00009146
Chris Lattnercf5008a2007-11-06 21:52:06 +00009147 // We sometimes end up with phi cycles that non-obviously end up being the
9148 // same value, for example:
9149 // z = some value; x = phi (y, z); y = phi (x, z)
9150 // where the phi nodes don't necessarily need to be in the same block. Do a
9151 // quick check to see if the PHI node only contains a single non-phi value, if
9152 // so, scan to see if the phi cycle is actually equal to that value.
9153 {
9154 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
9155 // Scan for the first non-phi operand.
9156 while (InValNo != NumOperandVals &&
9157 isa<PHINode>(PN.getIncomingValue(InValNo)))
9158 ++InValNo;
9159
9160 if (InValNo != NumOperandVals) {
9161 Value *NonPhiInVal = PN.getOperand(InValNo);
9162
9163 // Scan the rest of the operands to see if there are any conflicts, if so
9164 // there is no need to recursively scan other phis.
9165 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
9166 Value *OpVal = PN.getIncomingValue(InValNo);
9167 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
9168 break;
9169 }
9170
9171 // If we scanned over all operands, then we have one unique value plus
9172 // phi values. Scan PHI nodes to see if they all merge in each other or
9173 // the value.
9174 if (InValNo == NumOperandVals) {
9175 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
9176 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
9177 return ReplaceInstUsesWith(PN, NonPhiInVal);
9178 }
9179 }
9180 }
Chris Lattner60921c92003-12-19 05:58:40 +00009181 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +00009182}
9183
Reid Spencer17212df2006-12-12 09:18:51 +00009184static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
9185 Instruction *InsertPoint,
9186 InstCombiner *IC) {
Reid Spencerabaa8ca2007-01-08 16:32:00 +00009187 unsigned PtrSize = DTy->getPrimitiveSizeInBits();
9188 unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +00009189 // We must cast correctly to the pointer type. Ensure that we
9190 // sign extend the integer value if it is smaller as this is
9191 // used for address computation.
9192 Instruction::CastOps opcode =
9193 (VTySize < PtrSize ? Instruction::SExt :
9194 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
9195 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
Chris Lattner28977af2004-04-05 01:30:19 +00009196}
9197
Chris Lattnera1be5662002-05-02 17:06:02 +00009198
Chris Lattner7e708292002-06-25 16:13:24 +00009199Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +00009200 Value *PtrOp = GEP.getOperand(0);
Chris Lattner9bc14642007-04-28 00:57:34 +00009201 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
Chris Lattner7e708292002-06-25 16:13:24 +00009202 // If so, eliminate the noop.
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009203 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +00009204 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009205
Chris Lattnere87597f2004-10-16 18:11:37 +00009206 if (isa<UndefValue>(GEP.getOperand(0)))
9207 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
9208
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009209 bool HasZeroPointerIndex = false;
9210 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
9211 HasZeroPointerIndex = C->isNullValue();
9212
9213 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +00009214 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +00009215
Chris Lattner28977af2004-04-05 01:30:19 +00009216 // Eliminate unneeded casts for indices.
9217 bool MadeChange = false;
Chris Lattnerdb9654e2007-03-25 20:43:09 +00009218
Chris Lattnercb69a4e2004-04-07 18:38:20 +00009219 gep_type_iterator GTI = gep_type_begin(GEP);
Chris Lattnerdb9654e2007-03-25 20:43:09 +00009220 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattnercb69a4e2004-04-07 18:38:20 +00009221 if (isa<SequentialType>(*GTI)) {
9222 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
Chris Lattner76b7a062007-01-15 07:02:54 +00009223 if (CI->getOpcode() == Instruction::ZExt ||
9224 CI->getOpcode() == Instruction::SExt) {
9225 const Type *SrcTy = CI->getOperand(0)->getType();
9226 // We can eliminate a cast from i32 to i64 iff the target
9227 // is a 32-bit pointer target.
9228 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
9229 MadeChange = true;
9230 GEP.setOperand(i, CI->getOperand(0));
Chris Lattner28977af2004-04-05 01:30:19 +00009231 }
9232 }
9233 }
Chris Lattnercb69a4e2004-04-07 18:38:20 +00009234 // If we are using a wider index than needed for this platform, shrink it
9235 // to what we need. If the incoming value needs a cast instruction,
9236 // insert it. This explicit cast can make subsequent optimizations more
9237 // obvious.
9238 Value *Op = GEP.getOperand(i);
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009239 if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
Chris Lattner4f1134e2004-04-17 18:16:10 +00009240 if (Constant *C = dyn_cast<Constant>(Op)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00009241 GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
Chris Lattner4f1134e2004-04-17 18:16:10 +00009242 MadeChange = true;
9243 } else {
Reid Spencer17212df2006-12-12 09:18:51 +00009244 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
9245 GEP);
Chris Lattnercb69a4e2004-04-07 18:38:20 +00009246 GEP.setOperand(i, Op);
9247 MadeChange = true;
9248 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009249 }
Chris Lattner28977af2004-04-05 01:30:19 +00009250 }
Chris Lattnerdb9654e2007-03-25 20:43:09 +00009251 }
Chris Lattner28977af2004-04-05 01:30:19 +00009252 if (MadeChange) return &GEP;
9253
Chris Lattnerdb9654e2007-03-25 20:43:09 +00009254 // If this GEP instruction doesn't move the pointer, and if the input operand
9255 // is a bitcast of another pointer, just replace the GEP with a bitcast of the
9256 // real input to the dest type.
Chris Lattner6a94de22007-10-12 05:30:59 +00009257 if (GEP.hasAllZeroIndices()) {
9258 if (BitCastInst *BCI = dyn_cast<BitCastInst>(GEP.getOperand(0))) {
9259 // If the bitcast is of an allocation, and the allocation will be
9260 // converted to match the type of the cast, don't touch this.
9261 if (isa<AllocationInst>(BCI->getOperand(0))) {
9262 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
Chris Lattnera79dd432007-10-12 18:05:47 +00009263 if (Instruction *I = visitBitCast(*BCI)) {
9264 if (I != BCI) {
9265 I->takeName(BCI);
9266 BCI->getParent()->getInstList().insert(BCI, I);
9267 ReplaceInstUsesWith(*BCI, I);
9268 }
Chris Lattner6a94de22007-10-12 05:30:59 +00009269 return &GEP;
Chris Lattnera79dd432007-10-12 18:05:47 +00009270 }
Chris Lattner6a94de22007-10-12 05:30:59 +00009271 }
9272 return new BitCastInst(BCI->getOperand(0), GEP.getType());
9273 }
9274 }
9275
Chris Lattner90ac28c2002-08-02 19:29:35 +00009276 // Combine Indices - If the source pointer to this getelementptr instruction
9277 // is a getelementptr instruction, combine the indices of the two
9278 // getelementptr instructions into a single instruction.
9279 //
Chris Lattner72588fc2007-02-15 22:48:32 +00009280 SmallVector<Value*, 8> SrcGEPOperands;
Chris Lattner574da9b2005-01-13 20:14:25 +00009281 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner72588fc2007-02-15 22:48:32 +00009282 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
Chris Lattnerebd985c2004-03-25 22:59:29 +00009283
9284 if (!SrcGEPOperands.empty()) {
Chris Lattner620ce142004-05-07 22:09:22 +00009285 // Note that if our source is a gep chain itself that we wait for that
9286 // chain to be resolved before we perform this transformation. This
9287 // avoids us creating a TON of code in some cases.
9288 //
9289 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
9290 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
9291 return 0; // Wait until our source is folded to completion.
9292
Chris Lattner72588fc2007-02-15 22:48:32 +00009293 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +00009294
9295 // Find out whether the last index in the source GEP is a sequential idx.
9296 bool EndsWithSequential = false;
9297 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
9298 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +00009299 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +00009300
Chris Lattner90ac28c2002-08-02 19:29:35 +00009301 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +00009302 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +00009303 // Replace: gep (gep %P, long B), long A, ...
9304 // With: T = long A+B; gep %P, T, ...
9305 //
Chris Lattner620ce142004-05-07 22:09:22 +00009306 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner28977af2004-04-05 01:30:19 +00009307 if (SO1 == Constant::getNullValue(SO1->getType())) {
9308 Sum = GO1;
9309 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
9310 Sum = SO1;
9311 } else {
9312 // If they aren't the same type, convert both to an integer of the
9313 // target's pointer size.
9314 if (SO1->getType() != GO1->getType()) {
9315 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +00009316 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +00009317 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +00009318 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +00009319 } else {
Duncan Sands514ab342007-11-01 20:53:16 +00009320 unsigned PS = TD->getPointerSizeInBits();
9321 if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +00009322 // Convert GO1 to SO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +00009323 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +00009324
Duncan Sands514ab342007-11-01 20:53:16 +00009325 } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +00009326 // Convert SO1 to GO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +00009327 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +00009328 } else {
9329 const Type *PT = TD->getIntPtrType();
Reid Spencer17212df2006-12-12 09:18:51 +00009330 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
9331 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +00009332 }
9333 }
9334 }
Chris Lattner620ce142004-05-07 22:09:22 +00009335 if (isa<Constant>(SO1) && isa<Constant>(GO1))
9336 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
9337 else {
Chris Lattner48595f12004-06-10 02:07:29 +00009338 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
9339 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner620ce142004-05-07 22:09:22 +00009340 }
Chris Lattner28977af2004-04-05 01:30:19 +00009341 }
Chris Lattner620ce142004-05-07 22:09:22 +00009342
9343 // Recycle the GEP we already have if possible.
9344 if (SrcGEPOperands.size() == 2) {
9345 GEP.setOperand(0, SrcGEPOperands[0]);
9346 GEP.setOperand(1, Sum);
9347 return &GEP;
9348 } else {
9349 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9350 SrcGEPOperands.end()-1);
9351 Indices.push_back(Sum);
9352 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
9353 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009354 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +00009355 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanfd939082005-04-21 23:48:37 +00009356 SrcGEPOperands.size() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +00009357 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerebd985c2004-03-25 22:59:29 +00009358 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9359 SrcGEPOperands.end());
Chris Lattner90ac28c2002-08-02 19:29:35 +00009360 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
9361 }
9362
9363 if (!Indices.empty())
David Greeneb8f74792007-09-04 15:46:09 +00009364 return new GetElementPtrInst(SrcGEPOperands[0], Indices.begin(),
9365 Indices.end(), GEP.getName());
Chris Lattner9b761232002-08-17 22:21:59 +00009366
Chris Lattner620ce142004-05-07 22:09:22 +00009367 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattner9b761232002-08-17 22:21:59 +00009368 // GEP of global variable. If all of the indices for this GEP are
9369 // constants, we can promote this to a constexpr instead of an instruction.
9370
9371 // Scan for nonconstants...
Chris Lattner55eb1c42007-01-31 04:40:53 +00009372 SmallVector<Constant*, 8> Indices;
Chris Lattner9b761232002-08-17 22:21:59 +00009373 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
9374 for (; I != E && isa<Constant>(*I); ++I)
9375 Indices.push_back(cast<Constant>(*I));
9376
9377 if (I == E) { // If they are all constants...
Chris Lattner55eb1c42007-01-31 04:40:53 +00009378 Constant *CE = ConstantExpr::getGetElementPtr(GV,
9379 &Indices[0],Indices.size());
Chris Lattner9b761232002-08-17 22:21:59 +00009380
9381 // Replace all uses of the GEP with the new constexpr...
9382 return ReplaceInstUsesWith(GEP, CE);
9383 }
Reid Spencer3da59db2006-11-27 01:05:10 +00009384 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
Chris Lattnereed48272005-09-13 00:40:14 +00009385 if (!isa<PointerType>(X->getType())) {
9386 // Not interesting. Source pointer must be a cast from pointer.
9387 } else if (HasZeroPointerIndex) {
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009388 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
9389 // into : GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +00009390 //
9391 // This occurs when the program declares an array extern like "int X[];"
9392 //
9393 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
9394 const PointerType *XTy = cast<PointerType>(X->getType());
9395 if (const ArrayType *XATy =
9396 dyn_cast<ArrayType>(XTy->getElementType()))
9397 if (const ArrayType *CATy =
9398 dyn_cast<ArrayType>(CPTy->getElementType()))
9399 if (CATy->getElementType() == XATy->getElementType()) {
9400 // At this point, we know that the cast source type is a pointer
9401 // to an array of the same type as the destination pointer
9402 // array. Because the array type is never stepped over (there
9403 // is a leading zero) we can fold the cast into this GEP.
9404 GEP.setOperand(0, X);
9405 return &GEP;
9406 }
9407 } else if (GEP.getNumOperands() == 2) {
9408 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009409 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
9410 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnereed48272005-09-13 00:40:14 +00009411 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
9412 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
9413 if (isa<ArrayType>(SrcElTy) &&
Duncan Sands514ab342007-11-01 20:53:16 +00009414 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
9415 TD->getABITypeSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +00009416 Value *Idx[2];
9417 Idx[0] = Constant::getNullValue(Type::Int32Ty);
9418 Idx[1] = GEP.getOperand(1);
Chris Lattnereed48272005-09-13 00:40:14 +00009419 Value *V = InsertNewInstBefore(
David Greeneb8f74792007-09-04 15:46:09 +00009420 new GetElementPtrInst(X, Idx, Idx + 2, GEP.getName()), GEP);
Reid Spencer3da59db2006-11-27 01:05:10 +00009421 // V and GEP are both pointer types --> BitCast
9422 return new BitCastInst(V, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009423 }
Chris Lattner7835cdd2005-09-13 18:36:04 +00009424
9425 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009426 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +00009427 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009428 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +00009429
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009430 if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
Chris Lattner7835cdd2005-09-13 18:36:04 +00009431 uint64_t ArrayEltSize =
Duncan Sands514ab342007-11-01 20:53:16 +00009432 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +00009433
9434 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
9435 // allow either a mul, shift, or constant here.
9436 Value *NewIdx = 0;
9437 ConstantInt *Scale = 0;
9438 if (ArrayEltSize == 1) {
9439 NewIdx = GEP.getOperand(1);
9440 Scale = ConstantInt::get(NewIdx->getType(), 1);
9441 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattner6e2f8432005-09-14 17:32:56 +00009442 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +00009443 Scale = CI;
9444 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
9445 if (Inst->getOpcode() == Instruction::Shl &&
9446 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00009447 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
9448 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
9449 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +00009450 NewIdx = Inst->getOperand(0);
9451 } else if (Inst->getOpcode() == Instruction::Mul &&
9452 isa<ConstantInt>(Inst->getOperand(1))) {
9453 Scale = cast<ConstantInt>(Inst->getOperand(1));
9454 NewIdx = Inst->getOperand(0);
9455 }
9456 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009457
Chris Lattner7835cdd2005-09-13 18:36:04 +00009458 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009459 // out, perform the transformation. Note, we don't know whether Scale is
9460 // signed or not. We'll use unsigned version of division/modulo
9461 // operation after making sure Scale doesn't have the sign bit set.
9462 if (Scale && Scale->getSExtValue() >= 0LL &&
9463 Scale->getZExtValue() % ArrayEltSize == 0) {
9464 Scale = ConstantInt::get(Scale->getType(),
9465 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +00009466 if (Scale->getZExtValue() != 1) {
Reid Spencer17212df2006-12-12 09:18:51 +00009467 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009468 false /*ZExt*/);
Chris Lattner7835cdd2005-09-13 18:36:04 +00009469 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
9470 NewIdx = InsertNewInstBefore(Sc, GEP);
9471 }
9472
9473 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +00009474 Value *Idx[2];
9475 Idx[0] = Constant::getNullValue(Type::Int32Ty);
9476 Idx[1] = NewIdx;
Reid Spencer3da59db2006-11-27 01:05:10 +00009477 Instruction *NewGEP =
David Greeneb8f74792007-09-04 15:46:09 +00009478 new GetElementPtrInst(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +00009479 NewGEP = InsertNewInstBefore(NewGEP, GEP);
9480 // The NewGEP must be pointer typed, so must the old one -> BitCast
9481 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +00009482 }
9483 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009484 }
Chris Lattner8a2a3112001-12-14 16:52:21 +00009485 }
9486
Chris Lattner8a2a3112001-12-14 16:52:21 +00009487 return 0;
9488}
9489
Chris Lattner0864acf2002-11-04 16:18:53 +00009490Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
9491 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009492 if (AI.isArrayAllocation()) { // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +00009493 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
9494 const Type *NewTy =
9495 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattner0006bd72002-11-09 00:49:43 +00009496 AllocationInst *New = 0;
Chris Lattner0864acf2002-11-04 16:18:53 +00009497
9498 // Create and insert the replacement instruction...
9499 if (isa<MallocInst>(AI))
Nate Begeman14b05292005-11-05 09:21:28 +00009500 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +00009501 else {
9502 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman14b05292005-11-05 09:21:28 +00009503 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +00009504 }
Chris Lattner7c881df2004-03-19 06:08:10 +00009505
9506 InsertNewInstBefore(New, AI);
Misha Brukmanfd939082005-04-21 23:48:37 +00009507
Chris Lattner0864acf2002-11-04 16:18:53 +00009508 // Scan to the end of the allocation instructions, to skip over a block of
9509 // allocas if possible...
9510 //
9511 BasicBlock::iterator It = New;
9512 while (isa<AllocationInst>(*It)) ++It;
9513
9514 // Now that I is pointing to the first non-allocation-inst in the block,
9515 // insert our getelementptr instruction...
9516 //
Reid Spencerc5b206b2006-12-31 05:48:39 +00009517 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
David Greeneb8f74792007-09-04 15:46:09 +00009518 Value *Idx[2];
9519 Idx[0] = NullIdx;
9520 Idx[1] = NullIdx;
9521 Value *V = new GetElementPtrInst(New, Idx, Idx + 2,
Chris Lattner693787a2005-05-04 19:10:26 +00009522 New->getName()+".sub", It);
Chris Lattner0864acf2002-11-04 16:18:53 +00009523
9524 // Now make everything use the getelementptr instead of the original
9525 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +00009526 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +00009527 } else if (isa<UndefValue>(AI.getArraySize())) {
9528 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +00009529 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009530 }
Chris Lattner7c881df2004-03-19 06:08:10 +00009531
9532 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
9533 // Note that we only do this for alloca's, because malloc should allocate and
9534 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanfd939082005-04-21 23:48:37 +00009535 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Duncan Sands514ab342007-11-01 20:53:16 +00009536 TD->getABITypeSize(AI.getAllocatedType()) == 0)
Chris Lattner7c881df2004-03-19 06:08:10 +00009537 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
9538
Chris Lattner0864acf2002-11-04 16:18:53 +00009539 return 0;
9540}
9541
Chris Lattner67b1e1b2003-12-07 01:24:23 +00009542Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
9543 Value *Op = FI.getOperand(0);
9544
Chris Lattner17be6352004-10-18 02:59:09 +00009545 // free undef -> unreachable.
9546 if (isa<UndefValue>(Op)) {
9547 // Insert a new store to null because we cannot modify the CFG here.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009548 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009549 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
Chris Lattner17be6352004-10-18 02:59:09 +00009550 return EraseInstFromFunction(FI);
9551 }
Chris Lattner6fe55412007-04-14 00:20:02 +00009552
Chris Lattner6160e852004-02-28 04:57:37 +00009553 // If we have 'free null' delete the instruction. This can happen in stl code
9554 // when lots of inlining happens.
Chris Lattner17be6352004-10-18 02:59:09 +00009555 if (isa<ConstantPointerNull>(Op))
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009556 return EraseInstFromFunction(FI);
Chris Lattner6fe55412007-04-14 00:20:02 +00009557
9558 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
9559 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
9560 FI.setOperand(0, CI->getOperand(0));
9561 return &FI;
9562 }
9563
9564 // Change free (gep X, 0,0,0,0) into free(X)
9565 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
9566 if (GEPI->hasAllZeroIndices()) {
9567 AddToWorkList(GEPI);
9568 FI.setOperand(0, GEPI->getOperand(0));
9569 return &FI;
9570 }
9571 }
9572
9573 // Change free(malloc) into nothing, if the malloc has a single use.
9574 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
9575 if (MI->hasOneUse()) {
9576 EraseInstFromFunction(FI);
9577 return EraseInstFromFunction(*MI);
9578 }
Chris Lattner6160e852004-02-28 04:57:37 +00009579
Chris Lattner67b1e1b2003-12-07 01:24:23 +00009580 return 0;
9581}
9582
9583
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009584/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patel99db6ad2007-10-18 19:52:32 +00009585static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling587c01d2008-02-26 10:53:30 +00009586 const TargetData *TD) {
Chris Lattnerb89e0712004-07-13 01:49:43 +00009587 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +00009588 Value *CastOp = CI->getOperand(0);
Chris Lattnerb89e0712004-07-13 01:49:43 +00009589
Devang Patel99db6ad2007-10-18 19:52:32 +00009590 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
9591 // Instead of loading constant c string, use corresponding integer value
9592 // directly if string length is small enough.
9593 const std::string &Str = CE->getOperand(0)->getStringValue();
9594 if (!Str.empty()) {
9595 unsigned len = Str.length();
9596 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
9597 unsigned numBits = Ty->getPrimitiveSizeInBits();
9598 // Replace LI with immediate integer store.
9599 if ((numBits >> 3) == len + 1) {
Bill Wendling587c01d2008-02-26 10:53:30 +00009600 APInt StrVal(numBits, 0);
9601 APInt SingleChar(numBits, 0);
9602 if (TD->isLittleEndian()) {
9603 for (signed i = len-1; i >= 0; i--) {
9604 SingleChar = (uint64_t) Str[i];
9605 StrVal = (StrVal << 8) | SingleChar;
9606 }
9607 } else {
9608 for (unsigned i = 0; i < len; i++) {
9609 SingleChar = (uint64_t) Str[i];
9610 StrVal = (StrVal << 8) | SingleChar;
9611 }
9612 // Append NULL at the end.
9613 SingleChar = 0;
9614 StrVal = (StrVal << 8) | SingleChar;
9615 }
9616 Value *NL = ConstantInt::get(StrVal);
9617 return IC.ReplaceInstUsesWith(LI, NL);
Devang Patel99db6ad2007-10-18 19:52:32 +00009618 }
9619 }
9620 }
9621
Chris Lattnerb89e0712004-07-13 01:49:43 +00009622 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +00009623 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattnerb89e0712004-07-13 01:49:43 +00009624 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +00009625
Reid Spencer42230162007-01-22 05:51:25 +00009626 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +00009627 isa<VectorType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +00009628 // If the source is an array, the code below will not succeed. Check to
9629 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
9630 // constants.
9631 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
9632 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
9633 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +00009634 Value *Idxs[2];
9635 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
9636 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerf9527852005-01-31 04:50:46 +00009637 SrcTy = cast<PointerType>(CastOp->getType());
9638 SrcPTy = SrcTy->getElementType();
9639 }
9640
Reid Spencer42230162007-01-22 05:51:25 +00009641 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +00009642 isa<VectorType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +00009643 // Do not allow turning this into a load of an integer, which is then
9644 // casted to a pointer, this pessimizes pointer analysis a lot.
9645 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Reid Spencer42230162007-01-22 05:51:25 +00009646 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
9647 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +00009648
Chris Lattnerf9527852005-01-31 04:50:46 +00009649 // Okay, we are casting from one integer or pointer type to another of
9650 // the same size. Instead of casting the pointer before the load, cast
9651 // the result of the loaded value.
9652 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
9653 CI->getName(),
9654 LI.isVolatile()),LI);
9655 // Now cast the result of the load.
Reid Spencerd977d862006-12-12 23:36:14 +00009656 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerf9527852005-01-31 04:50:46 +00009657 }
Chris Lattnerb89e0712004-07-13 01:49:43 +00009658 }
9659 }
9660 return 0;
9661}
9662
Chris Lattnerc10aced2004-09-19 18:43:46 +00009663/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattner8a375202004-09-19 19:18:10 +00009664/// from this value cannot trap. If it is not obviously safe to load from the
9665/// specified pointer, we do a quick local scan of the basic block containing
9666/// ScanFrom, to determine if the address is already accessed.
9667static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
Duncan Sands892c7e42007-09-19 10:10:31 +00009668 // If it is an alloca it is always safe to load from.
9669 if (isa<AllocaInst>(V)) return true;
9670
Duncan Sands46318cd2007-09-19 10:25:38 +00009671 // If it is a global variable it is mostly safe to load from.
Duncan Sands892c7e42007-09-19 10:10:31 +00009672 if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
Duncan Sands46318cd2007-09-19 10:25:38 +00009673 // Don't try to evaluate aliases. External weak GV can be null.
Duncan Sands892c7e42007-09-19 10:10:31 +00009674 return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
Chris Lattner8a375202004-09-19 19:18:10 +00009675
9676 // Otherwise, be a little bit agressive by scanning the local block where we
9677 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00009678 // from/to. If so, the previous load or store would have already trapped,
9679 // so there is no harm doing an extra load (also, CSE will later eliminate
9680 // the load entirely).
Chris Lattner8a375202004-09-19 19:18:10 +00009681 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
9682
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00009683 while (BBI != E) {
Chris Lattner8a375202004-09-19 19:18:10 +00009684 --BBI;
9685
9686 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
9687 if (LI->getOperand(0) == V) return true;
9688 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
9689 if (SI->getOperand(1) == V) return true;
Misha Brukmanfd939082005-04-21 23:48:37 +00009690
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00009691 }
Chris Lattner8a375202004-09-19 19:18:10 +00009692 return false;
Chris Lattnerc10aced2004-09-19 18:43:46 +00009693}
9694
Chris Lattner8d2e8882007-08-11 18:48:48 +00009695/// GetUnderlyingObject - Trace through a series of getelementptrs and bitcasts
9696/// until we find the underlying object a pointer is referring to or something
9697/// we don't understand. Note that the returned pointer may be offset from the
9698/// input, because we ignore GEP indices.
9699static Value *GetUnderlyingObject(Value *Ptr) {
9700 while (1) {
9701 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
9702 if (CE->getOpcode() == Instruction::BitCast ||
9703 CE->getOpcode() == Instruction::GetElementPtr)
9704 Ptr = CE->getOperand(0);
9705 else
9706 return Ptr;
9707 } else if (BitCastInst *BCI = dyn_cast<BitCastInst>(Ptr)) {
9708 Ptr = BCI->getOperand(0);
9709 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
9710 Ptr = GEP->getOperand(0);
9711 } else {
9712 return Ptr;
9713 }
9714 }
9715}
9716
Chris Lattner833b8a42003-06-26 05:06:25 +00009717Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
9718 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +00009719
Dan Gohman9941f742007-07-20 16:34:21 +00009720 // Attempt to improve the alignment.
Chris Lattnerf2369f22007-08-09 19:05:49 +00009721 unsigned KnownAlign = GetOrEnforceKnownAlignment(Op, TD);
Dan Gohman9941f742007-07-20 16:34:21 +00009722 if (KnownAlign > LI.getAlignment())
9723 LI.setAlignment(KnownAlign);
9724
Chris Lattner37366c12005-05-01 04:24:53 +00009725 // load (cast X) --> cast (load X) iff safe
Reid Spencer3ed469c2006-11-02 20:25:50 +00009726 if (isa<CastInst>(Op))
Devang Patel99db6ad2007-10-18 19:52:32 +00009727 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattner37366c12005-05-01 04:24:53 +00009728 return Res;
9729
9730 // None of the following transforms are legal for volatile loads.
9731 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +00009732
Chris Lattner62f254d2005-09-12 22:00:15 +00009733 if (&LI.getParent()->front() != &LI) {
9734 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattner9c1f0fd2005-09-12 22:21:03 +00009735 // If the instruction immediately before this is a store to the same
9736 // address, do a simple form of store->load forwarding.
Chris Lattner62f254d2005-09-12 22:00:15 +00009737 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
9738 if (SI->getOperand(1) == LI.getOperand(0))
9739 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattner9c1f0fd2005-09-12 22:21:03 +00009740 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
9741 if (LIB->getOperand(0) == LI.getOperand(0))
9742 return ReplaceInstUsesWith(LI, LIB);
Chris Lattner62f254d2005-09-12 22:00:15 +00009743 }
Chris Lattner37366c12005-05-01 04:24:53 +00009744
Christopher Lambb15147e2007-12-29 07:56:53 +00009745 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
9746 const Value *GEPI0 = GEPI->getOperand(0);
9747 // TODO: Consider a target hook for valid address spaces for this xform.
9748 if (isa<ConstantPointerNull>(GEPI0) &&
9749 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
Chris Lattner37366c12005-05-01 04:24:53 +00009750 // Insert a new store to null instruction before the load to indicate
9751 // that this code is not reachable. We do this instead of inserting
9752 // an unreachable instruction directly because we cannot modify the
9753 // CFG.
9754 new StoreInst(UndefValue::get(LI.getType()),
9755 Constant::getNullValue(Op->getType()), &LI);
9756 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
9757 }
Christopher Lambb15147e2007-12-29 07:56:53 +00009758 }
Chris Lattner37366c12005-05-01 04:24:53 +00009759
Chris Lattnere87597f2004-10-16 18:11:37 +00009760 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner37366c12005-05-01 04:24:53 +00009761 // load null/undef -> undef
Christopher Lambb15147e2007-12-29 07:56:53 +00009762 // TODO: Consider a target hook for valid address spaces for this xform.
9763 if (isa<UndefValue>(C) || (C->isNullValue() &&
9764 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
Chris Lattner17be6352004-10-18 02:59:09 +00009765 // Insert a new store to null instruction before the load to indicate that
9766 // this code is not reachable. We do this instead of inserting an
9767 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattner37366c12005-05-01 04:24:53 +00009768 new StoreInst(UndefValue::get(LI.getType()),
9769 Constant::getNullValue(Op->getType()), &LI);
Chris Lattnere87597f2004-10-16 18:11:37 +00009770 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner17be6352004-10-18 02:59:09 +00009771 }
Chris Lattner833b8a42003-06-26 05:06:25 +00009772
Chris Lattnere87597f2004-10-16 18:11:37 +00009773 // Instcombine load (constant global) into the value loaded.
9774 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Reid Spencer5cbf9852007-01-30 20:08:39 +00009775 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattnere87597f2004-10-16 18:11:37 +00009776 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +00009777
Chris Lattnere87597f2004-10-16 18:11:37 +00009778 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009779 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
Chris Lattnere87597f2004-10-16 18:11:37 +00009780 if (CE->getOpcode() == Instruction::GetElementPtr) {
9781 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Reid Spencer5cbf9852007-01-30 20:08:39 +00009782 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattner363f2a22005-09-26 05:28:06 +00009783 if (Constant *V =
9784 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattnere87597f2004-10-16 18:11:37 +00009785 return ReplaceInstUsesWith(LI, V);
Chris Lattner37366c12005-05-01 04:24:53 +00009786 if (CE->getOperand(0)->isNullValue()) {
9787 // Insert a new store to null instruction before the load to indicate
9788 // that this code is not reachable. We do this instead of inserting
9789 // an unreachable instruction directly because we cannot modify the
9790 // CFG.
9791 new StoreInst(UndefValue::get(LI.getType()),
9792 Constant::getNullValue(Op->getType()), &LI);
9793 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
9794 }
9795
Reid Spencer3da59db2006-11-27 01:05:10 +00009796 } else if (CE->isCast()) {
Devang Patel99db6ad2007-10-18 19:52:32 +00009797 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattnere87597f2004-10-16 18:11:37 +00009798 return Res;
9799 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009800 }
Chris Lattnere87597f2004-10-16 18:11:37 +00009801 }
Chris Lattner8d2e8882007-08-11 18:48:48 +00009802
9803 // If this load comes from anywhere in a constant global, and if the global
9804 // is all undef or zero, we know what it loads.
9805 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(Op))) {
9806 if (GV->isConstant() && GV->hasInitializer()) {
9807 if (GV->getInitializer()->isNullValue())
9808 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
9809 else if (isa<UndefValue>(GV->getInitializer()))
9810 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
9811 }
9812 }
Chris Lattnerf499eac2004-04-08 20:39:49 +00009813
Chris Lattner37366c12005-05-01 04:24:53 +00009814 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +00009815 // Change select and PHI nodes to select values instead of addresses: this
9816 // helps alias analysis out a lot, allows many others simplifications, and
9817 // exposes redundancy in the code.
9818 //
9819 // Note that we cannot do the transformation unless we know that the
9820 // introduced loads cannot trap! Something like this is valid as long as
9821 // the condition is always false: load (select bool %C, int* null, int* %G),
9822 // but it would not be valid if we transformed it to load from null
9823 // unconditionally.
9824 //
9825 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
9826 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +00009827 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
9828 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerc10aced2004-09-19 18:43:46 +00009829 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner79f0c8e2004-09-20 10:15:10 +00009830 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +00009831 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner79f0c8e2004-09-20 10:15:10 +00009832 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +00009833 return new SelectInst(SI->getCondition(), V1, V2);
9834 }
9835
Chris Lattner684fe212004-09-23 15:46:00 +00009836 // load (select (cond, null, P)) -> load P
9837 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
9838 if (C->isNullValue()) {
9839 LI.setOperand(0, SI->getOperand(2));
9840 return &LI;
9841 }
9842
9843 // load (select (cond, P, null)) -> load P
9844 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
9845 if (C->isNullValue()) {
9846 LI.setOperand(0, SI->getOperand(1));
9847 return &LI;
9848 }
Chris Lattnerc10aced2004-09-19 18:43:46 +00009849 }
9850 }
Chris Lattner833b8a42003-06-26 05:06:25 +00009851 return 0;
9852}
9853
Reid Spencer55af2b52007-01-19 21:20:31 +00009854/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009855/// when possible.
9856static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
9857 User *CI = cast<User>(SI.getOperand(1));
9858 Value *CastOp = CI->getOperand(0);
9859
9860 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
9861 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
9862 const Type *SrcPTy = SrcTy->getElementType();
9863
Reid Spencer42230162007-01-22 05:51:25 +00009864 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009865 // If the source is an array, the code below will not succeed. Check to
9866 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
9867 // constants.
9868 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
9869 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
9870 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +00009871 Value* Idxs[2];
9872 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
9873 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009874 SrcTy = cast<PointerType>(CastOp->getType());
9875 SrcPTy = SrcTy->getElementType();
9876 }
9877
Reid Spencer67f827c2007-01-20 23:35:48 +00009878 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
9879 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
9880 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009881
9882 // Okay, we are casting from one integer or pointer type to another of
Reid Spencer75153962007-01-18 18:54:33 +00009883 // the same size. Instead of casting the pointer before
9884 // the store, cast the value to be stored.
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009885 Value *NewCast;
Reid Spencerd977d862006-12-12 23:36:14 +00009886 Value *SIOp0 = SI.getOperand(0);
Reid Spencer75153962007-01-18 18:54:33 +00009887 Instruction::CastOps opcode = Instruction::BitCast;
9888 const Type* CastSrcTy = SIOp0->getType();
9889 const Type* CastDstTy = SrcPTy;
9890 if (isa<PointerType>(CastDstTy)) {
9891 if (CastSrcTy->isInteger())
Reid Spencerd977d862006-12-12 23:36:14 +00009892 opcode = Instruction::IntToPtr;
Reid Spencer67f827c2007-01-20 23:35:48 +00009893 } else if (isa<IntegerType>(CastDstTy)) {
Reid Spencerc55b2432006-12-13 18:21:21 +00009894 if (isa<PointerType>(SIOp0->getType()))
Reid Spencerd977d862006-12-12 23:36:14 +00009895 opcode = Instruction::PtrToInt;
9896 }
9897 if (Constant *C = dyn_cast<Constant>(SIOp0))
Reid Spencer75153962007-01-18 18:54:33 +00009898 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009899 else
Reid Spencer3da59db2006-11-27 01:05:10 +00009900 NewCast = IC.InsertNewInstBefore(
Reid Spencer75153962007-01-18 18:54:33 +00009901 CastInst::create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
9902 SI);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009903 return new StoreInst(NewCast, CastOp);
9904 }
9905 }
9906 }
9907 return 0;
9908}
9909
Chris Lattner2f503e62005-01-31 05:36:43 +00009910Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
9911 Value *Val = SI.getOperand(0);
9912 Value *Ptr = SI.getOperand(1);
9913
9914 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner9ca96412006-02-08 03:25:32 +00009915 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +00009916 ++NumCombined;
9917 return 0;
9918 }
Chris Lattner836692d2007-01-15 06:51:56 +00009919
9920 // If the RHS is an alloca with a single use, zapify the store, making the
9921 // alloca dead.
9922 if (Ptr->hasOneUse()) {
9923 if (isa<AllocaInst>(Ptr)) {
9924 EraseInstFromFunction(SI);
9925 ++NumCombined;
9926 return 0;
9927 }
9928
9929 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
9930 if (isa<AllocaInst>(GEP->getOperand(0)) &&
9931 GEP->getOperand(0)->hasOneUse()) {
9932 EraseInstFromFunction(SI);
9933 ++NumCombined;
9934 return 0;
9935 }
9936 }
Chris Lattner2f503e62005-01-31 05:36:43 +00009937
Dan Gohman9941f742007-07-20 16:34:21 +00009938 // Attempt to improve the alignment.
Chris Lattnerf2369f22007-08-09 19:05:49 +00009939 unsigned KnownAlign = GetOrEnforceKnownAlignment(Ptr, TD);
Dan Gohman9941f742007-07-20 16:34:21 +00009940 if (KnownAlign > SI.getAlignment())
9941 SI.setAlignment(KnownAlign);
9942
Chris Lattner9ca96412006-02-08 03:25:32 +00009943 // Do really simple DSE, to catch cases where there are several consequtive
9944 // stores to the same location, separated by a few arithmetic operations. This
9945 // situation often occurs with bitfield accesses.
9946 BasicBlock::iterator BBI = &SI;
9947 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
9948 --ScanInsts) {
9949 --BBI;
9950
9951 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
9952 // Prev store isn't volatile, and stores to the same location?
9953 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
9954 ++NumDeadStore;
9955 ++BBI;
9956 EraseInstFromFunction(*PrevSI);
9957 continue;
9958 }
9959 break;
9960 }
9961
Chris Lattnerb4db97f2006-05-26 19:19:20 +00009962 // If this is a load, we have to stop. However, if the loaded value is from
9963 // the pointer we're loading and is producing the pointer we're storing,
9964 // then *this* store is dead (X = load P; store X -> P).
9965 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Chris Lattnera54c7eb2007-09-07 05:33:03 +00009966 if (LI == Val && LI->getOperand(0) == Ptr && !SI.isVolatile()) {
Chris Lattnerb4db97f2006-05-26 19:19:20 +00009967 EraseInstFromFunction(SI);
9968 ++NumCombined;
9969 return 0;
9970 }
9971 // Otherwise, this is a load from some other location. Stores before it
9972 // may not be dead.
9973 break;
9974 }
9975
Chris Lattner9ca96412006-02-08 03:25:32 +00009976 // Don't skip over loads or things that can modify memory.
Chris Lattnerb4db97f2006-05-26 19:19:20 +00009977 if (BBI->mayWriteToMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +00009978 break;
9979 }
9980
9981
9982 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +00009983
9984 // store X, null -> turns into 'unreachable' in SimplifyCFG
9985 if (isa<ConstantPointerNull>(Ptr)) {
9986 if (!isa<UndefValue>(Val)) {
9987 SI.setOperand(0, UndefValue::get(Val->getType()));
9988 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattnerdbab3862007-03-02 21:28:56 +00009989 AddToWorkList(U); // Dropped a use.
Chris Lattner2f503e62005-01-31 05:36:43 +00009990 ++NumCombined;
9991 }
9992 return 0; // Do not modify these!
9993 }
9994
9995 // store undef, Ptr -> noop
9996 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +00009997 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +00009998 ++NumCombined;
9999 return 0;
10000 }
10001
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010002 // If the pointer destination is a cast, see if we can fold the cast into the
10003 // source instead.
Reid Spencer3ed469c2006-11-02 20:25:50 +000010004 if (isa<CastInst>(Ptr))
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010005 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10006 return Res;
10007 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer3da59db2006-11-27 01:05:10 +000010008 if (CE->isCast())
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010009 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10010 return Res;
10011
Chris Lattner408902b2005-09-12 23:23:25 +000010012
10013 // If this store is the last instruction in the basic block, and if the block
10014 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner9ca96412006-02-08 03:25:32 +000010015 BBI = &SI; ++BBI;
Chris Lattner408902b2005-09-12 23:23:25 +000010016 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
Chris Lattner3284d1f2007-04-15 00:07:55 +000010017 if (BI->isUnconditional())
10018 if (SimplifyStoreAtEndOfBlock(SI))
10019 return 0; // xform done!
Chris Lattner408902b2005-09-12 23:23:25 +000010020
Chris Lattner2f503e62005-01-31 05:36:43 +000010021 return 0;
10022}
10023
Chris Lattner3284d1f2007-04-15 00:07:55 +000010024/// SimplifyStoreAtEndOfBlock - Turn things like:
10025/// if () { *P = v1; } else { *P = v2 }
10026/// into a phi node with a store in the successor.
10027///
Chris Lattner31755a02007-04-15 01:02:18 +000010028/// Simplify things like:
10029/// *P = v1; if () { *P = v2; }
10030/// into a phi node with a store in the successor.
10031///
Chris Lattner3284d1f2007-04-15 00:07:55 +000010032bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
10033 BasicBlock *StoreBB = SI.getParent();
10034
10035 // Check to see if the successor block has exactly two incoming edges. If
10036 // so, see if the other predecessor contains a store to the same location.
10037 // if so, insert a PHI node (if needed) and move the stores down.
Chris Lattner31755a02007-04-15 01:02:18 +000010038 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Chris Lattner3284d1f2007-04-15 00:07:55 +000010039
10040 // Determine whether Dest has exactly two predecessors and, if so, compute
10041 // the other predecessor.
Chris Lattner31755a02007-04-15 01:02:18 +000010042 pred_iterator PI = pred_begin(DestBB);
10043 BasicBlock *OtherBB = 0;
Chris Lattner3284d1f2007-04-15 00:07:55 +000010044 if (*PI != StoreBB)
Chris Lattner31755a02007-04-15 01:02:18 +000010045 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000010046 ++PI;
Chris Lattner31755a02007-04-15 01:02:18 +000010047 if (PI == pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000010048 return false;
10049
10050 if (*PI != StoreBB) {
Chris Lattner31755a02007-04-15 01:02:18 +000010051 if (OtherBB)
Chris Lattner3284d1f2007-04-15 00:07:55 +000010052 return false;
Chris Lattner31755a02007-04-15 01:02:18 +000010053 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000010054 }
Chris Lattner31755a02007-04-15 01:02:18 +000010055 if (++PI != pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000010056 return false;
10057
10058
Chris Lattner31755a02007-04-15 01:02:18 +000010059 // Verify that the other block ends in a branch and is not otherwise empty.
10060 BasicBlock::iterator BBI = OtherBB->getTerminator();
Chris Lattner3284d1f2007-04-15 00:07:55 +000010061 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
Chris Lattner31755a02007-04-15 01:02:18 +000010062 if (!OtherBr || BBI == OtherBB->begin())
Chris Lattner3284d1f2007-04-15 00:07:55 +000010063 return false;
10064
Chris Lattner31755a02007-04-15 01:02:18 +000010065 // If the other block ends in an unconditional branch, check for the 'if then
10066 // else' case. there is an instruction before the branch.
10067 StoreInst *OtherStore = 0;
10068 if (OtherBr->isUnconditional()) {
10069 // If this isn't a store, or isn't a store to the same location, bail out.
10070 --BBI;
10071 OtherStore = dyn_cast<StoreInst>(BBI);
10072 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
10073 return false;
10074 } else {
Chris Lattnerd717c182007-05-05 22:32:24 +000010075 // Otherwise, the other block ended with a conditional branch. If one of the
Chris Lattner31755a02007-04-15 01:02:18 +000010076 // destinations is StoreBB, then we have the if/then case.
10077 if (OtherBr->getSuccessor(0) != StoreBB &&
10078 OtherBr->getSuccessor(1) != StoreBB)
10079 return false;
10080
10081 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
Chris Lattnerd717c182007-05-05 22:32:24 +000010082 // if/then triangle. See if there is a store to the same ptr as SI that
10083 // lives in OtherBB.
Chris Lattner31755a02007-04-15 01:02:18 +000010084 for (;; --BBI) {
10085 // Check to see if we find the matching store.
10086 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
10087 if (OtherStore->getOperand(1) != SI.getOperand(1))
10088 return false;
10089 break;
10090 }
Chris Lattnerd717c182007-05-05 22:32:24 +000010091 // If we find something that may be using the stored value, or if we run
10092 // out of instructions, we can't do the xform.
Chris Lattner31755a02007-04-15 01:02:18 +000010093 if (isa<LoadInst>(BBI) || BBI->mayWriteToMemory() ||
10094 BBI == OtherBB->begin())
10095 return false;
10096 }
10097
10098 // In order to eliminate the store in OtherBr, we have to
10099 // make sure nothing reads the stored value in StoreBB.
10100 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
10101 // FIXME: This should really be AA driven.
10102 if (isa<LoadInst>(I) || I->mayWriteToMemory())
10103 return false;
10104 }
10105 }
Chris Lattner3284d1f2007-04-15 00:07:55 +000010106
Chris Lattner31755a02007-04-15 01:02:18 +000010107 // Insert a PHI node now if we need it.
Chris Lattner3284d1f2007-04-15 00:07:55 +000010108 Value *MergedVal = OtherStore->getOperand(0);
10109 if (MergedVal != SI.getOperand(0)) {
10110 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
10111 PN->reserveOperandSpace(2);
10112 PN->addIncoming(SI.getOperand(0), SI.getParent());
Chris Lattner31755a02007-04-15 01:02:18 +000010113 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
10114 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Chris Lattner3284d1f2007-04-15 00:07:55 +000010115 }
10116
10117 // Advance to a place where it is safe to insert the new store and
10118 // insert it.
Chris Lattner31755a02007-04-15 01:02:18 +000010119 BBI = DestBB->begin();
Chris Lattner3284d1f2007-04-15 00:07:55 +000010120 while (isa<PHINode>(BBI)) ++BBI;
10121 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
10122 OtherStore->isVolatile()), *BBI);
10123
10124 // Nuke the old stores.
10125 EraseInstFromFunction(SI);
10126 EraseInstFromFunction(*OtherStore);
10127 ++NumCombined;
10128 return true;
10129}
10130
Chris Lattner2f503e62005-01-31 05:36:43 +000010131
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000010132Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
10133 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +000010134 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000010135 BasicBlock *TrueDest;
10136 BasicBlock *FalseDest;
10137 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
10138 !isa<Constant>(X)) {
10139 // Swap Destinations and condition...
10140 BI.setCondition(X);
10141 BI.setSuccessor(0, FalseDest);
10142 BI.setSuccessor(1, TrueDest);
10143 return &BI;
10144 }
10145
Reid Spencere4d87aa2006-12-23 06:05:41 +000010146 // Cannonicalize fcmp_one -> fcmp_oeq
10147 FCmpInst::Predicate FPred; Value *Y;
10148 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
10149 TrueDest, FalseDest)))
10150 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
10151 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
10152 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000010153 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
Chris Lattner6934a042007-02-11 01:23:03 +000010154 Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
10155 NewSCC->takeName(I);
Reid Spencere4d87aa2006-12-23 06:05:41 +000010156 // Swap Destinations and condition...
10157 BI.setCondition(NewSCC);
10158 BI.setSuccessor(0, FalseDest);
10159 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000010160 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000010161 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000010162 AddToWorkList(NewSCC);
Reid Spencere4d87aa2006-12-23 06:05:41 +000010163 return &BI;
10164 }
10165
10166 // Cannonicalize icmp_ne -> icmp_eq
10167 ICmpInst::Predicate IPred;
10168 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
10169 TrueDest, FalseDest)))
10170 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
10171 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
10172 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
10173 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000010174 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
Chris Lattner6934a042007-02-11 01:23:03 +000010175 Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
10176 NewSCC->takeName(I);
Chris Lattner40f5d702003-06-04 05:10:11 +000010177 // Swap Destinations and condition...
Chris Lattneracd1f0f2004-07-30 07:50:03 +000010178 BI.setCondition(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000010179 BI.setSuccessor(0, FalseDest);
10180 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000010181 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000010182 I->eraseFromParent();;
Chris Lattnerdbab3862007-03-02 21:28:56 +000010183 AddToWorkList(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000010184 return &BI;
10185 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010186
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000010187 return 0;
10188}
Chris Lattner0864acf2002-11-04 16:18:53 +000010189
Chris Lattner46238a62004-07-03 00:26:11 +000010190Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
10191 Value *Cond = SI.getCondition();
10192 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
10193 if (I->getOpcode() == Instruction::Add)
10194 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
10195 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
10196 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattnere87597f2004-10-16 18:11:37 +000010197 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +000010198 AddRHS));
10199 SI.setOperand(0, I->getOperand(0));
Chris Lattnerdbab3862007-03-02 21:28:56 +000010200 AddToWorkList(I);
Chris Lattner46238a62004-07-03 00:26:11 +000010201 return &SI;
10202 }
10203 }
10204 return 0;
10205}
10206
Chris Lattner220b0cf2006-03-05 00:22:33 +000010207/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
10208/// is to leave as a vector operation.
10209static bool CheapToScalarize(Value *V, bool isConstant) {
10210 if (isa<ConstantAggregateZero>(V))
10211 return true;
Reid Spencer9d6565a2007-02-15 02:26:10 +000010212 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000010213 if (isConstant) return true;
10214 // If all elts are the same, we can extract.
10215 Constant *Op0 = C->getOperand(0);
10216 for (unsigned i = 1; i < C->getNumOperands(); ++i)
10217 if (C->getOperand(i) != Op0)
10218 return false;
10219 return true;
10220 }
10221 Instruction *I = dyn_cast<Instruction>(V);
10222 if (!I) return false;
10223
10224 // Insert element gets simplified to the inserted element or is deleted if
10225 // this is constant idx extract element and its a constant idx insertelt.
10226 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
10227 isa<ConstantInt>(I->getOperand(2)))
10228 return true;
10229 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
10230 return true;
10231 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
10232 if (BO->hasOneUse() &&
10233 (CheapToScalarize(BO->getOperand(0), isConstant) ||
10234 CheapToScalarize(BO->getOperand(1), isConstant)))
10235 return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +000010236 if (CmpInst *CI = dyn_cast<CmpInst>(I))
10237 if (CI->hasOneUse() &&
10238 (CheapToScalarize(CI->getOperand(0), isConstant) ||
10239 CheapToScalarize(CI->getOperand(1), isConstant)))
10240 return true;
Chris Lattner220b0cf2006-03-05 00:22:33 +000010241
10242 return false;
10243}
10244
Chris Lattnerd2b7cec2007-02-14 05:52:17 +000010245/// Read and decode a shufflevector mask.
10246///
10247/// It turns undef elements into values that are larger than the number of
10248/// elements in the input.
Chris Lattner863bcff2006-05-25 23:48:38 +000010249static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
10250 unsigned NElts = SVI->getType()->getNumElements();
10251 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
10252 return std::vector<unsigned>(NElts, 0);
10253 if (isa<UndefValue>(SVI->getOperand(2)))
10254 return std::vector<unsigned>(NElts, 2*NElts);
10255
10256 std::vector<unsigned> Result;
Reid Spencer9d6565a2007-02-15 02:26:10 +000010257 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Chris Lattner863bcff2006-05-25 23:48:38 +000010258 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
10259 if (isa<UndefValue>(CP->getOperand(i)))
10260 Result.push_back(NElts*2); // undef -> 8
10261 else
Reid Spencerb83eb642006-10-20 07:07:24 +000010262 Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
Chris Lattner863bcff2006-05-25 23:48:38 +000010263 return Result;
10264}
10265
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010266/// FindScalarElement - Given a vector and an element number, see if the scalar
10267/// value is already around as a register, for example if it were inserted then
10268/// extracted from the vector.
10269static Value *FindScalarElement(Value *V, unsigned EltNo) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000010270 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
10271 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +000010272 unsigned Width = PTy->getNumElements();
10273 if (EltNo >= Width) // Out of range access.
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010274 return UndefValue::get(PTy->getElementType());
10275
10276 if (isa<UndefValue>(V))
10277 return UndefValue::get(PTy->getElementType());
10278 else if (isa<ConstantAggregateZero>(V))
10279 return Constant::getNullValue(PTy->getElementType());
Reid Spencer9d6565a2007-02-15 02:26:10 +000010280 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010281 return CP->getOperand(EltNo);
10282 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
10283 // If this is an insert to a variable element, we don't know what it is.
Reid Spencerb83eb642006-10-20 07:07:24 +000010284 if (!isa<ConstantInt>(III->getOperand(2)))
10285 return 0;
10286 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010287
10288 // If this is an insert to the element we are looking for, return the
10289 // inserted value.
Reid Spencerb83eb642006-10-20 07:07:24 +000010290 if (EltNo == IIElt)
10291 return III->getOperand(1);
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010292
10293 // Otherwise, the insertelement doesn't modify the value, recurse on its
10294 // vector input.
10295 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner389a6f52006-04-10 23:06:36 +000010296 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Chris Lattner863bcff2006-05-25 23:48:38 +000010297 unsigned InEl = getShuffleMask(SVI)[EltNo];
10298 if (InEl < Width)
10299 return FindScalarElement(SVI->getOperand(0), InEl);
10300 else if (InEl < Width*2)
10301 return FindScalarElement(SVI->getOperand(1), InEl - Width);
10302 else
10303 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010304 }
10305
10306 // Otherwise, we don't know.
10307 return 0;
10308}
10309
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010310Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010311
Dan Gohman07a96762007-07-16 14:29:03 +000010312 // If vector val is undef, replace extract with scalar undef.
Chris Lattner1f13c882006-03-31 18:25:14 +000010313 if (isa<UndefValue>(EI.getOperand(0)))
10314 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10315
Dan Gohman07a96762007-07-16 14:29:03 +000010316 // If vector val is constant 0, replace extract with scalar 0.
Chris Lattner1f13c882006-03-31 18:25:14 +000010317 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
10318 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
10319
Reid Spencer9d6565a2007-02-15 02:26:10 +000010320 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Dan Gohman07a96762007-07-16 14:29:03 +000010321 // If vector val is constant with uniform operands, replace EI
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010322 // with that operand
Chris Lattner220b0cf2006-03-05 00:22:33 +000010323 Constant *op0 = C->getOperand(0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010324 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +000010325 if (C->getOperand(i) != op0) {
10326 op0 = 0;
10327 break;
10328 }
10329 if (op0)
10330 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010331 }
Chris Lattner220b0cf2006-03-05 00:22:33 +000010332
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010333 // If extracting a specified index from the vector, see if we can recursively
10334 // find a previously computed scalar that was inserted into the vector.
Reid Spencerb83eb642006-10-20 07:07:24 +000010335 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner85464092007-04-09 01:37:55 +000010336 unsigned IndexVal = IdxC->getZExtValue();
10337 unsigned VectorWidth =
10338 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
10339
10340 // If this is extracting an invalid index, turn this into undef, to avoid
10341 // crashing the code below.
10342 if (IndexVal >= VectorWidth)
10343 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10344
Chris Lattner867b99f2006-10-05 06:55:50 +000010345 // This instruction only demands the single element from the input vector.
10346 // If the input vector has a single use, simplify it based on this use
10347 // property.
Chris Lattner85464092007-04-09 01:37:55 +000010348 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Chris Lattner867b99f2006-10-05 06:55:50 +000010349 uint64_t UndefElts;
10350 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Reid Spencerb83eb642006-10-20 07:07:24 +000010351 1 << IndexVal,
Chris Lattner867b99f2006-10-05 06:55:50 +000010352 UndefElts)) {
10353 EI.setOperand(0, V);
10354 return &EI;
10355 }
10356 }
10357
Reid Spencerb83eb642006-10-20 07:07:24 +000010358 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010359 return ReplaceInstUsesWith(EI, Elt);
Chris Lattnerb7300fa2007-04-14 23:02:14 +000010360
10361 // If the this extractelement is directly using a bitcast from a vector of
10362 // the same number of elements, see if we can find the source element from
10363 // it. In this case, we will end up needing to bitcast the scalars.
10364 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
10365 if (const VectorType *VT =
10366 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
10367 if (VT->getNumElements() == VectorWidth)
10368 if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
10369 return new BitCastInst(Elt, EI.getType());
10370 }
Chris Lattner389a6f52006-04-10 23:06:36 +000010371 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010372
Chris Lattner73fa49d2006-05-25 22:53:38 +000010373 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010374 if (I->hasOneUse()) {
10375 // Push extractelement into predecessor operation if legal and
10376 // profitable to do so
10377 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000010378 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
10379 if (CheapToScalarize(BO, isConstantElt)) {
10380 ExtractElementInst *newEI0 =
10381 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
10382 EI.getName()+".lhs");
10383 ExtractElementInst *newEI1 =
10384 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
10385 EI.getName()+".rhs");
10386 InsertNewInstBefore(newEI0, EI);
10387 InsertNewInstBefore(newEI1, EI);
10388 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
10389 }
Reid Spencer3ed469c2006-11-02 20:25:50 +000010390 } else if (isa<LoadInst>(I)) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +000010391 unsigned AS =
10392 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +000010393 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
10394 PointerType::get(EI.getType(), AS),EI);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010395 GetElementPtrInst *GEP =
Reid Spencerde331242006-11-29 01:11:01 +000010396 new GetElementPtrInst(Ptr, EI.getOperand(1), I->getName() + ".gep");
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010397 InsertNewInstBefore(GEP, EI);
10398 return new LoadInst(GEP);
Chris Lattner73fa49d2006-05-25 22:53:38 +000010399 }
10400 }
10401 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
10402 // Extracting the inserted element?
10403 if (IE->getOperand(2) == EI.getOperand(1))
10404 return ReplaceInstUsesWith(EI, IE->getOperand(1));
10405 // If the inserted and extracted elements are constants, they must not
10406 // be the same value, extract from the pre-inserted value instead.
10407 if (isa<Constant>(IE->getOperand(2)) &&
10408 isa<Constant>(EI.getOperand(1))) {
10409 AddUsesToWorkList(EI);
10410 EI.setOperand(0, IE->getOperand(0));
10411 return &EI;
10412 }
10413 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
10414 // If this is extracting an element from a shufflevector, figure out where
10415 // it came from and extract from the appropriate input element instead.
Reid Spencerb83eb642006-10-20 07:07:24 +000010416 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
10417 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner863bcff2006-05-25 23:48:38 +000010418 Value *Src;
10419 if (SrcIdx < SVI->getType()->getNumElements())
10420 Src = SVI->getOperand(0);
10421 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
10422 SrcIdx -= SVI->getType()->getNumElements();
10423 Src = SVI->getOperand(1);
10424 } else {
10425 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +000010426 }
Chris Lattner867b99f2006-10-05 06:55:50 +000010427 return new ExtractElementInst(Src, SrcIdx);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010428 }
10429 }
Chris Lattner73fa49d2006-05-25 22:53:38 +000010430 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010431 return 0;
10432}
10433
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010434/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
10435/// elements from either LHS or RHS, return the shuffle mask and true.
10436/// Otherwise, return false.
10437static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
10438 std::vector<Constant*> &Mask) {
10439 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
10440 "Invalid CollectSingleShuffleElements");
Reid Spencer9d6565a2007-02-15 02:26:10 +000010441 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010442
10443 if (isa<UndefValue>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010444 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010445 return true;
10446 } else if (V == LHS) {
10447 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000010448 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010449 return true;
10450 } else if (V == RHS) {
10451 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000010452 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010453 return true;
10454 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
10455 // If this is an insert of an extract from some other vector, include it.
10456 Value *VecOp = IEI->getOperand(0);
10457 Value *ScalarOp = IEI->getOperand(1);
10458 Value *IdxOp = IEI->getOperand(2);
10459
Chris Lattnerd929f062006-04-27 21:14:21 +000010460 if (!isa<ConstantInt>(IdxOp))
10461 return false;
Reid Spencerb83eb642006-10-20 07:07:24 +000010462 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerd929f062006-04-27 21:14:21 +000010463
10464 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
10465 // Okay, we can handle this if the vector we are insertinting into is
10466 // transitively ok.
10467 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
10468 // If so, update the mask to reflect the inserted undef.
Reid Spencerc5b206b2006-12-31 05:48:39 +000010469 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
Chris Lattnerd929f062006-04-27 21:14:21 +000010470 return true;
10471 }
10472 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
10473 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010474 EI->getOperand(0)->getType() == V->getType()) {
10475 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000010476 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010477
10478 // This must be extracting from either LHS or RHS.
10479 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
10480 // Okay, we can handle this if the vector we are insertinting into is
10481 // transitively ok.
10482 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
10483 // If so, update the mask to reflect the inserted value.
10484 if (EI->getOperand(0) == LHS) {
10485 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000010486 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010487 } else {
10488 assert(EI->getOperand(0) == RHS);
10489 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000010490 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010491
10492 }
10493 return true;
10494 }
10495 }
10496 }
10497 }
10498 }
10499 // TODO: Handle shufflevector here!
10500
10501 return false;
10502}
10503
10504/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
10505/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
10506/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +000010507static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010508 Value *&RHS) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000010509 assert(isa<VectorType>(V->getType()) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010510 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +000010511 "Invalid shuffle!");
Reid Spencer9d6565a2007-02-15 02:26:10 +000010512 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattnerefb47352006-04-15 01:39:45 +000010513
10514 if (isa<UndefValue>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010515 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000010516 return V;
10517 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010518 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
Chris Lattnerefb47352006-04-15 01:39:45 +000010519 return V;
10520 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
10521 // If this is an insert of an extract from some other vector, include it.
10522 Value *VecOp = IEI->getOperand(0);
10523 Value *ScalarOp = IEI->getOperand(1);
10524 Value *IdxOp = IEI->getOperand(2);
10525
10526 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
10527 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
10528 EI->getOperand(0)->getType() == V->getType()) {
10529 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000010530 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
10531 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000010532
10533 // Either the extracted from or inserted into vector must be RHSVec,
10534 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010535 if (EI->getOperand(0) == RHS || RHS == 0) {
10536 RHS = EI->getOperand(0);
10537 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +000010538 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000010539 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000010540 return V;
10541 }
10542
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010543 if (VecOp == RHS) {
10544 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +000010545 // Everything but the extracted element is replaced with the RHS.
10546 for (unsigned i = 0; i != NumElts; ++i) {
10547 if (i != InsertedIdx)
Reid Spencerc5b206b2006-12-31 05:48:39 +000010548 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
Chris Lattnerefb47352006-04-15 01:39:45 +000010549 }
10550 return V;
10551 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010552
10553 // If this insertelement is a chain that comes from exactly these two
10554 // vectors, return the vector and the effective shuffle.
10555 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
10556 return EI->getOperand(0);
10557
Chris Lattnerefb47352006-04-15 01:39:45 +000010558 }
10559 }
10560 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010561 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +000010562
10563 // Otherwise, can't do anything fancy. Return an identity vector.
10564 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000010565 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattnerefb47352006-04-15 01:39:45 +000010566 return V;
10567}
10568
10569Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
10570 Value *VecOp = IE.getOperand(0);
10571 Value *ScalarOp = IE.getOperand(1);
10572 Value *IdxOp = IE.getOperand(2);
10573
Chris Lattner599ded12007-04-09 01:11:16 +000010574 // Inserting an undef or into an undefined place, remove this.
10575 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
10576 ReplaceInstUsesWith(IE, VecOp);
10577
Chris Lattnerefb47352006-04-15 01:39:45 +000010578 // If the inserted element was extracted from some other vector, and if the
10579 // indexes are constant, try to turn this into a shufflevector operation.
10580 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
10581 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
10582 EI->getOperand(0)->getType() == IE.getType()) {
10583 unsigned NumVectorElts = IE.getType()->getNumElements();
Chris Lattnere34e9a22007-04-14 23:32:02 +000010584 unsigned ExtractedIdx =
10585 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Reid Spencerb83eb642006-10-20 07:07:24 +000010586 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000010587
10588 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
10589 return ReplaceInstUsesWith(IE, VecOp);
10590
10591 if (InsertedIdx >= NumVectorElts) // Out of range insert.
10592 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
10593
10594 // If we are extracting a value from a vector, then inserting it right
10595 // back into the same place, just use the input vector.
10596 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
10597 return ReplaceInstUsesWith(IE, VecOp);
10598
10599 // We could theoretically do this for ANY input. However, doing so could
10600 // turn chains of insertelement instructions into a chain of shufflevector
10601 // instructions, and right now we do not merge shufflevectors. As such,
10602 // only do this in a situation where it is clear that there is benefit.
10603 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
10604 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
10605 // the values of VecOp, except then one read from EIOp0.
10606 // Build a new shuffle mask.
10607 std::vector<Constant*> Mask;
10608 if (isa<UndefValue>(VecOp))
Reid Spencerc5b206b2006-12-31 05:48:39 +000010609 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000010610 else {
10611 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Reid Spencerc5b206b2006-12-31 05:48:39 +000010612 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
Chris Lattnerefb47352006-04-15 01:39:45 +000010613 NumVectorElts));
10614 }
Reid Spencerc5b206b2006-12-31 05:48:39 +000010615 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000010616 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Reid Spencer9d6565a2007-02-15 02:26:10 +000010617 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000010618 }
10619
10620 // If this insertelement isn't used by some other insertelement, turn it
10621 // (and any insertelements it points to), into one big shuffle.
10622 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
10623 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010624 Value *RHS = 0;
10625 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
10626 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
10627 // We now have a shuffle of LHS, RHS, Mask.
Reid Spencer9d6565a2007-02-15 02:26:10 +000010628 return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000010629 }
10630 }
10631 }
10632
10633 return 0;
10634}
10635
10636
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010637Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
10638 Value *LHS = SVI.getOperand(0);
10639 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +000010640 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010641
10642 bool MadeChange = false;
10643
Chris Lattner867b99f2006-10-05 06:55:50 +000010644 // Undefined shuffle mask -> undefined value.
Chris Lattner863bcff2006-05-25 23:48:38 +000010645 if (isa<UndefValue>(SVI.getOperand(2)))
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010646 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
10647
Chris Lattnere4929dd2007-01-05 07:36:08 +000010648 // If we have shuffle(x, undef, mask) and any elements of mask refer to
Chris Lattnerefb47352006-04-15 01:39:45 +000010649 // the undef, change them to undefs.
Chris Lattnere4929dd2007-01-05 07:36:08 +000010650 if (isa<UndefValue>(SVI.getOperand(1))) {
10651 // Scan to see if there are any references to the RHS. If so, replace them
10652 // with undef element refs and set MadeChange to true.
10653 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
10654 if (Mask[i] >= e && Mask[i] != 2*e) {
10655 Mask[i] = 2*e;
10656 MadeChange = true;
10657 }
10658 }
10659
10660 if (MadeChange) {
10661 // Remap any references to RHS to use LHS.
10662 std::vector<Constant*> Elts;
10663 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
10664 if (Mask[i] == 2*e)
10665 Elts.push_back(UndefValue::get(Type::Int32Ty));
10666 else
10667 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
10668 }
Reid Spencer9d6565a2007-02-15 02:26:10 +000010669 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattnere4929dd2007-01-05 07:36:08 +000010670 }
10671 }
Chris Lattnerefb47352006-04-15 01:39:45 +000010672
Chris Lattner863bcff2006-05-25 23:48:38 +000010673 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
10674 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
10675 if (LHS == RHS || isa<UndefValue>(LHS)) {
10676 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010677 // shuffle(undef,undef,mask) -> undef.
10678 return ReplaceInstUsesWith(SVI, LHS);
10679 }
10680
Chris Lattner863bcff2006-05-25 23:48:38 +000010681 // Remap any references to RHS to use LHS.
10682 std::vector<Constant*> Elts;
10683 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000010684 if (Mask[i] >= 2*e)
Reid Spencerc5b206b2006-12-31 05:48:39 +000010685 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000010686 else {
10687 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
10688 (Mask[i] < e && isa<UndefValue>(LHS)))
10689 Mask[i] = 2*e; // Turn into undef.
10690 else
10691 Mask[i] &= (e-1); // Force to LHS.
Reid Spencerc5b206b2006-12-31 05:48:39 +000010692 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000010693 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010694 }
Chris Lattner863bcff2006-05-25 23:48:38 +000010695 SVI.setOperand(0, SVI.getOperand(1));
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010696 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Reid Spencer9d6565a2007-02-15 02:26:10 +000010697 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000010698 LHS = SVI.getOperand(0);
10699 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010700 MadeChange = true;
10701 }
10702
Chris Lattner7b2e27922006-05-26 00:29:06 +000010703 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +000010704 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +000010705
Chris Lattner863bcff2006-05-25 23:48:38 +000010706 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
10707 if (Mask[i] >= e*2) continue; // Ignore undef values.
10708 // Is this an identity shuffle of the LHS value?
10709 isLHSID &= (Mask[i] == i);
10710
10711 // Is this an identity shuffle of the RHS value?
10712 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +000010713 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010714
Chris Lattner863bcff2006-05-25 23:48:38 +000010715 // Eliminate identity shuffles.
10716 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
10717 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010718
Chris Lattner7b2e27922006-05-26 00:29:06 +000010719 // If the LHS is a shufflevector itself, see if we can combine it with this
10720 // one without producing an unusual shuffle. Here we are really conservative:
10721 // we are absolutely afraid of producing a shuffle mask not in the input
10722 // program, because the code gen may not be smart enough to turn a merged
10723 // shuffle into two specific shuffles: it may produce worse code. As such,
10724 // we only merge two shuffles if the result is one of the two input shuffle
10725 // masks. In this case, merging the shuffles just removes one instruction,
10726 // which we know is safe. This is good for things like turning:
10727 // (splat(splat)) -> splat.
10728 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
10729 if (isa<UndefValue>(RHS)) {
10730 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
10731
10732 std::vector<unsigned> NewMask;
10733 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
10734 if (Mask[i] >= 2*e)
10735 NewMask.push_back(2*e);
10736 else
10737 NewMask.push_back(LHSMask[Mask[i]]);
10738
10739 // If the result mask is equal to the src shuffle or this shuffle mask, do
10740 // the replacement.
10741 if (NewMask == LHSMask || NewMask == Mask) {
10742 std::vector<Constant*> Elts;
10743 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
10744 if (NewMask[i] >= e*2) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010745 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000010746 } else {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010747 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000010748 }
10749 }
10750 return new ShuffleVectorInst(LHSSVI->getOperand(0),
10751 LHSSVI->getOperand(1),
Reid Spencer9d6565a2007-02-15 02:26:10 +000010752 ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000010753 }
10754 }
10755 }
Chris Lattnerc5eff442007-01-30 22:32:46 +000010756
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010757 return MadeChange ? &SVI : 0;
10758}
10759
10760
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010761
Chris Lattnerea1c4542004-12-08 23:43:58 +000010762
10763/// TryToSinkInstruction - Try to move the specified instruction from its
10764/// current block into the beginning of DestBlock, which can only happen if it's
10765/// safe to move the instruction past all of the instructions between it and the
10766/// end of its block.
10767static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
10768 assert(I->hasOneUse() && "Invariants didn't hold!");
10769
Chris Lattner108e9022005-10-27 17:13:11 +000010770 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
10771 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
Misha Brukmanfd939082005-04-21 23:48:37 +000010772
Chris Lattnerea1c4542004-12-08 23:43:58 +000010773 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +000010774 if (isa<AllocaInst>(I) && I->getParent() ==
10775 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +000010776 return false;
10777
Chris Lattner96a52a62004-12-09 07:14:34 +000010778 // We can only sink load instructions if there is nothing between the load and
10779 // the end of block that could change the value.
10780 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattner96a52a62004-12-09 07:14:34 +000010781 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
10782 Scan != E; ++Scan)
10783 if (Scan->mayWriteToMemory())
10784 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +000010785 }
Chris Lattnerea1c4542004-12-08 23:43:58 +000010786
10787 BasicBlock::iterator InsertPos = DestBlock->begin();
10788 while (isa<PHINode>(InsertPos)) ++InsertPos;
10789
Chris Lattner4bc5f802005-08-08 19:11:57 +000010790 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +000010791 ++NumSunkInst;
10792 return true;
10793}
10794
Chris Lattnerf4f5a772006-05-10 19:00:36 +000010795
10796/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
10797/// all reachable code to the worklist.
10798///
10799/// This has a couple of tricks to make the code faster and more powerful. In
10800/// particular, we constant fold and DCE instructions as we go, to avoid adding
10801/// them to the worklist (this significantly speeds up instcombine on code where
10802/// many instructions are dead or constant). Additionally, if we find a branch
10803/// whose condition is a known constant, we only visit the reachable successors.
10804///
10805static void AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +000010806 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +000010807 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +000010808 const TargetData *TD) {
Chris Lattner2c7718a2007-03-23 19:17:18 +000010809 std::vector<BasicBlock*> Worklist;
10810 Worklist.push_back(BB);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000010811
Chris Lattner2c7718a2007-03-23 19:17:18 +000010812 while (!Worklist.empty()) {
10813 BB = Worklist.back();
10814 Worklist.pop_back();
10815
10816 // We have now visited this block! If we've already been here, ignore it.
10817 if (!Visited.insert(BB)) continue;
10818
10819 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
10820 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000010821
Chris Lattner2c7718a2007-03-23 19:17:18 +000010822 // DCE instruction if trivially dead.
10823 if (isInstructionTriviallyDead(Inst)) {
10824 ++NumDeadInst;
10825 DOUT << "IC: DCE: " << *Inst;
10826 Inst->eraseFromParent();
10827 continue;
10828 }
10829
10830 // ConstantProp instruction if trivially constant.
10831 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
10832 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
10833 Inst->replaceAllUsesWith(C);
10834 ++NumConstProp;
10835 Inst->eraseFromParent();
10836 continue;
10837 }
Chris Lattner3ccc6bc2007-07-20 22:06:41 +000010838
Chris Lattner2c7718a2007-03-23 19:17:18 +000010839 IC.AddToWorkList(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000010840 }
Chris Lattner2c7718a2007-03-23 19:17:18 +000010841
10842 // Recursively visit successors. If this is a branch or switch on a
10843 // constant, only visit the reachable successor.
Nick Lewycky91436992008-03-09 08:50:23 +000010844 if (BB->getUnwindDest())
10845 Worklist.push_back(BB->getUnwindDest());
Chris Lattner2c7718a2007-03-23 19:17:18 +000010846 TerminatorInst *TI = BB->getTerminator();
10847 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
10848 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
10849 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky91436992008-03-09 08:50:23 +000010850 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
10851 if (ReachableBB != BB->getUnwindDest())
10852 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000010853 continue;
10854 }
10855 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
10856 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
10857 // See if this is an explicit destination.
10858 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
10859 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky91436992008-03-09 08:50:23 +000010860 BasicBlock *ReachableBB = SI->getSuccessor(i);
10861 if (ReachableBB != BB->getUnwindDest())
10862 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000010863 continue;
10864 }
10865
10866 // Otherwise it is the default destination.
10867 Worklist.push_back(SI->getSuccessor(0));
10868 continue;
10869 }
10870 }
10871
10872 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
10873 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +000010874 }
Chris Lattnerf4f5a772006-05-10 19:00:36 +000010875}
10876
Chris Lattnerec9c3582007-03-03 02:04:50 +000010877bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000010878 bool Changed = false;
Chris Lattnerbc61e662003-11-02 05:57:39 +000010879 TD = &getAnalysis<TargetData>();
Chris Lattnerec9c3582007-03-03 02:04:50 +000010880
10881 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
10882 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +000010883
Chris Lattnerb3d59702005-07-07 20:40:38 +000010884 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +000010885 // Do a depth-first traversal of the function, populate the worklist with
10886 // the reachable instructions. Ignore blocks that are not reachable. Keep
10887 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +000010888 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerdbab3862007-03-02 21:28:56 +000010889 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +000010890
Chris Lattnerb3d59702005-07-07 20:40:38 +000010891 // Do a quick scan over the function. If we find any blocks that are
10892 // unreachable, remove any instructions inside of them. This prevents
10893 // the instcombine code from having to deal with some bad special cases.
10894 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
10895 if (!Visited.count(BB)) {
10896 Instruction *Term = BB->getTerminator();
10897 while (Term != BB->begin()) { // Remove instrs bottom-up
10898 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +000010899
Bill Wendlingb7427032006-11-26 09:46:52 +000010900 DOUT << "IC: DCE: " << *I;
Chris Lattnerb3d59702005-07-07 20:40:38 +000010901 ++NumDeadInst;
10902
10903 if (!I->use_empty())
10904 I->replaceAllUsesWith(UndefValue::get(I->getType()));
10905 I->eraseFromParent();
10906 }
10907 }
10908 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000010909
Chris Lattnerdbab3862007-03-02 21:28:56 +000010910 while (!Worklist.empty()) {
10911 Instruction *I = RemoveOneFromWorkList();
10912 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +000010913
Chris Lattner8c8c66a2006-05-11 17:11:52 +000010914 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +000010915 if (isInstructionTriviallyDead(I)) {
Chris Lattner8c8c66a2006-05-11 17:11:52 +000010916 // Add operands to the worklist.
Chris Lattner4bb7c022003-10-06 17:11:01 +000010917 if (I->getNumOperands() < 4)
Chris Lattner7bcc0e72004-02-28 05:22:00 +000010918 AddUsesToWorkList(*I);
Chris Lattner62b14df2002-09-02 04:59:56 +000010919 ++NumDeadInst;
Chris Lattner4bb7c022003-10-06 17:11:01 +000010920
Bill Wendlingb7427032006-11-26 09:46:52 +000010921 DOUT << "IC: DCE: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000010922
10923 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000010924 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000010925 continue;
10926 }
Chris Lattner62b14df2002-09-02 04:59:56 +000010927
Chris Lattner8c8c66a2006-05-11 17:11:52 +000010928 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattner0a19ffa2007-01-30 23:16:15 +000010929 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Bill Wendlingb7427032006-11-26 09:46:52 +000010930 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000010931
Chris Lattner8c8c66a2006-05-11 17:11:52 +000010932 // Add operands to the worklist.
Chris Lattner7bcc0e72004-02-28 05:22:00 +000010933 AddUsesToWorkList(*I);
Chris Lattnerc736d562002-12-05 22:41:53 +000010934 ReplaceInstUsesWith(*I, C);
10935
Chris Lattner62b14df2002-09-02 04:59:56 +000010936 ++NumConstProp;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000010937 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000010938 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000010939 continue;
Chris Lattner62b14df2002-09-02 04:59:56 +000010940 }
Chris Lattner4bb7c022003-10-06 17:11:01 +000010941
Chris Lattnerea1c4542004-12-08 23:43:58 +000010942 // See if we can trivially sink this instruction to a successor basic block.
10943 if (I->hasOneUse()) {
10944 BasicBlock *BB = I->getParent();
10945 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
10946 if (UserParent != BB) {
10947 bool UserIsSuccessor = false;
10948 // See if the user is one of our successors.
10949 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
10950 if (*SI == UserParent) {
10951 UserIsSuccessor = true;
10952 break;
10953 }
10954
10955 // If the user is one of our immediate successors, and if that successor
10956 // only has us as a predecessors (we'd have to split the critical edge
10957 // otherwise), we can keep going.
10958 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
10959 next(pred_begin(UserParent)) == pred_end(UserParent))
10960 // Okay, the CFG is simple enough, try to sink this instruction.
10961 Changed |= TryToSinkInstruction(I, UserParent);
10962 }
10963 }
10964
Chris Lattner8a2a3112001-12-14 16:52:21 +000010965 // Now that we have an instruction, try combining it to simplify it...
Reid Spencera9b81012007-03-26 17:44:01 +000010966#ifndef NDEBUG
10967 std::string OrigI;
10968#endif
10969 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
Chris Lattner90ac28c2002-08-02 19:29:35 +000010970 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +000010971 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000010972 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000010973 if (Result != I) {
Bill Wendlingb7427032006-11-26 09:46:52 +000010974 DOUT << "IC: Old = " << *I
10975 << " New = " << *Result;
Chris Lattner0cea42a2004-03-13 23:54:27 +000010976
Chris Lattnerf523d062004-06-09 05:08:07 +000010977 // Everything uses the new instruction now.
10978 I->replaceAllUsesWith(Result);
10979
10980 // Push the new instruction and any users onto the worklist.
Chris Lattnerdbab3862007-03-02 21:28:56 +000010981 AddToWorkList(Result);
Chris Lattnerf523d062004-06-09 05:08:07 +000010982 AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000010983
Chris Lattner6934a042007-02-11 01:23:03 +000010984 // Move the name to the new instruction first.
10985 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000010986
10987 // Insert the new instruction into the basic block...
10988 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +000010989 BasicBlock::iterator InsertPos = I;
10990
10991 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
10992 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
10993 ++InsertPos;
10994
10995 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000010996
Chris Lattner00d51312004-05-01 23:27:23 +000010997 // Make sure that we reprocess all operands now that we reduced their
10998 // use counts.
Chris Lattnerdbab3862007-03-02 21:28:56 +000010999 AddUsesToWorkList(*I);
Chris Lattner216d4d82004-05-01 23:19:52 +000011000
Chris Lattnerf523d062004-06-09 05:08:07 +000011001 // Instructions can end up on the worklist more than once. Make sure
11002 // we do not process an instruction that has been deleted.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011003 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011004
11005 // Erase the old instruction.
11006 InstParent->getInstList().erase(I);
Chris Lattner7e708292002-06-25 16:13:24 +000011007 } else {
Evan Chengc7baf682007-03-27 16:44:48 +000011008#ifndef NDEBUG
Reid Spencera9b81012007-03-26 17:44:01 +000011009 DOUT << "IC: Mod = " << OrigI
11010 << " New = " << *I;
Evan Chengc7baf682007-03-27 16:44:48 +000011011#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +000011012
Chris Lattner90ac28c2002-08-02 19:29:35 +000011013 // If the instruction was modified, it's possible that it is now dead.
11014 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +000011015 if (isInstructionTriviallyDead(I)) {
11016 // Make sure we process all operands now that we are reducing their
11017 // use counts.
Chris Lattnerec9c3582007-03-03 02:04:50 +000011018 AddUsesToWorkList(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000011019
Chris Lattner00d51312004-05-01 23:27:23 +000011020 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011021 // occurrences of this instruction.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011022 RemoveFromWorkList(I);
Chris Lattner2f503e62005-01-31 05:36:43 +000011023 I->eraseFromParent();
Chris Lattnerf523d062004-06-09 05:08:07 +000011024 } else {
Chris Lattnerec9c3582007-03-03 02:04:50 +000011025 AddToWorkList(I);
11026 AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +000011027 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000011028 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011029 Changed = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +000011030 }
11031 }
11032
Chris Lattnerec9c3582007-03-03 02:04:50 +000011033 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattnera9ff5eb2007-08-05 08:47:58 +000011034
11035 // Do an explicit clear, this shrinks the map if needed.
11036 WorklistMap.clear();
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011037 return Changed;
Chris Lattnerbd0ef772002-02-26 21:46:54 +000011038}
11039
Chris Lattnerec9c3582007-03-03 02:04:50 +000011040
11041bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +000011042 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
11043
Chris Lattnerec9c3582007-03-03 02:04:50 +000011044 bool EverMadeChange = false;
11045
11046 // Iterate while there is work to do.
11047 unsigned Iteration = 0;
11048 while (DoOneIteration(F, Iteration++))
11049 EverMadeChange = true;
11050 return EverMadeChange;
11051}
11052
Brian Gaeke96d4bf72004-07-27 17:43:21 +000011053FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011054 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +000011055}
Brian Gaeked0fde302003-11-11 22:41:34 +000011056