blob: 9e069fd05baf1b11c613217a86586b3a12111e87 [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);
Evan Chengb98a10e2008-03-24 00:21:34 +0000239 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
240 bool DoXform = true);
Chris Lattner9fe38862003-06-19 17:00:31 +0000241
Chris Lattner28977af2004-04-05 01:30:19 +0000242 public:
Chris Lattner8b170942002-08-09 23:47:40 +0000243 // InsertNewInstBefore - insert an instruction New before instruction Old
244 // in the program. Add the new instruction to the worklist.
245 //
Chris Lattner955f3312004-09-28 21:48:02 +0000246 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattnere6f9a912002-08-23 18:32:43 +0000247 assert(New && New->getParent() == 0 &&
248 "New instruction already inserted into a basic block!");
Chris Lattner8b170942002-08-09 23:47:40 +0000249 BasicBlock *BB = Old.getParent();
250 BB->getInstList().insert(&Old, New); // Insert inst
Chris Lattnerdbab3862007-03-02 21:28:56 +0000251 AddToWorkList(New);
Chris Lattner4cb170c2004-02-23 06:38:22 +0000252 return New;
Chris Lattner8b170942002-08-09 23:47:40 +0000253 }
254
Chris Lattner0c967662004-09-24 15:21:34 +0000255 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
256 /// This also adds the cast to the worklist. Finally, this returns the
257 /// cast.
Reid Spencer17212df2006-12-12 09:18:51 +0000258 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
259 Instruction &Pos) {
Chris Lattner0c967662004-09-24 15:21:34 +0000260 if (V->getType() == Ty) return V;
Misha Brukmanfd939082005-04-21 23:48:37 +0000261
Chris Lattnere2ed0572006-04-06 19:19:17 +0000262 if (Constant *CV = dyn_cast<Constant>(V))
Reid Spencer17212df2006-12-12 09:18:51 +0000263 return ConstantExpr::getCast(opc, CV, Ty);
Chris Lattnere2ed0572006-04-06 19:19:17 +0000264
Reid Spencer17212df2006-12-12 09:18:51 +0000265 Instruction *C = CastInst::create(opc, V, Ty, V->getName(), &Pos);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000266 AddToWorkList(C);
Chris Lattner0c967662004-09-24 15:21:34 +0000267 return C;
268 }
Chris Lattner6d0339d2008-01-13 22:23:22 +0000269
270 Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
271 return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
272 }
273
Chris Lattner0c967662004-09-24 15:21:34 +0000274
Chris Lattner8b170942002-08-09 23:47:40 +0000275 // ReplaceInstUsesWith - This method is to be used when an instruction is
276 // found to be dead, replacable with another preexisting expression. Here
277 // we add all uses of I to the worklist, replace all uses of I with the new
278 // value, then return I, so that the inst combiner will know that I was
279 // modified.
280 //
281 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000282 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner15a76c02004-04-05 02:10:19 +0000283 if (&I != V) {
284 I.replaceAllUsesWith(V);
285 return &I;
286 } else {
287 // If we are replacing the instruction with itself, this must be in a
288 // segment of unreachable code, so just clobber the instruction.
Chris Lattner17be6352004-10-18 02:59:09 +0000289 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +0000290 return &I;
291 }
Chris Lattner8b170942002-08-09 23:47:40 +0000292 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000293
Chris Lattner6dce1a72006-02-07 06:56:34 +0000294 // UpdateValueUsesWith - This method is to be used when an value is
295 // found to be replacable with another preexisting expression or was
296 // updated. Here we add all uses of I to the worklist, replace all uses of
297 // I with the new value (unless the instruction was just updated), then
298 // return true, so that the inst combiner will know that I was modified.
299 //
300 bool UpdateValueUsesWith(Value *Old, Value *New) {
301 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
302 if (Old != New)
303 Old->replaceAllUsesWith(New);
304 if (Instruction *I = dyn_cast<Instruction>(Old))
Chris Lattnerdbab3862007-03-02 21:28:56 +0000305 AddToWorkList(I);
Chris Lattnerf8c36f52006-02-12 08:02:11 +0000306 if (Instruction *I = dyn_cast<Instruction>(New))
Chris Lattnerdbab3862007-03-02 21:28:56 +0000307 AddToWorkList(I);
Chris Lattner6dce1a72006-02-07 06:56:34 +0000308 return true;
309 }
310
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000311 // EraseInstFromFunction - When dealing with an instruction that has side
312 // effects or produces a void value, we can't rely on DCE to delete the
313 // instruction. Instead, visit methods should return the value returned by
314 // this function.
315 Instruction *EraseInstFromFunction(Instruction &I) {
316 assert(I.use_empty() && "Cannot erase instruction that is used!");
317 AddUsesToWorkList(I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000318 RemoveFromWorkList(&I);
Chris Lattner954f66a2004-11-18 21:41:39 +0000319 I.eraseFromParent();
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000320 return 0; // Don't do anything with FI
321 }
322
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000323 private:
Chris Lattner24c8e382003-07-24 17:35:25 +0000324 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
325 /// InsertBefore instruction. This is specialized a bit to avoid inserting
326 /// casts that are known to not do anything...
327 ///
Reid Spencer17212df2006-12-12 09:18:51 +0000328 Value *InsertOperandCastBefore(Instruction::CastOps opcode,
329 Value *V, const Type *DestTy,
Chris Lattner24c8e382003-07-24 17:35:25 +0000330 Instruction *InsertBefore);
331
Reid Spencere4d87aa2006-12-23 06:05:41 +0000332 /// SimplifyCommutative - This performs a few simplifications for
333 /// commutative operators.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000334 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000335
Reid Spencere4d87aa2006-12-23 06:05:41 +0000336 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
337 /// most-complex to least-complex order.
338 bool SimplifyCompare(CmpInst &I);
339
Reid Spencer2ec619a2007-03-23 21:24:59 +0000340 /// SimplifyDemandedBits - Attempts to replace V with a simpler value based
341 /// on the demanded bits.
Reid Spencer8cb68342007-03-12 17:25:59 +0000342 bool SimplifyDemandedBits(Value *V, APInt DemandedMask,
343 APInt& KnownZero, APInt& KnownOne,
344 unsigned Depth = 0);
345
Chris Lattner867b99f2006-10-05 06:55:50 +0000346 Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
347 uint64_t &UndefElts, unsigned Depth = 0);
348
Chris Lattner4e998b22004-09-29 05:07:12 +0000349 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
350 // PHI node as operand #0, see if we can fold the instruction into the PHI
351 // (which is only possible if all operands to the PHI are constants).
352 Instruction *FoldOpIntoPhi(Instruction &I);
353
Chris Lattnerbac32862004-11-14 19:13:23 +0000354 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
355 // operator and they all are only used by the PHI, PHI together their
356 // inputs, and do the operation once, to the result of the PHI.
357 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
Chris Lattner7da52b22006-11-01 04:51:18 +0000358 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
359
360
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000361 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
362 ConstantInt *AndRHS, BinaryOperator &TheAnd);
Chris Lattnerc8e77562005-09-18 04:24:45 +0000363
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000364 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
Chris Lattnerc8e77562005-09-18 04:24:45 +0000365 bool isSub, Instruction &I);
Chris Lattnera96879a2004-09-29 17:40:11 +0000366 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000367 bool isSigned, bool Inside, Instruction &IB);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000368 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
Chris Lattnerafe91a52006-06-15 19:07:26 +0000369 Instruction *MatchBSwap(BinaryOperator &I);
Chris Lattner3284d1f2007-04-15 00:07:55 +0000370 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000371 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
372
Chris Lattnerafe91a52006-06-15 19:07:26 +0000373
Reid Spencerc55b2432006-12-13 18:21:21 +0000374 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000375 };
Chris Lattnerf6293092002-07-23 18:06:35 +0000376
Devang Patel19974732007-05-03 01:11:54 +0000377 char InstCombiner::ID = 0;
Chris Lattner7f8897f2006-08-27 22:42:52 +0000378 RegisterPass<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000379}
380
Chris Lattner4f98c562003-03-10 21:43:22 +0000381// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattnere87597f2004-10-16 18:11:37 +0000382// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattner4f98c562003-03-10 21:43:22 +0000383static unsigned getComplexity(Value *V) {
384 if (isa<Instruction>(V)) {
385 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattnere87597f2004-10-16 18:11:37 +0000386 return 3;
387 return 4;
Chris Lattner4f98c562003-03-10 21:43:22 +0000388 }
Chris Lattnere87597f2004-10-16 18:11:37 +0000389 if (isa<Argument>(V)) return 3;
390 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattner4f98c562003-03-10 21:43:22 +0000391}
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000392
Chris Lattnerc8802d22003-03-11 00:12:48 +0000393// isOnlyUse - Return true if this instruction will be deleted if we stop using
394// it.
395static bool isOnlyUse(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000396 return V->hasOneUse() || isa<Constant>(V);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000397}
398
Chris Lattner4cb170c2004-02-23 06:38:22 +0000399// getPromotedType - Return the specified type promoted as it would be to pass
400// though a va_arg area...
401static const Type *getPromotedType(const Type *Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000402 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
403 if (ITy->getBitWidth() < 32)
404 return Type::Int32Ty;
Chris Lattner2b7e0ad2007-05-23 01:17:04 +0000405 }
Reid Spencera54b7cb2007-01-12 07:05:14 +0000406 return Ty;
Chris Lattner4cb170c2004-02-23 06:38:22 +0000407}
408
Reid Spencer3da59db2006-11-27 01:05:10 +0000409/// getBitCastOperand - If the specified operand is a CastInst or a constant
410/// expression bitcast, return the operand value, otherwise return null.
411static Value *getBitCastOperand(Value *V) {
412 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
Chris Lattnereed48272005-09-13 00:40:14 +0000413 return I->getOperand(0);
414 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Reid Spencer3da59db2006-11-27 01:05:10 +0000415 if (CE->getOpcode() == Instruction::BitCast)
Chris Lattnereed48272005-09-13 00:40:14 +0000416 return CE->getOperand(0);
417 return 0;
418}
419
Reid Spencer3da59db2006-11-27 01:05:10 +0000420/// This function is a wrapper around CastInst::isEliminableCastPair. It
421/// simply extracts arguments and returns what that function returns.
Reid Spencer3da59db2006-11-27 01:05:10 +0000422static Instruction::CastOps
423isEliminableCastPair(
424 const CastInst *CI, ///< The first cast instruction
425 unsigned opcode, ///< The opcode of the second cast instruction
426 const Type *DstTy, ///< The target type for the second cast instruction
427 TargetData *TD ///< The target data for pointer size
428) {
429
430 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
431 const Type *MidTy = CI->getType(); // B from above
Chris Lattner33a61132006-05-06 09:00:16 +0000432
Reid Spencer3da59db2006-11-27 01:05:10 +0000433 // Get the opcodes of the two Cast instructions
434 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
435 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner33a61132006-05-06 09:00:16 +0000436
Reid Spencer3da59db2006-11-27 01:05:10 +0000437 return Instruction::CastOps(
438 CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
439 DstTy, TD->getIntPtrType()));
Chris Lattner33a61132006-05-06 09:00:16 +0000440}
441
442/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
443/// in any code being generated. It does not require codegen if V is simple
444/// enough or if the cast can be folded into other casts.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000445static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
446 const Type *Ty, TargetData *TD) {
Chris Lattner33a61132006-05-06 09:00:16 +0000447 if (V->getType() == Ty || isa<Constant>(V)) return false;
448
Chris Lattner01575b72006-05-25 23:24:33 +0000449 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner33a61132006-05-06 09:00:16 +0000450 if (const CastInst *CI = dyn_cast<CastInst>(V))
Reid Spencere4d87aa2006-12-23 06:05:41 +0000451 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner33a61132006-05-06 09:00:16 +0000452 return false;
453 return true;
454}
455
456/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
457/// InsertBefore instruction. This is specialized a bit to avoid inserting
458/// casts that are known to not do anything...
459///
Reid Spencer17212df2006-12-12 09:18:51 +0000460Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
461 Value *V, const Type *DestTy,
Chris Lattner33a61132006-05-06 09:00:16 +0000462 Instruction *InsertBefore) {
463 if (V->getType() == DestTy) return V;
464 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencer17212df2006-12-12 09:18:51 +0000465 return ConstantExpr::getCast(opcode, C, DestTy);
Chris Lattner33a61132006-05-06 09:00:16 +0000466
Reid Spencer17212df2006-12-12 09:18:51 +0000467 return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
Chris Lattner33a61132006-05-06 09:00:16 +0000468}
469
Chris Lattner4f98c562003-03-10 21:43:22 +0000470// SimplifyCommutative - This performs a few simplifications for commutative
471// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000472//
Chris Lattner4f98c562003-03-10 21:43:22 +0000473// 1. Order operands such that they are listed from right (least complex) to
474// left (most complex). This puts constants before unary operators before
475// binary operators.
476//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000477// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
478// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000479//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000480bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000481 bool Changed = false;
482 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
483 Changed = !I.swapOperands();
Misha Brukmanfd939082005-04-21 23:48:37 +0000484
Chris Lattner4f98c562003-03-10 21:43:22 +0000485 if (!I.isAssociative()) return Changed;
486 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000487 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
488 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
489 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner2a9c8472003-05-27 16:40:51 +0000490 Constant *Folded = ConstantExpr::get(I.getOpcode(),
491 cast<Constant>(I.getOperand(1)),
492 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000493 I.setOperand(0, Op->getOperand(0));
494 I.setOperand(1, Folded);
495 return true;
496 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
497 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
498 isOnlyUse(Op) && isOnlyUse(Op1)) {
499 Constant *C1 = cast<Constant>(Op->getOperand(1));
500 Constant *C2 = cast<Constant>(Op1->getOperand(1));
501
502 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner2a9c8472003-05-27 16:40:51 +0000503 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000504 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
505 Op1->getOperand(0),
506 Op1->getName(), &I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000507 AddToWorkList(New);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000508 I.setOperand(0, New);
509 I.setOperand(1, Folded);
510 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000511 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000512 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000513 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000514}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000515
Reid Spencere4d87aa2006-12-23 06:05:41 +0000516/// SimplifyCompare - For a CmpInst this function just orders the operands
517/// so that theyare listed from right (least complex) to left (most complex).
518/// This puts constants before unary operators before binary operators.
519bool InstCombiner::SimplifyCompare(CmpInst &I) {
520 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
521 return false;
522 I.swapOperands();
523 // Compare instructions are not associative so there's nothing else we can do.
524 return true;
525}
526
Chris Lattner8d969642003-03-10 23:06:50 +0000527// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
528// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000529//
Chris Lattner8d969642003-03-10 23:06:50 +0000530static inline Value *dyn_castNegVal(Value *V) {
531 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000532 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000533
Chris Lattner0ce85802004-12-14 20:08:06 +0000534 // Constants can be considered to be negated values if they can be folded.
535 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
536 return ConstantExpr::getNeg(C);
Chris Lattner8d969642003-03-10 23:06:50 +0000537 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000538}
539
Chris Lattner8d969642003-03-10 23:06:50 +0000540static inline Value *dyn_castNotVal(Value *V) {
541 if (BinaryOperator::isNot(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000542 return BinaryOperator::getNotArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000543
544 // Constants can be considered to be not'ed values...
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000545 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Zhou Sheng4a1822a2007-04-02 13:45:30 +0000546 return ConstantInt::get(~C->getValue());
Chris Lattner8d969642003-03-10 23:06:50 +0000547 return 0;
548}
549
Chris Lattnerc8802d22003-03-11 00:12:48 +0000550// dyn_castFoldableMul - If this value is a multiply that can be folded into
551// other computations (because it has a constant operand), return the
Chris Lattner50af16a2004-11-13 19:50:12 +0000552// non-constant operand of the multiply, and set CST to point to the multiplier.
553// Otherwise, return null.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000554//
Chris Lattner50af16a2004-11-13 19:50:12 +0000555static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattner42a75512007-01-15 02:27:26 +0000556 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner50af16a2004-11-13 19:50:12 +0000557 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000558 if (I->getOpcode() == Instruction::Mul)
Chris Lattner50e60c72004-11-15 05:54:07 +0000559 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000560 return I->getOperand(0);
Chris Lattner50af16a2004-11-13 19:50:12 +0000561 if (I->getOpcode() == Instruction::Shl)
Chris Lattner50e60c72004-11-15 05:54:07 +0000562 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000563 // The multiplier is really 1 << CST.
Zhou Sheng97b52c22007-03-29 01:57:21 +0000564 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000565 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Zhou Sheng97b52c22007-03-29 01:57:21 +0000566 CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
Chris Lattner50af16a2004-11-13 19:50:12 +0000567 return I->getOperand(0);
568 }
569 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000570 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000571}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000572
Chris Lattner574da9b2005-01-13 20:14:25 +0000573/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
574/// expression, return it.
575static User *dyn_castGetElementPtr(Value *V) {
576 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
577 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
578 if (CE->getOpcode() == Instruction::GetElementPtr)
579 return cast<User>(V);
580 return false;
581}
582
Reid Spencer7177c3a2007-03-25 05:33:51 +0000583/// AddOne - Add one to a ConstantInt
Chris Lattnera96879a2004-09-29 17:40:11 +0000584static ConstantInt *AddOne(ConstantInt *C) {
Reid Spencer2149a9d2007-03-25 19:55:33 +0000585 APInt Val(C->getValue());
586 return ConstantInt::get(++Val);
Chris Lattner955f3312004-09-28 21:48:02 +0000587}
Reid Spencer7177c3a2007-03-25 05:33:51 +0000588/// SubOne - Subtract one from a ConstantInt
Chris Lattnera96879a2004-09-29 17:40:11 +0000589static ConstantInt *SubOne(ConstantInt *C) {
Reid Spencer2149a9d2007-03-25 19:55:33 +0000590 APInt Val(C->getValue());
591 return ConstantInt::get(--Val);
Reid Spencer7177c3a2007-03-25 05:33:51 +0000592}
593/// Add - Add two ConstantInts together
594static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
595 return ConstantInt::get(C1->getValue() + C2->getValue());
596}
597/// And - Bitwise AND two ConstantInts together
598static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
599 return ConstantInt::get(C1->getValue() & C2->getValue());
600}
601/// Subtract - Subtract one ConstantInt from another
602static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
603 return ConstantInt::get(C1->getValue() - C2->getValue());
604}
605/// Multiply - Multiply two ConstantInts together
606static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
607 return ConstantInt::get(C1->getValue() * C2->getValue());
Chris Lattner955f3312004-09-28 21:48:02 +0000608}
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000609/// MultiplyOverflows - True if the multiply can not be expressed in an int
610/// this size.
611static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
612 uint32_t W = C1->getBitWidth();
613 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
614 if (sign) {
615 LHSExt.sext(W * 2);
616 RHSExt.sext(W * 2);
617 } else {
618 LHSExt.zext(W * 2);
619 RHSExt.zext(W * 2);
620 }
621
622 APInt MulExt = LHSExt * RHSExt;
623
624 if (sign) {
625 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
626 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
627 return MulExt.slt(Min) || MulExt.sgt(Max);
628 } else
629 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
630}
Chris Lattner955f3312004-09-28 21:48:02 +0000631
Chris Lattner68d5ff22006-02-09 07:38:58 +0000632/// ComputeMaskedBits - Determine which of the bits specified in Mask are
633/// known to be either zero or one and return them in the KnownZero/KnownOne
Reid Spencer3e7594f2007-03-08 01:46:38 +0000634/// bit sets. This code only analyzes bits in Mask, in order to short-circuit
635/// processing.
636/// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
637/// we cannot optimize based on the assumption that it is zero without changing
638/// it to be an explicit zero. If we don't change it to zero, other code could
639/// optimized based on the contradictory assumption that it is non-zero.
640/// Because instcombine aggressively folds operations with undef args anyway,
641/// this won't lose us code quality.
Reid Spencer55702aa2007-03-25 21:11:44 +0000642static void ComputeMaskedBits(Value *V, const APInt &Mask, APInt& KnownZero,
Reid Spencer3e7594f2007-03-08 01:46:38 +0000643 APInt& KnownOne, unsigned Depth = 0) {
Zhou Sheng771dbf72007-03-13 02:23:10 +0000644 assert(V && "No Value?");
645 assert(Depth <= 6 && "Limit Search Depth");
Reid Spencer3e7594f2007-03-08 01:46:38 +0000646 uint32_t BitWidth = Mask.getBitWidth();
Zhou Shengaa305ab2007-03-28 02:19:03 +0000647 assert(cast<IntegerType>(V->getType())->getBitWidth() == BitWidth &&
Zhou Sheng771dbf72007-03-13 02:23:10 +0000648 KnownZero.getBitWidth() == BitWidth &&
Reid Spencer3e7594f2007-03-08 01:46:38 +0000649 KnownOne.getBitWidth() == BitWidth &&
Zhou Shengaa305ab2007-03-28 02:19:03 +0000650 "V, Mask, KnownOne and KnownZero should have same BitWidth");
Reid Spencer3e7594f2007-03-08 01:46:38 +0000651 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
652 // We know all of the bits for a constant!
Zhou Sheng771dbf72007-03-13 02:23:10 +0000653 KnownOne = CI->getValue() & Mask;
Reid Spencer3e7594f2007-03-08 01:46:38 +0000654 KnownZero = ~KnownOne & Mask;
655 return;
656 }
657
Reid Spencer3e7594f2007-03-08 01:46:38 +0000658 if (Depth == 6 || Mask == 0)
659 return; // Limit search depth.
660
661 Instruction *I = dyn_cast<Instruction>(V);
662 if (!I) return;
663
Zhou Sheng771dbf72007-03-13 02:23:10 +0000664 KnownZero.clear(); KnownOne.clear(); // Don't know anything.
Reid Spencer3e7594f2007-03-08 01:46:38 +0000665 APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000666
667 switch (I->getOpcode()) {
Reid Spencer2b812072007-03-25 02:03:12 +0000668 case Instruction::And: {
Reid Spencer3e7594f2007-03-08 01:46:38 +0000669 // If either the LHS or the RHS are Zero, the result is zero.
670 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
Reid Spencer2b812072007-03-25 02:03:12 +0000671 APInt Mask2(Mask & ~KnownZero);
672 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000673 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
674 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
675
676 // Output known-1 bits are only known if set in both the LHS & RHS.
677 KnownOne &= KnownOne2;
678 // Output known-0 are known to be clear if zero in either the LHS | RHS.
679 KnownZero |= KnownZero2;
680 return;
Reid Spencer2b812072007-03-25 02:03:12 +0000681 }
682 case Instruction::Or: {
Reid Spencer3e7594f2007-03-08 01:46:38 +0000683 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
Reid Spencer2b812072007-03-25 02:03:12 +0000684 APInt Mask2(Mask & ~KnownOne);
685 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000686 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
687 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
688
689 // Output known-0 bits are only known if clear in both the LHS & RHS.
690 KnownZero &= KnownZero2;
691 // Output known-1 are known to be set if set in either the LHS | RHS.
692 KnownOne |= KnownOne2;
693 return;
Reid Spencer2b812072007-03-25 02:03:12 +0000694 }
Reid Spencer3e7594f2007-03-08 01:46:38 +0000695 case Instruction::Xor: {
696 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
697 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
698 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
699 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
700
701 // Output known-0 bits are known if clear or set in both the LHS & RHS.
702 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
703 // Output known-1 are known to be set if set in only one of the LHS, RHS.
704 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
705 KnownZero = KnownZeroOut;
706 return;
707 }
708 case Instruction::Select:
709 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
710 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
711 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
712 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
713
714 // Only known if known in both the LHS and RHS.
715 KnownOne &= KnownOne2;
716 KnownZero &= KnownZero2;
717 return;
718 case Instruction::FPTrunc:
719 case Instruction::FPExt:
720 case Instruction::FPToUI:
721 case Instruction::FPToSI:
722 case Instruction::SIToFP:
723 case Instruction::PtrToInt:
724 case Instruction::UIToFP:
725 case Instruction::IntToPtr:
726 return; // Can't work with floating point or pointers
Zhou Sheng771dbf72007-03-13 02:23:10 +0000727 case Instruction::Trunc: {
Reid Spencer3e7594f2007-03-08 01:46:38 +0000728 // All these have integer operands
Zhou Sheng771dbf72007-03-13 02:23:10 +0000729 uint32_t SrcBitWidth =
730 cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
Zhou Shengaa305ab2007-03-28 02:19:03 +0000731 APInt MaskIn(Mask);
732 MaskIn.zext(SrcBitWidth);
733 KnownZero.zext(SrcBitWidth);
734 KnownOne.zext(SrcBitWidth);
735 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
Zhou Sheng771dbf72007-03-13 02:23:10 +0000736 KnownZero.trunc(BitWidth);
737 KnownOne.trunc(BitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000738 return;
Zhou Sheng771dbf72007-03-13 02:23:10 +0000739 }
Reid Spencer3e7594f2007-03-08 01:46:38 +0000740 case Instruction::BitCast: {
741 const Type *SrcTy = I->getOperand(0)->getType();
742 if (SrcTy->isInteger()) {
743 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
744 return;
745 }
746 break;
747 }
748 case Instruction::ZExt: {
749 // Compute the bits in the result that are not present in the input.
750 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Zhou Sheng771dbf72007-03-13 02:23:10 +0000751 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer2f549172007-03-25 04:26:16 +0000752
Zhou Shengaa305ab2007-03-28 02:19:03 +0000753 APInt MaskIn(Mask);
754 MaskIn.trunc(SrcBitWidth);
755 KnownZero.trunc(SrcBitWidth);
756 KnownOne.trunc(SrcBitWidth);
757 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000758 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
759 // The top bits are known to be zero.
Zhou Sheng771dbf72007-03-13 02:23:10 +0000760 KnownZero.zext(BitWidth);
761 KnownOne.zext(BitWidth);
Zhou Shengaa305ab2007-03-28 02:19:03 +0000762 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000763 return;
764 }
765 case Instruction::SExt: {
766 // Compute the bits in the result that are not present in the input.
767 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Zhou Sheng771dbf72007-03-13 02:23:10 +0000768 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer2f549172007-03-25 04:26:16 +0000769
Zhou Shengaa305ab2007-03-28 02:19:03 +0000770 APInt MaskIn(Mask);
771 MaskIn.trunc(SrcBitWidth);
772 KnownZero.trunc(SrcBitWidth);
773 KnownOne.trunc(SrcBitWidth);
774 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000775 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Zhou Sheng771dbf72007-03-13 02:23:10 +0000776 KnownZero.zext(BitWidth);
777 KnownOne.zext(BitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000778
779 // If the sign bit of the input is known set or clear, then we know the
780 // top bits of the result.
Zhou Shengaa305ab2007-03-28 02:19:03 +0000781 if (KnownZero[SrcBitWidth-1]) // Input sign bit known zero
Zhou Sheng34a4b382007-03-28 17:38:21 +0000782 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Zhou Shengaa305ab2007-03-28 02:19:03 +0000783 else if (KnownOne[SrcBitWidth-1]) // Input sign bit known set
Zhou Sheng34a4b382007-03-28 17:38:21 +0000784 KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000785 return;
786 }
787 case Instruction::Shl:
788 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
789 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000790 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer2b812072007-03-25 02:03:12 +0000791 APInt Mask2(Mask.lshr(ShiftAmt));
792 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000793 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Zhou Sheng430f6262007-03-12 05:44:52 +0000794 KnownZero <<= ShiftAmt;
795 KnownOne <<= ShiftAmt;
Reid Spencer2149a9d2007-03-25 19:55:33 +0000796 KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt); // low bits known 0
Reid Spencer3e7594f2007-03-08 01:46:38 +0000797 return;
798 }
799 break;
800 case Instruction::LShr:
801 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
802 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
803 // Compute the new bits that are at the top now.
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000804 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000805
806 // Unsigned shift right.
Reid Spencer2b812072007-03-25 02:03:12 +0000807 APInt Mask2(Mask.shl(ShiftAmt));
808 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000809 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
810 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
811 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
Zhou Shengaa305ab2007-03-28 02:19:03 +0000812 // high bits known zero.
813 KnownZero |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000814 return;
815 }
816 break;
817 case Instruction::AShr:
Zhou Shengaa305ab2007-03-28 02:19:03 +0000818 // (ashr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
Reid Spencer3e7594f2007-03-08 01:46:38 +0000819 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
820 // Compute the new bits that are at the top now.
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000821 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000822
823 // Signed shift right.
Reid Spencer2b812072007-03-25 02:03:12 +0000824 APInt Mask2(Mask.shl(ShiftAmt));
825 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000826 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
827 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
828 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
829
Zhou Shengaa305ab2007-03-28 02:19:03 +0000830 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
831 if (KnownZero[BitWidth-ShiftAmt-1]) // New bits are known zero.
Reid Spencer3e7594f2007-03-08 01:46:38 +0000832 KnownZero |= HighBits;
Zhou Shengaa305ab2007-03-28 02:19:03 +0000833 else if (KnownOne[BitWidth-ShiftAmt-1]) // New bits are known one.
Reid Spencer3e7594f2007-03-08 01:46:38 +0000834 KnownOne |= HighBits;
Reid Spencer3e7594f2007-03-08 01:46:38 +0000835 return;
836 }
837 break;
Duncan Sands1d57a752008-03-21 08:32:17 +0000838 case Instruction::Add: {
Chris Lattner41dc0fc2008-03-21 05:19:58 +0000839 // If either the LHS or the RHS are Zero, the result is zero.
840 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
841 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
842 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
843 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
844
845 // Output known-0 bits are known if clear or set in both the low clear bits
846 // common to both LHS & RHS. For example, 8+(X<<3) is known to have the
847 // low 3 bits clear.
848 unsigned KnownZeroOut = std::min(KnownZero.countTrailingOnes(),
849 KnownZero2.countTrailingOnes());
850
851 KnownZero = APInt::getLowBitsSet(BitWidth, KnownZeroOut);
852 KnownOne = APInt(BitWidth, 0);
853 return;
Duncan Sands1d57a752008-03-21 08:32:17 +0000854 }
Chris Lattner41dc0fc2008-03-21 05:19:58 +0000855 case Instruction::Sub: {
856 ConstantInt *CLHS = dyn_cast<ConstantInt>(I->getOperand(0));
857 if (!CLHS) break;
858
859 // We know that the top bits of C-X are clear if X contains less bits
860 // than C (i.e. no wrap-around can happen). For example, 20-X is
861 // positive if we can prove that X is >= 0 and < 16.
862 if (CLHS->getValue().isNegative())
863 break;
864
865 unsigned NLZ = (CLHS->getValue()+1).countLeadingZeros();
866 // NLZ can't be BitWidth with no sign bit
867 APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
868 ComputeMaskedBits(I->getOperand(1), MaskV, KnownZero, KnownOne, Depth+1);
869
870 // If all of the MaskV bits are known to be zero, then we know the output
871 // top bits are zero, because we now know that the output is from [0-C].
872 if ((KnownZero & MaskV) == MaskV) {
873 unsigned NLZ2 = CLHS->getValue().countLeadingZeros();
874 // Top bits known zero.
875 KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2) & Mask;
876 KnownOne = APInt(BitWidth, 0); // No one bits known.
877 } else {
878 KnownZero = KnownOne = APInt(BitWidth, 0); // Otherwise, nothing known.
879 }
880 return;
881 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +0000882 case Instruction::SRem:
883 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
884 APInt RA = Rem->getValue();
885 if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
886 APInt LowBits = RA.isStrictlyPositive() ? ((RA - 1) | RA) : ~RA;
887 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
888 ComputeMaskedBits(I->getOperand(0), Mask2,KnownZero2,KnownOne2,Depth+1);
889
890 // The sign of a remainder is equal to the sign of the first
891 // operand (zero being positive).
892 if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
893 KnownZero2 |= ~LowBits;
894 else if (KnownOne2[BitWidth-1])
895 KnownOne2 |= ~LowBits;
896
897 KnownZero |= KnownZero2 & Mask;
898 KnownOne |= KnownOne2 & Mask;
899
900 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
901 }
902 }
903 break;
904 case Instruction::URem:
905 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
906 APInt RA = Rem->getValue();
907 if (RA.isStrictlyPositive() && RA.isPowerOf2()) {
908 APInt LowBits = (RA - 1) | RA;
909 APInt Mask2 = LowBits & Mask;
910 KnownZero |= ~LowBits & Mask;
911 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne,Depth+1);
912 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
913 }
914 } else {
915 // Since the result is less than or equal to RHS, any leading zero bits
916 // in RHS must also exist in the result.
917 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Chris Lattner41dc0fc2008-03-21 05:19:58 +0000918 ComputeMaskedBits(I->getOperand(1), AllOnes, KnownZero2, KnownOne2,
919 Depth+1);
Nick Lewyckyc1a2a612008-03-06 06:48:30 +0000920
921 uint32_t Leaders = KnownZero2.countLeadingOnes();
922 KnownZero |= APInt::getHighBitsSet(BitWidth, Leaders) & Mask;
923 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
924 }
925 break;
Reid Spencer3e7594f2007-03-08 01:46:38 +0000926 }
927}
928
Reid Spencere7816b52007-03-08 01:52:58 +0000929/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
930/// this predicate to simplify operations downstream. Mask is known to be zero
931/// for bits that V cannot have.
932static bool MaskedValueIsZero(Value *V, const APInt& Mask, unsigned Depth = 0) {
Zhou Shengedd089c2007-03-12 16:54:56 +0000933 APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
Reid Spencere7816b52007-03-08 01:52:58 +0000934 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
935 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
936 return (KnownZero & Mask) == Mask;
937}
938
Chris Lattner255d8912006-02-11 09:31:47 +0000939/// ShrinkDemandedConstant - Check to see if the specified operand of the
940/// specified instruction is a constant integer. If so, check to see if there
941/// are any bits set in the constant that are not demanded. If so, shrink the
942/// constant and return true.
943static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000944 APInt Demanded) {
945 assert(I && "No instruction?");
946 assert(OpNo < I->getNumOperands() && "Operand index too large");
947
948 // If the operand is not a constant integer, nothing to do.
949 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
950 if (!OpC) return false;
951
952 // If there are no bits set that aren't demanded, nothing to do.
953 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
954 if ((~Demanded & OpC->getValue()) == 0)
955 return false;
956
957 // This instruction is producing bits that are not demanded. Shrink the RHS.
958 Demanded &= OpC->getValue();
959 I->setOperand(OpNo, ConstantInt::get(Demanded));
960 return true;
961}
962
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000963// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
964// set of known zero and one bits, compute the maximum and minimum values that
965// could have the specified known zero and known one bits, returning them in
966// min/max.
967static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
Reid Spencer0460fb32007-03-22 20:36:03 +0000968 const APInt& KnownZero,
969 const APInt& KnownOne,
970 APInt& Min, APInt& Max) {
971 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
972 assert(KnownZero.getBitWidth() == BitWidth &&
973 KnownOne.getBitWidth() == BitWidth &&
974 Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
975 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000976 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000977
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000978 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
979 // bit if it is unknown.
980 Min = KnownOne;
981 Max = KnownOne|UnknownBits;
982
Zhou Sheng4acf1552007-03-28 05:15:57 +0000983 if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
Zhou Sheng4a1822a2007-04-02 13:45:30 +0000984 Min.set(BitWidth-1);
985 Max.clear(BitWidth-1);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000986 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000987}
988
989// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
990// a set of known zero and one bits, compute the maximum and minimum values that
991// could have the specified known zero and known one bits, returning them in
992// min/max.
993static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
Chris Lattnera9ff5eb2007-08-05 08:47:58 +0000994 const APInt &KnownZero,
995 const APInt &KnownOne,
996 APInt &Min, APInt &Max) {
997 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth(); BitWidth = BitWidth;
Reid Spencer0460fb32007-03-22 20:36:03 +0000998 assert(KnownZero.getBitWidth() == BitWidth &&
999 KnownOne.getBitWidth() == BitWidth &&
1000 Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
1001 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +00001002 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00001003
1004 // The minimum value is when the unknown bits are all zeros.
1005 Min = KnownOne;
1006 // The maximum value is when the unknown bits are all ones.
1007 Max = KnownOne|UnknownBits;
1008}
Chris Lattner255d8912006-02-11 09:31:47 +00001009
Reid Spencer8cb68342007-03-12 17:25:59 +00001010/// SimplifyDemandedBits - This function attempts to replace V with a simpler
1011/// value based on the demanded bits. When this function is called, it is known
1012/// that only the bits set in DemandedMask of the result of V are ever used
1013/// downstream. Consequently, depending on the mask and V, it may be possible
1014/// to replace V with a constant or one of its operands. In such cases, this
1015/// function does the replacement and returns true. In all other cases, it
1016/// returns false after analyzing the expression and setting KnownOne and known
1017/// to be one in the expression. KnownZero contains all the bits that are known
1018/// to be zero in the expression. These are provided to potentially allow the
1019/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
1020/// the expression. KnownOne and KnownZero always follow the invariant that
1021/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
1022/// the bits in KnownOne and KnownZero may only be accurate for those bits set
1023/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
1024/// and KnownOne must all be the same.
1025bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
1026 APInt& KnownZero, APInt& KnownOne,
1027 unsigned Depth) {
1028 assert(V != 0 && "Null pointer of Value???");
1029 assert(Depth <= 6 && "Limit Search Depth");
1030 uint32_t BitWidth = DemandedMask.getBitWidth();
1031 const IntegerType *VTy = cast<IntegerType>(V->getType());
1032 assert(VTy->getBitWidth() == BitWidth &&
1033 KnownZero.getBitWidth() == BitWidth &&
1034 KnownOne.getBitWidth() == BitWidth &&
1035 "Value *V, DemandedMask, KnownZero and KnownOne \
1036 must have same BitWidth");
1037 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
1038 // We know all of the bits for a constant!
1039 KnownOne = CI->getValue() & DemandedMask;
1040 KnownZero = ~KnownOne & DemandedMask;
1041 return false;
1042 }
1043
Zhou Sheng96704452007-03-14 03:21:24 +00001044 KnownZero.clear();
1045 KnownOne.clear();
Reid Spencer8cb68342007-03-12 17:25:59 +00001046 if (!V->hasOneUse()) { // Other users may use these bits.
1047 if (Depth != 0) { // Not at the root.
1048 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
1049 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
1050 return false;
1051 }
1052 // If this is the root being simplified, allow it to have multiple uses,
1053 // just set the DemandedMask to all bits.
1054 DemandedMask = APInt::getAllOnesValue(BitWidth);
1055 } else if (DemandedMask == 0) { // Not demanding any bits from V.
1056 if (V != UndefValue::get(VTy))
1057 return UpdateValueUsesWith(V, UndefValue::get(VTy));
1058 return false;
1059 } else if (Depth == 6) { // Limit search depth.
1060 return false;
1061 }
1062
1063 Instruction *I = dyn_cast<Instruction>(V);
1064 if (!I) return false; // Only analyze instructions.
1065
Reid Spencer8cb68342007-03-12 17:25:59 +00001066 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
1067 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
1068 switch (I->getOpcode()) {
1069 default: break;
1070 case Instruction::And:
1071 // If either the LHS or the RHS are Zero, the result is zero.
1072 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1073 RHSKnownZero, RHSKnownOne, Depth+1))
1074 return true;
1075 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1076 "Bits known to be one AND zero?");
1077
1078 // If something is known zero on the RHS, the bits aren't demanded on the
1079 // LHS.
1080 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
1081 LHSKnownZero, LHSKnownOne, Depth+1))
1082 return true;
1083 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1084 "Bits known to be one AND zero?");
1085
1086 // If all of the demanded bits are known 1 on one side, return the other.
1087 // These bits cannot contribute to the result of the 'and'.
1088 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
1089 (DemandedMask & ~LHSKnownZero))
1090 return UpdateValueUsesWith(I, I->getOperand(0));
1091 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
1092 (DemandedMask & ~RHSKnownZero))
1093 return UpdateValueUsesWith(I, I->getOperand(1));
1094
1095 // If all of the demanded bits in the inputs are known zeros, return zero.
1096 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
1097 return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
1098
1099 // If the RHS is a constant, see if we can simplify it.
1100 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
1101 return UpdateValueUsesWith(I, I);
1102
1103 // Output known-1 bits are only known if set in both the LHS & RHS.
1104 RHSKnownOne &= LHSKnownOne;
1105 // Output known-0 are known to be clear if zero in either the LHS | RHS.
1106 RHSKnownZero |= LHSKnownZero;
1107 break;
1108 case Instruction::Or:
1109 // If either the LHS or the RHS are One, the result is One.
1110 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1111 RHSKnownZero, RHSKnownOne, Depth+1))
1112 return true;
1113 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1114 "Bits known to be one AND zero?");
1115 // If something is known one on the RHS, the bits aren't demanded on the
1116 // LHS.
1117 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
1118 LHSKnownZero, LHSKnownOne, Depth+1))
1119 return true;
1120 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1121 "Bits known to be one AND zero?");
1122
1123 // If all of the demanded bits are known zero on one side, return the other.
1124 // These bits cannot contribute to the result of the 'or'.
1125 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
1126 (DemandedMask & ~LHSKnownOne))
1127 return UpdateValueUsesWith(I, I->getOperand(0));
1128 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
1129 (DemandedMask & ~RHSKnownOne))
1130 return UpdateValueUsesWith(I, I->getOperand(1));
1131
1132 // If all of the potentially set bits on one side are known to be set on
1133 // the other side, just use the 'other' side.
1134 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
1135 (DemandedMask & (~RHSKnownZero)))
1136 return UpdateValueUsesWith(I, I->getOperand(0));
1137 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
1138 (DemandedMask & (~LHSKnownZero)))
1139 return UpdateValueUsesWith(I, I->getOperand(1));
1140
1141 // If the RHS is a constant, see if we can simplify it.
1142 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1143 return UpdateValueUsesWith(I, I);
1144
1145 // Output known-0 bits are only known if clear in both the LHS & RHS.
1146 RHSKnownZero &= LHSKnownZero;
1147 // Output known-1 are known to be set if set in either the LHS | RHS.
1148 RHSKnownOne |= LHSKnownOne;
1149 break;
1150 case Instruction::Xor: {
1151 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1152 RHSKnownZero, RHSKnownOne, Depth+1))
1153 return true;
1154 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1155 "Bits known to be one AND zero?");
1156 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1157 LHSKnownZero, LHSKnownOne, Depth+1))
1158 return true;
1159 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1160 "Bits known to be one AND zero?");
1161
1162 // If all of the demanded bits are known zero on one side, return the other.
1163 // These bits cannot contribute to the result of the 'xor'.
1164 if ((DemandedMask & RHSKnownZero) == DemandedMask)
1165 return UpdateValueUsesWith(I, I->getOperand(0));
1166 if ((DemandedMask & LHSKnownZero) == DemandedMask)
1167 return UpdateValueUsesWith(I, I->getOperand(1));
1168
1169 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1170 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1171 (RHSKnownOne & LHSKnownOne);
1172 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1173 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1174 (RHSKnownOne & LHSKnownZero);
1175
1176 // If all of the demanded bits are known to be zero on one side or the
1177 // other, turn this into an *inclusive* or.
1178 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1179 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1180 Instruction *Or =
1181 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1182 I->getName());
1183 InsertNewInstBefore(Or, *I);
1184 return UpdateValueUsesWith(I, Or);
1185 }
1186
1187 // If all of the demanded bits on one side are known, and all of the set
1188 // bits on that side are also known to be set on the other side, turn this
1189 // into an AND, as we know the bits will be cleared.
1190 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1191 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1192 // all known
1193 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1194 Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
1195 Instruction *And =
1196 BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
1197 InsertNewInstBefore(And, *I);
1198 return UpdateValueUsesWith(I, And);
1199 }
1200 }
1201
1202 // If the RHS is a constant, see if we can simplify it.
1203 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1204 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1205 return UpdateValueUsesWith(I, I);
1206
1207 RHSKnownZero = KnownZeroOut;
1208 RHSKnownOne = KnownOneOut;
1209 break;
1210 }
1211 case Instruction::Select:
1212 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
1213 RHSKnownZero, RHSKnownOne, Depth+1))
1214 return true;
1215 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1216 LHSKnownZero, LHSKnownOne, Depth+1))
1217 return true;
1218 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1219 "Bits known to be one AND zero?");
1220 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1221 "Bits known to be one AND zero?");
1222
1223 // If the operands are constants, see if we can simplify them.
1224 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1225 return UpdateValueUsesWith(I, I);
1226 if (ShrinkDemandedConstant(I, 2, DemandedMask))
1227 return UpdateValueUsesWith(I, I);
1228
1229 // Only known if known in both the LHS and RHS.
1230 RHSKnownOne &= LHSKnownOne;
1231 RHSKnownZero &= LHSKnownZero;
1232 break;
1233 case Instruction::Trunc: {
1234 uint32_t truncBf =
1235 cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
Zhou Sheng01542f32007-03-29 02:26:30 +00001236 DemandedMask.zext(truncBf);
1237 RHSKnownZero.zext(truncBf);
1238 RHSKnownOne.zext(truncBf);
1239 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1240 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer8cb68342007-03-12 17:25:59 +00001241 return true;
1242 DemandedMask.trunc(BitWidth);
1243 RHSKnownZero.trunc(BitWidth);
1244 RHSKnownOne.trunc(BitWidth);
1245 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1246 "Bits known to be one AND zero?");
1247 break;
1248 }
1249 case Instruction::BitCast:
1250 if (!I->getOperand(0)->getType()->isInteger())
1251 return false;
1252
1253 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1254 RHSKnownZero, RHSKnownOne, Depth+1))
1255 return true;
1256 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1257 "Bits known to be one AND zero?");
1258 break;
1259 case Instruction::ZExt: {
1260 // Compute the bits in the result that are not present in the input.
1261 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Reid Spencer2f549172007-03-25 04:26:16 +00001262 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer8cb68342007-03-12 17:25:59 +00001263
Zhou Shengd48653a2007-03-29 04:45:55 +00001264 DemandedMask.trunc(SrcBitWidth);
1265 RHSKnownZero.trunc(SrcBitWidth);
1266 RHSKnownOne.trunc(SrcBitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001267 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1268 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer8cb68342007-03-12 17:25:59 +00001269 return true;
1270 DemandedMask.zext(BitWidth);
1271 RHSKnownZero.zext(BitWidth);
1272 RHSKnownOne.zext(BitWidth);
1273 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1274 "Bits known to be one AND zero?");
1275 // The top bits are known to be zero.
Zhou Sheng01542f32007-03-29 02:26:30 +00001276 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001277 break;
1278 }
1279 case Instruction::SExt: {
1280 // Compute the bits in the result that are not present in the input.
1281 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Reid Spencer2f549172007-03-25 04:26:16 +00001282 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer8cb68342007-03-12 17:25:59 +00001283
Reid Spencer8cb68342007-03-12 17:25:59 +00001284 APInt InputDemandedBits = DemandedMask &
Zhou Sheng01542f32007-03-29 02:26:30 +00001285 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001286
Zhou Sheng01542f32007-03-29 02:26:30 +00001287 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
Reid Spencer8cb68342007-03-12 17:25:59 +00001288 // If any of the sign extended bits are demanded, we know that the sign
1289 // bit is demanded.
1290 if ((NewBits & DemandedMask) != 0)
Zhou Sheng4a1822a2007-04-02 13:45:30 +00001291 InputDemandedBits.set(SrcBitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001292
Zhou Shengd48653a2007-03-29 04:45:55 +00001293 InputDemandedBits.trunc(SrcBitWidth);
1294 RHSKnownZero.trunc(SrcBitWidth);
1295 RHSKnownOne.trunc(SrcBitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001296 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1297 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer8cb68342007-03-12 17:25:59 +00001298 return true;
1299 InputDemandedBits.zext(BitWidth);
1300 RHSKnownZero.zext(BitWidth);
1301 RHSKnownOne.zext(BitWidth);
1302 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1303 "Bits known to be one AND zero?");
1304
1305 // If the sign bit of the input is known set or clear, then we know the
1306 // top bits of the result.
1307
1308 // If the input sign bit is known zero, or if the NewBits are not demanded
1309 // convert this into a zero extension.
Zhou Sheng01542f32007-03-29 02:26:30 +00001310 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits)
Reid Spencer8cb68342007-03-12 17:25:59 +00001311 {
1312 // Convert to ZExt cast
1313 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1314 return UpdateValueUsesWith(I, NewCast);
Zhou Sheng01542f32007-03-29 02:26:30 +00001315 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
Reid Spencer8cb68342007-03-12 17:25:59 +00001316 RHSKnownOne |= NewBits;
Reid Spencer8cb68342007-03-12 17:25:59 +00001317 }
1318 break;
1319 }
1320 case Instruction::Add: {
1321 // Figure out what the input bits are. If the top bits of the and result
1322 // are not demanded, then the add doesn't demand them from its input
1323 // either.
Reid Spencer55702aa2007-03-25 21:11:44 +00001324 uint32_t NLZ = DemandedMask.countLeadingZeros();
Reid Spencer8cb68342007-03-12 17:25:59 +00001325
1326 // If there is a constant on the RHS, there are a variety of xformations
1327 // we can do.
1328 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1329 // If null, this should be simplified elsewhere. Some of the xforms here
1330 // won't work if the RHS is zero.
1331 if (RHS->isZero())
1332 break;
1333
1334 // If the top bit of the output is demanded, demand everything from the
1335 // input. Otherwise, we demand all the input bits except NLZ top bits.
Zhou Sheng01542f32007-03-29 02:26:30 +00001336 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001337
1338 // Find information about known zero/one bits in the input.
1339 if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits,
1340 LHSKnownZero, LHSKnownOne, Depth+1))
1341 return true;
1342
1343 // If the RHS of the add has bits set that can't affect the input, reduce
1344 // the constant.
1345 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1346 return UpdateValueUsesWith(I, I);
1347
1348 // Avoid excess work.
1349 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1350 break;
1351
1352 // Turn it into OR if input bits are zero.
1353 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1354 Instruction *Or =
1355 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1356 I->getName());
1357 InsertNewInstBefore(Or, *I);
1358 return UpdateValueUsesWith(I, Or);
1359 }
1360
1361 // We can say something about the output known-zero and known-one bits,
1362 // depending on potential carries from the input constant and the
1363 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1364 // bits set and the RHS constant is 0x01001, then we know we have a known
1365 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1366
1367 // To compute this, we first compute the potential carry bits. These are
1368 // the bits which may be modified. I'm not aware of a better way to do
1369 // this scan.
Zhou Shengb9cb95f2007-03-31 02:38:39 +00001370 const APInt& RHSVal = RHS->getValue();
1371 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
Reid Spencer8cb68342007-03-12 17:25:59 +00001372
1373 // Now that we know which bits have carries, compute the known-1/0 sets.
1374
1375 // Bits are known one if they are known zero in one operand and one in the
1376 // other, and there is no input carry.
1377 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1378 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1379
1380 // Bits are known zero if they are known zero in both operands and there
1381 // is no input carry.
1382 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1383 } else {
1384 // If the high-bits of this ADD are not demanded, then it does not demand
1385 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001386 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001387 // Right fill the mask of bits for this ADD to demand the most
1388 // significant bit and all those below it.
Zhou Sheng01542f32007-03-29 02:26:30 +00001389 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001390 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1391 LHSKnownZero, LHSKnownOne, Depth+1))
1392 return true;
1393 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1394 LHSKnownZero, LHSKnownOne, Depth+1))
1395 return true;
1396 }
1397 }
1398 break;
1399 }
1400 case Instruction::Sub:
1401 // If the high-bits of this SUB are not demanded, then it does not demand
1402 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001403 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001404 // Right fill the mask of bits for this SUB to demand the most
1405 // significant bit and all those below it.
Zhou Sheng4351c642007-04-02 08:20:41 +00001406 uint32_t NLZ = DemandedMask.countLeadingZeros();
Zhou Sheng01542f32007-03-29 02:26:30 +00001407 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001408 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1409 LHSKnownZero, LHSKnownOne, Depth+1))
1410 return true;
1411 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1412 LHSKnownZero, LHSKnownOne, Depth+1))
1413 return true;
1414 }
1415 break;
1416 case Instruction::Shl:
1417 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001418 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001419 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1420 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001421 RHSKnownZero, RHSKnownOne, Depth+1))
1422 return true;
1423 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1424 "Bits known to be one AND zero?");
1425 RHSKnownZero <<= ShiftAmt;
1426 RHSKnownOne <<= ShiftAmt;
1427 // low bits known zero.
Zhou Shengadc14952007-03-14 09:07:33 +00001428 if (ShiftAmt)
Zhou Shenge9e03f62007-03-28 15:02:20 +00001429 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
Reid Spencer8cb68342007-03-12 17:25:59 +00001430 }
1431 break;
1432 case Instruction::LShr:
1433 // For a logical shift right
1434 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001435 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001436
Reid Spencer8cb68342007-03-12 17:25:59 +00001437 // Unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001438 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1439 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001440 RHSKnownZero, RHSKnownOne, Depth+1))
1441 return true;
1442 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1443 "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001444 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1445 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
Zhou Shengadc14952007-03-14 09:07:33 +00001446 if (ShiftAmt) {
1447 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001448 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Zhou Shengadc14952007-03-14 09:07:33 +00001449 RHSKnownZero |= HighBits; // high bits known zero.
1450 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001451 }
1452 break;
1453 case Instruction::AShr:
1454 // If this is an arithmetic shift right and only the low-bit is set, we can
1455 // always convert this into a logical shr, even if the shift amount is
1456 // variable. The low bit of the shift cannot be an input sign bit unless
1457 // the shift amount is >= the size of the datatype, which is undefined.
1458 if (DemandedMask == 1) {
1459 // Perform the logical shift right.
1460 Value *NewVal = BinaryOperator::createLShr(
1461 I->getOperand(0), I->getOperand(1), I->getName());
1462 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1463 return UpdateValueUsesWith(I, NewVal);
1464 }
Chris Lattner4241e4d2007-07-15 20:54:51 +00001465
1466 // If the sign bit is the only bit demanded by this ashr, then there is no
1467 // need to do it, the shift doesn't change the high bit.
1468 if (DemandedMask.isSignBit())
1469 return UpdateValueUsesWith(I, I->getOperand(0));
Reid Spencer8cb68342007-03-12 17:25:59 +00001470
1471 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00001472 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001473
Reid Spencer8cb68342007-03-12 17:25:59 +00001474 // Signed shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001475 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Lauro Ramos Venanciod0499af2007-06-06 17:08:48 +00001476 // If any of the "high bits" are demanded, we should set the sign bit as
1477 // demanded.
1478 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1479 DemandedMaskIn.set(BitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001480 if (SimplifyDemandedBits(I->getOperand(0),
Zhou Sheng01542f32007-03-29 02:26:30 +00001481 DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001482 RHSKnownZero, RHSKnownOne, Depth+1))
1483 return true;
1484 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1485 "Bits known to be one AND zero?");
1486 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001487 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Reid Spencer8cb68342007-03-12 17:25:59 +00001488 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1489 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1490
1491 // Handle the sign bits.
1492 APInt SignBit(APInt::getSignBit(BitWidth));
1493 // Adjust to where it is now in the mask.
1494 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1495
1496 // If the input sign bit is known to be zero, or if none of the top bits
1497 // are demanded, turn this into an unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001498 if (RHSKnownZero[BitWidth-ShiftAmt-1] ||
Reid Spencer8cb68342007-03-12 17:25:59 +00001499 (HighBits & ~DemandedMask) == HighBits) {
1500 // Perform the logical shift right.
1501 Value *NewVal = BinaryOperator::createLShr(
1502 I->getOperand(0), SA, I->getName());
1503 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1504 return UpdateValueUsesWith(I, NewVal);
1505 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1506 RHSKnownOne |= HighBits;
1507 }
1508 }
1509 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001510 case Instruction::SRem:
1511 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1512 APInt RA = Rem->getValue();
1513 if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
1514 APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) | RA : ~RA;
1515 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1516 if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1517 LHSKnownZero, LHSKnownOne, Depth+1))
1518 return true;
1519
1520 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1521 LHSKnownZero |= ~LowBits;
1522 else if (LHSKnownOne[BitWidth-1])
1523 LHSKnownOne |= ~LowBits;
1524
1525 KnownZero |= LHSKnownZero & DemandedMask;
1526 KnownOne |= LHSKnownOne & DemandedMask;
1527
1528 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1529 }
1530 }
1531 break;
1532 case Instruction::URem:
1533 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1534 APInt RA = Rem->getValue();
1535 if (RA.isPowerOf2()) {
1536 APInt LowBits = (RA - 1) | RA;
1537 APInt Mask2 = LowBits & DemandedMask;
1538 KnownZero |= ~LowBits & DemandedMask;
1539 if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1540 KnownZero, KnownOne, Depth+1))
1541 return true;
1542
1543 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1544 }
1545 } else {
1546 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1547 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1548 if (SimplifyDemandedBits(I->getOperand(1), AllOnes,
1549 KnownZero2, KnownOne2, Depth+1))
1550 return true;
1551
1552 uint32_t Leaders = KnownZero2.countLeadingOnes();
1553 KnownZero |= APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
1554 }
1555 break;
Reid Spencer8cb68342007-03-12 17:25:59 +00001556 }
1557
1558 // If the client is only demanding bits that we know, return the known
1559 // constant.
1560 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1561 return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
1562 return false;
1563}
1564
Chris Lattner867b99f2006-10-05 06:55:50 +00001565
1566/// SimplifyDemandedVectorElts - The specified value producecs a vector with
1567/// 64 or fewer elements. DemandedElts contains the set of elements that are
1568/// actually used by the caller. This method analyzes which elements of the
1569/// operand are undef and returns that information in UndefElts.
1570///
1571/// If the information about demanded elements can be used to simplify the
1572/// operation, the operation is simplified, then the resultant value is
1573/// returned. This returns null if no change was made.
1574Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1575 uint64_t &UndefElts,
1576 unsigned Depth) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001577 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner867b99f2006-10-05 06:55:50 +00001578 assert(VWidth <= 64 && "Vector too wide to analyze!");
1579 uint64_t EltMask = ~0ULL >> (64-VWidth);
1580 assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1581 "Invalid DemandedElts!");
1582
1583 if (isa<UndefValue>(V)) {
1584 // If the entire vector is undefined, just return this info.
1585 UndefElts = EltMask;
1586 return 0;
1587 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1588 UndefElts = EltMask;
1589 return UndefValue::get(V->getType());
1590 }
1591
1592 UndefElts = 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001593 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1594 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner867b99f2006-10-05 06:55:50 +00001595 Constant *Undef = UndefValue::get(EltTy);
1596
1597 std::vector<Constant*> Elts;
1598 for (unsigned i = 0; i != VWidth; ++i)
1599 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1600 Elts.push_back(Undef);
1601 UndefElts |= (1ULL << i);
1602 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1603 Elts.push_back(Undef);
1604 UndefElts |= (1ULL << i);
1605 } else { // Otherwise, defined.
1606 Elts.push_back(CP->getOperand(i));
1607 }
1608
1609 // If we changed the constant, return it.
Reid Spencer9d6565a2007-02-15 02:26:10 +00001610 Constant *NewCP = ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001611 return NewCP != CP ? NewCP : 0;
1612 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001613 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner867b99f2006-10-05 06:55:50 +00001614 // set to undef.
Reid Spencer9d6565a2007-02-15 02:26:10 +00001615 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner867b99f2006-10-05 06:55:50 +00001616 Constant *Zero = Constant::getNullValue(EltTy);
1617 Constant *Undef = UndefValue::get(EltTy);
1618 std::vector<Constant*> Elts;
1619 for (unsigned i = 0; i != VWidth; ++i)
1620 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1621 UndefElts = DemandedElts ^ EltMask;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001622 return ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001623 }
1624
1625 if (!V->hasOneUse()) { // Other users may use these bits.
1626 if (Depth != 0) { // Not at the root.
1627 // TODO: Just compute the UndefElts information recursively.
1628 return false;
1629 }
1630 return false;
1631 } else if (Depth == 10) { // Limit search depth.
1632 return false;
1633 }
1634
1635 Instruction *I = dyn_cast<Instruction>(V);
1636 if (!I) return false; // Only analyze instructions.
1637
1638 bool MadeChange = false;
1639 uint64_t UndefElts2;
1640 Value *TmpV;
1641 switch (I->getOpcode()) {
1642 default: break;
1643
1644 case Instruction::InsertElement: {
1645 // If this is a variable index, we don't know which element it overwrites.
1646 // demand exactly the same input as we produce.
Reid Spencerb83eb642006-10-20 07:07:24 +00001647 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner867b99f2006-10-05 06:55:50 +00001648 if (Idx == 0) {
1649 // Note that we can't propagate undef elt info, because we don't know
1650 // which elt is getting updated.
1651 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1652 UndefElts2, Depth+1);
1653 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1654 break;
1655 }
1656
1657 // If this is inserting an element that isn't demanded, remove this
1658 // insertelement.
Reid Spencerb83eb642006-10-20 07:07:24 +00001659 unsigned IdxNo = Idx->getZExtValue();
Chris Lattner867b99f2006-10-05 06:55:50 +00001660 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1661 return AddSoonDeadInstToWorklist(*I, 0);
1662
1663 // Otherwise, the element inserted overwrites whatever was there, so the
1664 // input demanded set is simpler than the output set.
1665 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1666 DemandedElts & ~(1ULL << IdxNo),
1667 UndefElts, Depth+1);
1668 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1669
1670 // The inserted element is defined.
1671 UndefElts |= 1ULL << IdxNo;
1672 break;
1673 }
Chris Lattner69878332007-04-14 22:29:23 +00001674 case Instruction::BitCast: {
Dan Gohman07a96762007-07-16 14:29:03 +00001675 // Vector->vector casts only.
Chris Lattner69878332007-04-14 22:29:23 +00001676 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1677 if (!VTy) break;
1678 unsigned InVWidth = VTy->getNumElements();
1679 uint64_t InputDemandedElts = 0;
1680 unsigned Ratio;
1681
1682 if (VWidth == InVWidth) {
Dan Gohman07a96762007-07-16 14:29:03 +00001683 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
Chris Lattner69878332007-04-14 22:29:23 +00001684 // elements as are demanded of us.
1685 Ratio = 1;
1686 InputDemandedElts = DemandedElts;
1687 } else if (VWidth > InVWidth) {
1688 // Untested so far.
1689 break;
1690
1691 // If there are more elements in the result than there are in the source,
1692 // then an input element is live if any of the corresponding output
1693 // elements are live.
1694 Ratio = VWidth/InVWidth;
1695 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1696 if (DemandedElts & (1ULL << OutIdx))
1697 InputDemandedElts |= 1ULL << (OutIdx/Ratio);
1698 }
1699 } else {
1700 // Untested so far.
1701 break;
1702
1703 // If there are more elements in the source than there are in the result,
1704 // then an input element is live if the corresponding output element is
1705 // live.
1706 Ratio = InVWidth/VWidth;
1707 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1708 if (DemandedElts & (1ULL << InIdx/Ratio))
1709 InputDemandedElts |= 1ULL << InIdx;
1710 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001711
Chris Lattner69878332007-04-14 22:29:23 +00001712 // div/rem demand all inputs, because they don't want divide by zero.
1713 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1714 UndefElts2, Depth+1);
1715 if (TmpV) {
1716 I->setOperand(0, TmpV);
1717 MadeChange = true;
1718 }
1719
1720 UndefElts = UndefElts2;
1721 if (VWidth > InVWidth) {
1722 assert(0 && "Unimp");
1723 // If there are more elements in the result than there are in the source,
1724 // then an output element is undef if the corresponding input element is
1725 // undef.
1726 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1727 if (UndefElts2 & (1ULL << (OutIdx/Ratio)))
1728 UndefElts |= 1ULL << OutIdx;
1729 } else if (VWidth < InVWidth) {
1730 assert(0 && "Unimp");
1731 // If there are more elements in the source than there are in the result,
1732 // then a result element is undef if all of the corresponding input
1733 // elements are undef.
1734 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1735 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1736 if ((UndefElts2 & (1ULL << InIdx)) == 0) // Not undef?
1737 UndefElts &= ~(1ULL << (InIdx/Ratio)); // Clear undef bit.
1738 }
1739 break;
1740 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001741 case Instruction::And:
1742 case Instruction::Or:
1743 case Instruction::Xor:
1744 case Instruction::Add:
1745 case Instruction::Sub:
1746 case Instruction::Mul:
1747 // div/rem demand all inputs, because they don't want divide by zero.
1748 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1749 UndefElts, Depth+1);
1750 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1751 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1752 UndefElts2, Depth+1);
1753 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1754
1755 // Output elements are undefined if both are undefined. Consider things
1756 // like undef&0. The result is known zero, not undef.
1757 UndefElts &= UndefElts2;
1758 break;
1759
1760 case Instruction::Call: {
1761 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1762 if (!II) break;
1763 switch (II->getIntrinsicID()) {
1764 default: break;
1765
1766 // Binary vector operations that work column-wise. A dest element is a
1767 // function of the corresponding input elements from the two inputs.
1768 case Intrinsic::x86_sse_sub_ss:
1769 case Intrinsic::x86_sse_mul_ss:
1770 case Intrinsic::x86_sse_min_ss:
1771 case Intrinsic::x86_sse_max_ss:
1772 case Intrinsic::x86_sse2_sub_sd:
1773 case Intrinsic::x86_sse2_mul_sd:
1774 case Intrinsic::x86_sse2_min_sd:
1775 case Intrinsic::x86_sse2_max_sd:
1776 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1777 UndefElts, Depth+1);
1778 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1779 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1780 UndefElts2, Depth+1);
1781 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1782
1783 // If only the low elt is demanded and this is a scalarizable intrinsic,
1784 // scalarize it now.
1785 if (DemandedElts == 1) {
1786 switch (II->getIntrinsicID()) {
1787 default: break;
1788 case Intrinsic::x86_sse_sub_ss:
1789 case Intrinsic::x86_sse_mul_ss:
1790 case Intrinsic::x86_sse2_sub_sd:
1791 case Intrinsic::x86_sse2_mul_sd:
1792 // TODO: Lower MIN/MAX/ABS/etc
1793 Value *LHS = II->getOperand(1);
1794 Value *RHS = II->getOperand(2);
1795 // Extract the element as scalars.
1796 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1797 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1798
1799 switch (II->getIntrinsicID()) {
1800 default: assert(0 && "Case stmts out of sync!");
1801 case Intrinsic::x86_sse_sub_ss:
1802 case Intrinsic::x86_sse2_sub_sd:
1803 TmpV = InsertNewInstBefore(BinaryOperator::createSub(LHS, RHS,
1804 II->getName()), *II);
1805 break;
1806 case Intrinsic::x86_sse_mul_ss:
1807 case Intrinsic::x86_sse2_mul_sd:
1808 TmpV = InsertNewInstBefore(BinaryOperator::createMul(LHS, RHS,
1809 II->getName()), *II);
1810 break;
1811 }
1812
1813 Instruction *New =
1814 new InsertElementInst(UndefValue::get(II->getType()), TmpV, 0U,
1815 II->getName());
1816 InsertNewInstBefore(New, *II);
1817 AddSoonDeadInstToWorklist(*II, 0);
1818 return New;
1819 }
1820 }
1821
1822 // Output elements are undefined if both are undefined. Consider things
1823 // like undef&0. The result is known zero, not undef.
1824 UndefElts &= UndefElts2;
1825 break;
1826 }
1827 break;
1828 }
1829 }
1830 return MadeChange ? I : 0;
1831}
1832
Nick Lewycky455e1762007-09-06 02:40:25 +00001833/// @returns true if the specified compare predicate is
Reid Spencere4d87aa2006-12-23 06:05:41 +00001834/// true when both operands are equal...
Nick Lewycky455e1762007-09-06 02:40:25 +00001835/// @brief Determine if the icmp Predicate is true when both operands are equal
1836static bool isTrueWhenEqual(ICmpInst::Predicate pred) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001837 return pred == ICmpInst::ICMP_EQ || pred == ICmpInst::ICMP_UGE ||
1838 pred == ICmpInst::ICMP_SGE || pred == ICmpInst::ICMP_ULE ||
1839 pred == ICmpInst::ICMP_SLE;
1840}
1841
Nick Lewycky455e1762007-09-06 02:40:25 +00001842/// @returns true if the specified compare instruction is
1843/// true when both operands are equal...
1844/// @brief Determine if the ICmpInst returns true when both operands are equal
1845static bool isTrueWhenEqual(ICmpInst &ICI) {
1846 return isTrueWhenEqual(ICI.getPredicate());
1847}
1848
Chris Lattner564a7272003-08-13 19:01:45 +00001849/// AssociativeOpt - Perform an optimization on an associative operator. This
1850/// function is designed to check a chain of associative operators for a
1851/// potential to apply a certain optimization. Since the optimization may be
1852/// applicable if the expression was reassociated, this checks the chain, then
1853/// reassociates the expression as necessary to expose the optimization
1854/// opportunity. This makes use of a special Functor, which must define
1855/// 'shouldApply' and 'apply' methods.
1856///
1857template<typename Functor>
1858Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1859 unsigned Opcode = Root.getOpcode();
1860 Value *LHS = Root.getOperand(0);
1861
1862 // Quick check, see if the immediate LHS matches...
1863 if (F.shouldApply(LHS))
1864 return F.apply(Root);
1865
1866 // Otherwise, if the LHS is not of the same opcode as the root, return.
1867 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +00001868 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +00001869 // Should we apply this transform to the RHS?
1870 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1871
1872 // If not to the RHS, check to see if we should apply to the LHS...
1873 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1874 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1875 ShouldApply = true;
1876 }
1877
1878 // If the functor wants to apply the optimization to the RHS of LHSI,
1879 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1880 if (ShouldApply) {
1881 BasicBlock *BB = Root.getParent();
Misha Brukmanfd939082005-04-21 23:48:37 +00001882
Chris Lattner564a7272003-08-13 19:01:45 +00001883 // Now all of the instructions are in the current basic block, go ahead
1884 // and perform the reassociation.
1885 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1886
1887 // First move the selected RHS to the LHS of the root...
1888 Root.setOperand(0, LHSI->getOperand(1));
1889
1890 // Make what used to be the LHS of the root be the user of the root...
1891 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +00001892 if (&Root == TmpLHSI) {
Chris Lattner15a76c02004-04-05 02:10:19 +00001893 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1894 return 0;
1895 }
Chris Lattner65725312004-04-16 18:08:07 +00001896 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +00001897 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +00001898 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1899 BasicBlock::iterator ARI = &Root; ++ARI;
1900 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
1901 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +00001902
1903 // Now propagate the ExtraOperand down the chain of instructions until we
1904 // get to LHSI.
1905 while (TmpLHSI != LHSI) {
1906 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +00001907 // Move the instruction to immediately before the chain we are
1908 // constructing to avoid breaking dominance properties.
1909 NextLHSI->getParent()->getInstList().remove(NextLHSI);
1910 BB->getInstList().insert(ARI, NextLHSI);
1911 ARI = NextLHSI;
1912
Chris Lattner564a7272003-08-13 19:01:45 +00001913 Value *NextOp = NextLHSI->getOperand(1);
1914 NextLHSI->setOperand(1, ExtraOperand);
1915 TmpLHSI = NextLHSI;
1916 ExtraOperand = NextOp;
1917 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001918
Chris Lattner564a7272003-08-13 19:01:45 +00001919 // Now that the instructions are reassociated, have the functor perform
1920 // the transformation...
1921 return F.apply(Root);
1922 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001923
Chris Lattner564a7272003-08-13 19:01:45 +00001924 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1925 }
1926 return 0;
1927}
1928
1929
1930// AddRHS - Implements: X + X --> X << 1
1931struct AddRHS {
1932 Value *RHS;
1933 AddRHS(Value *rhs) : RHS(rhs) {}
1934 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1935 Instruction *apply(BinaryOperator &Add) const {
Reid Spencercc46cdb2007-02-02 14:08:20 +00001936 return BinaryOperator::createShl(Add.getOperand(0),
Reid Spencer832254e2007-02-02 02:16:23 +00001937 ConstantInt::get(Add.getType(), 1));
Chris Lattner564a7272003-08-13 19:01:45 +00001938 }
1939};
1940
1941// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1942// iff C1&C2 == 0
1943struct AddMaskingAnd {
1944 Constant *C2;
1945 AddMaskingAnd(Constant *c) : C2(c) {}
1946 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001947 ConstantInt *C1;
Misha Brukmanfd939082005-04-21 23:48:37 +00001948 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001949 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +00001950 }
1951 Instruction *apply(BinaryOperator &Add) const {
Chris Lattner48595f12004-06-10 02:07:29 +00001952 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +00001953 }
1954};
1955
Chris Lattner6e7ba452005-01-01 16:22:27 +00001956static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +00001957 InstCombiner *IC) {
Reid Spencer3da59db2006-11-27 01:05:10 +00001958 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Chris Lattner6e7ba452005-01-01 16:22:27 +00001959 if (Constant *SOC = dyn_cast<Constant>(SO))
Reid Spencer3da59db2006-11-27 01:05:10 +00001960 return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
Misha Brukmanfd939082005-04-21 23:48:37 +00001961
Reid Spencer3da59db2006-11-27 01:05:10 +00001962 return IC->InsertNewInstBefore(CastInst::create(
1963 CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001964 }
1965
Chris Lattner2eefe512004-04-09 19:05:30 +00001966 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +00001967 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1968 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +00001969
Chris Lattner2eefe512004-04-09 19:05:30 +00001970 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1971 if (ConstIsRHS)
Chris Lattner6e7ba452005-01-01 16:22:27 +00001972 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1973 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +00001974 }
1975
1976 Value *Op0 = SO, *Op1 = ConstOperand;
1977 if (!ConstIsRHS)
1978 std::swap(Op0, Op1);
1979 Instruction *New;
Chris Lattner6e7ba452005-01-01 16:22:27 +00001980 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1981 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Reid Spencere4d87aa2006-12-23 06:05:41 +00001982 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1983 New = CmpInst::create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
1984 SO->getName()+".cmp");
Chris Lattner326c0f32004-04-10 19:15:56 +00001985 else {
Chris Lattner2eefe512004-04-09 19:05:30 +00001986 assert(0 && "Unknown binary instruction type!");
Chris Lattner326c0f32004-04-10 19:15:56 +00001987 abort();
1988 }
Chris Lattner6e7ba452005-01-01 16:22:27 +00001989 return IC->InsertNewInstBefore(New, I);
1990}
1991
1992// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1993// constant as the other operand, try to fold the binary operator into the
1994// select arguments. This also works for Cast instructions, which obviously do
1995// not have a second operand.
1996static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1997 InstCombiner *IC) {
1998 // Don't modify shared select instructions
1999 if (!SI->hasOneUse()) return 0;
2000 Value *TV = SI->getOperand(1);
2001 Value *FV = SI->getOperand(2);
2002
2003 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +00002004 // Bool selects with constant operands can be folded to logical ops.
Reid Spencer4fe16d62007-01-11 18:21:29 +00002005 if (SI->getType() == Type::Int1Ty) return 0;
Chris Lattner956db272005-04-21 05:43:13 +00002006
Chris Lattner6e7ba452005-01-01 16:22:27 +00002007 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
2008 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
2009
2010 return new SelectInst(SI->getCondition(), SelectTrueVal,
2011 SelectFalseVal);
2012 }
2013 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +00002014}
2015
Chris Lattner4e998b22004-09-29 05:07:12 +00002016
2017/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
2018/// node as operand #0, see if we can fold the instruction into the PHI (which
2019/// is only possible if all operands to the PHI are constants).
2020Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
2021 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00002022 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002023 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner4e998b22004-09-29 05:07:12 +00002024
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002025 // Check to see if all of the operands of the PHI are constants. If there is
2026 // one non-constant value, remember the BB it is. If there is more than one
Chris Lattnerb3036682007-02-24 01:03:45 +00002027 // or if *it* is a PHI, bail out.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002028 BasicBlock *NonConstBB = 0;
2029 for (unsigned i = 0; i != NumPHIValues; ++i)
2030 if (!isa<Constant>(PN->getIncomingValue(i))) {
2031 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +00002032 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002033 NonConstBB = PN->getIncomingBlock(i);
2034
2035 // If the incoming non-constant value is in I's block, we have an infinite
2036 // loop.
2037 if (NonConstBB == I.getParent())
2038 return 0;
2039 }
2040
2041 // If there is exactly one non-constant value, we can insert a copy of the
2042 // operation in that block. However, if this is a critical edge, we would be
2043 // inserting the computation one some other paths (e.g. inside a loop). Only
2044 // do this if the pred block is unconditionally branching into the phi block.
2045 if (NonConstBB) {
2046 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
2047 if (!BI || !BI->isUnconditional()) return 0;
2048 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002049
2050 // Okay, we can do the transformation: create the new PHI node.
Chris Lattner6934a042007-02-11 01:23:03 +00002051 PHINode *NewPN = new PHINode(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +00002052 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner4e998b22004-09-29 05:07:12 +00002053 InsertNewInstBefore(NewPN, *PN);
Chris Lattner6934a042007-02-11 01:23:03 +00002054 NewPN->takeName(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +00002055
2056 // Next, add all of the operands to the PHI.
2057 if (I.getNumOperands() == 2) {
2058 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +00002059 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00002060 Value *InV = 0;
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002061 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002062 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2063 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
2064 else
2065 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002066 } else {
2067 assert(PN->getIncomingBlock(i) == NonConstBB);
2068 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
2069 InV = BinaryOperator::create(BO->getOpcode(),
2070 PN->getIncomingValue(i), C, "phitmp",
2071 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +00002072 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2073 InV = CmpInst::create(CI->getOpcode(),
2074 CI->getPredicate(),
2075 PN->getIncomingValue(i), C, "phitmp",
2076 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002077 else
2078 assert(0 && "Unknown binop!");
2079
Chris Lattnerdbab3862007-03-02 21:28:56 +00002080 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002081 }
2082 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002083 }
Reid Spencer3da59db2006-11-27 01:05:10 +00002084 } else {
2085 CastInst *CI = cast<CastInst>(&I);
2086 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +00002087 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002088 Value *InV;
2089 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00002090 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002091 } else {
2092 assert(PN->getIncomingBlock(i) == NonConstBB);
Reid Spencer3da59db2006-11-27 01:05:10 +00002093 InV = CastInst::create(CI->getOpcode(), PN->getIncomingValue(i),
2094 I.getType(), "phitmp",
2095 NonConstBB->getTerminator());
Chris Lattnerdbab3862007-03-02 21:28:56 +00002096 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002097 }
2098 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002099 }
2100 }
2101 return ReplaceInstUsesWith(I, NewPN);
2102}
2103
Chris Lattner2454a2e2008-01-29 06:52:45 +00002104
2105/// CannotBeNegativeZero - Return true if we can prove that the specified FP
2106/// value is never equal to -0.0.
2107///
2108/// Note that this function will need to be revisited when we support nondefault
2109/// rounding modes!
2110///
2111static bool CannotBeNegativeZero(const Value *V) {
2112 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
2113 return !CFP->getValueAPF().isNegZero();
2114
2115 // (add x, 0.0) is guaranteed to return +0.0, not -0.0.
2116 if (const Instruction *I = dyn_cast<Instruction>(V)) {
2117 if (I->getOpcode() == Instruction::Add &&
2118 isa<ConstantFP>(I->getOperand(1)) &&
2119 cast<ConstantFP>(I->getOperand(1))->isNullValue())
2120 return true;
2121
2122 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
2123 if (II->getIntrinsicID() == Intrinsic::sqrt)
2124 return CannotBeNegativeZero(II->getOperand(1));
2125
2126 if (const CallInst *CI = dyn_cast<CallInst>(I))
2127 if (const Function *F = CI->getCalledFunction()) {
2128 if (F->isDeclaration()) {
2129 switch (F->getNameLen()) {
2130 case 3: // abs(x) != -0.0
2131 if (!strcmp(F->getNameStart(), "abs")) return true;
2132 break;
2133 case 4: // abs[lf](x) != -0.0
2134 if (!strcmp(F->getNameStart(), "absf")) return true;
2135 if (!strcmp(F->getNameStart(), "absl")) return true;
2136 break;
2137 }
2138 }
2139 }
2140 }
2141
2142 return false;
2143}
2144
2145
Chris Lattner7e708292002-06-25 16:13:24 +00002146Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002147 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002148 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002149
Chris Lattner66331a42004-04-10 22:01:55 +00002150 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattnere87597f2004-10-16 18:11:37 +00002151 // X + undef -> undef
2152 if (isa<UndefValue>(RHS))
2153 return ReplaceInstUsesWith(I, RHS);
2154
Chris Lattner66331a42004-04-10 22:01:55 +00002155 // X + 0 --> X
Chris Lattner9919e3d2006-12-02 00:13:08 +00002156 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
Chris Lattner5e678e02005-10-17 17:56:38 +00002157 if (RHSC->isNullValue())
2158 return ReplaceInstUsesWith(I, LHS);
Chris Lattner8532cf62005-10-17 20:18:38 +00002159 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00002160 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
2161 (I.getType())->getValueAPF()))
Chris Lattner8532cf62005-10-17 20:18:38 +00002162 return ReplaceInstUsesWith(I, LHS);
Chris Lattner5e678e02005-10-17 17:56:38 +00002163 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002164
Chris Lattner66331a42004-04-10 22:01:55 +00002165 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002166 // X + (signbit) --> X ^ signbit
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002167 const APInt& Val = CI->getValue();
Zhou Sheng4351c642007-04-02 08:20:41 +00002168 uint32_t BitWidth = Val.getBitWidth();
Reid Spencer2ec619a2007-03-23 21:24:59 +00002169 if (Val == APInt::getSignBit(BitWidth))
Chris Lattner48595f12004-06-10 02:07:29 +00002170 return BinaryOperator::createXor(LHS, RHS);
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002171
2172 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2173 // (X & 254)+1 -> (X&254)|1
Reid Spencer2ec619a2007-03-23 21:24:59 +00002174 if (!isa<VectorType>(I.getType())) {
2175 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2176 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
2177 KnownZero, KnownOne))
2178 return &I;
2179 }
Chris Lattner66331a42004-04-10 22:01:55 +00002180 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002181
2182 if (isa<PHINode>(LHS))
2183 if (Instruction *NV = FoldOpIntoPhi(I))
2184 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +00002185
Chris Lattner4f637d42006-01-06 17:59:59 +00002186 ConstantInt *XorRHS = 0;
2187 Value *XorLHS = 0;
Chris Lattnerc5eff442007-01-30 22:32:46 +00002188 if (isa<ConstantInt>(RHSC) &&
2189 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002190 uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002191 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner5931c542005-09-24 23:43:33 +00002192
Zhou Sheng4351c642007-04-02 08:20:41 +00002193 uint32_t Size = TySizeBits / 2;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002194 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2195 APInt CFF80Val(-C0080Val);
Chris Lattner5931c542005-09-24 23:43:33 +00002196 do {
2197 if (TySizeBits > Size) {
Chris Lattner5931c542005-09-24 23:43:33 +00002198 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2199 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002200 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2201 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner5931c542005-09-24 23:43:33 +00002202 // This is a sign extend if the top bits are known zero.
Zhou Sheng290bec52007-03-29 08:15:12 +00002203 if (!MaskedValueIsZero(XorLHS,
2204 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner5931c542005-09-24 23:43:33 +00002205 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002206 break;
Chris Lattner5931c542005-09-24 23:43:33 +00002207 }
2208 }
2209 Size >>= 1;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002210 C0080Val = APIntOps::lshr(C0080Val, Size);
2211 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2212 } while (Size >= 1);
Chris Lattner5931c542005-09-24 23:43:33 +00002213
Reid Spencer35c38852007-03-28 01:36:16 +00002214 // FIXME: This shouldn't be necessary. When the backends can handle types
2215 // with funny bit widths then this whole cascade of if statements should
2216 // be removed. It is just here to get the size of the "middle" type back
2217 // up to something that the back ends can handle.
2218 const Type *MiddleType = 0;
2219 switch (Size) {
2220 default: break;
2221 case 32: MiddleType = Type::Int32Ty; break;
2222 case 16: MiddleType = Type::Int16Ty; break;
2223 case 8: MiddleType = Type::Int8Ty; break;
2224 }
2225 if (MiddleType) {
Reid Spencerd977d862006-12-12 23:36:14 +00002226 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
Chris Lattner5931c542005-09-24 23:43:33 +00002227 InsertNewInstBefore(NewTrunc, I);
Reid Spencer35c38852007-03-28 01:36:16 +00002228 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner5931c542005-09-24 23:43:33 +00002229 }
2230 }
Chris Lattner66331a42004-04-10 22:01:55 +00002231 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002232
Chris Lattner564a7272003-08-13 19:01:45 +00002233 // X + X --> X << 1
Chris Lattner42a75512007-01-15 02:27:26 +00002234 if (I.getType()->isInteger() && I.getType() != Type::Int1Ty) {
Chris Lattner564a7272003-08-13 19:01:45 +00002235 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +00002236
2237 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2238 if (RHSI->getOpcode() == Instruction::Sub)
2239 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2240 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2241 }
2242 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2243 if (LHSI->getOpcode() == Instruction::Sub)
2244 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2245 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2246 }
Robert Bocchino71698282004-07-27 21:02:21 +00002247 }
Chris Lattnere92d2f42003-08-13 04:18:28 +00002248
Chris Lattner5c4afb92002-05-08 22:46:53 +00002249 // -A + B --> B - A
Chris Lattnerdd12f962008-02-17 21:03:36 +00002250 // -A + -B --> -(A + B)
2251 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattnere10c0b92008-02-18 17:50:16 +00002252 if (LHS->getType()->isIntOrIntVector()) {
2253 if (Value *RHSV = dyn_castNegVal(RHS)) {
2254 Instruction *NewAdd = BinaryOperator::createAdd(LHSV, RHSV, "sum");
2255 InsertNewInstBefore(NewAdd, I);
2256 return BinaryOperator::createNeg(NewAdd);
2257 }
Chris Lattnerdd12f962008-02-17 21:03:36 +00002258 }
2259
2260 return BinaryOperator::createSub(RHS, LHSV);
2261 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002262
2263 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +00002264 if (!isa<Constant>(RHS))
2265 if (Value *V = dyn_castNegVal(RHS))
Chris Lattner48595f12004-06-10 02:07:29 +00002266 return BinaryOperator::createSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002267
Misha Brukmanfd939082005-04-21 23:48:37 +00002268
Chris Lattner50af16a2004-11-13 19:50:12 +00002269 ConstantInt *C2;
2270 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2271 if (X == RHS) // X*C + X --> X * (C+1)
2272 return BinaryOperator::createMul(RHS, AddOne(C2));
2273
2274 // X*C1 + X*C2 --> X * (C1+C2)
2275 ConstantInt *C1;
2276 if (X == dyn_castFoldableMul(RHS, C1))
Reid Spencer7177c3a2007-03-25 05:33:51 +00002277 return BinaryOperator::createMul(X, Add(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002278 }
2279
2280 // X + X*C --> X * (C+1)
Chris Lattner50af16a2004-11-13 19:50:12 +00002281 if (dyn_castFoldableMul(RHS, C2) == LHS)
2282 return BinaryOperator::createMul(LHS, AddOne(C2));
2283
Chris Lattnere617c9e2007-01-05 02:17:46 +00002284 // X + ~X --> -1 since ~X = -X-1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00002285 if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2286 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere617c9e2007-01-05 02:17:46 +00002287
Chris Lattnerad3448c2003-02-18 19:57:07 +00002288
Chris Lattner564a7272003-08-13 19:01:45 +00002289 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002290 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnere617c9e2007-01-05 02:17:46 +00002291 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2292 return R;
Chris Lattnerc8802d22003-03-11 00:12:48 +00002293
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002294 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky0c2c3f62008-02-03 08:19:11 +00002295 if (I.getType()->isIntOrIntVector()) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002296 Value *W, *X, *Y, *Z;
2297 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2298 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2299 if (W != Y) {
2300 if (W == Z) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002301 std::swap(Y, Z);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002302 } else if (Y == X) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002303 std::swap(W, X);
2304 } else if (X == Z) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002305 std::swap(Y, Z);
2306 std::swap(W, X);
2307 }
2308 }
2309
2310 if (W == Y) {
2311 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, Z,
2312 LHS->getName()), I);
2313 return BinaryOperator::createMul(W, NewAdd);
2314 }
2315 }
2316 }
2317
Chris Lattner6b032052003-10-02 15:11:26 +00002318 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002319 Value *X = 0;
Reid Spencer7177c3a2007-03-25 05:33:51 +00002320 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
2321 return BinaryOperator::createSub(SubOne(CRHS), X);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002322
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002323 // (X & FF00) + xx00 -> (X+xx00) & FF00
2324 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002325 Constant *Anded = And(CRHS, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002326 if (Anded == CRHS) {
2327 // See if all bits from the first bit set in the Add RHS up are included
2328 // in the mask. First, get the rightmost bit.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002329 const APInt& AddRHSV = CRHS->getValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002330
2331 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002332 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002333
2334 // See if the and mask includes all of these bits.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002335 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanfd939082005-04-21 23:48:37 +00002336
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002337 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2338 // Okay, the xform is safe. Insert the new add pronto.
2339 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
2340 LHS->getName()), I);
2341 return BinaryOperator::createAnd(NewAdd, C2);
2342 }
2343 }
2344 }
2345
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002346 // Try to fold constant add into select arguments.
2347 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002348 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002349 return R;
Chris Lattner6b032052003-10-02 15:11:26 +00002350 }
2351
Reid Spencer1628cec2006-10-26 06:15:43 +00002352 // add (cast *A to intptrtype) B ->
Chris Lattner42790482007-12-20 01:56:58 +00002353 // cast (GEP (cast *A to sbyte*) B) --> intptrtype
Andrew Lenharth16d79552006-09-19 18:24:51 +00002354 {
Reid Spencer3da59db2006-11-27 01:05:10 +00002355 CastInst *CI = dyn_cast<CastInst>(LHS);
2356 Value *Other = RHS;
Andrew Lenharth16d79552006-09-19 18:24:51 +00002357 if (!CI) {
2358 CI = dyn_cast<CastInst>(RHS);
2359 Other = LHS;
2360 }
Andrew Lenharth45633262006-09-20 15:37:57 +00002361 if (CI && CI->getType()->isSized() &&
Reid Spencerabaa8ca2007-01-08 16:32:00 +00002362 (CI->getType()->getPrimitiveSizeInBits() ==
2363 TD->getIntPtrType()->getPrimitiveSizeInBits())
Andrew Lenharth45633262006-09-20 15:37:57 +00002364 && isa<PointerType>(CI->getOperand(0)->getType())) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00002365 unsigned AS =
2366 cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +00002367 Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2368 PointerType::get(Type::Int8Ty, AS), I);
Andrew Lenharth45633262006-09-20 15:37:57 +00002369 I2 = InsertNewInstBefore(new GetElementPtrInst(I2, Other, "ctg2"), I);
Reid Spencer3da59db2006-11-27 01:05:10 +00002370 return new PtrToIntInst(I2, CI->getType());
Andrew Lenharth16d79552006-09-19 18:24:51 +00002371 }
2372 }
Christopher Lamb30f017a2007-12-18 09:34:41 +00002373
Chris Lattner42790482007-12-20 01:56:58 +00002374 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb30f017a2007-12-18 09:34:41 +00002375 {
2376 SelectInst *SI = dyn_cast<SelectInst>(LHS);
2377 Value *Other = RHS;
2378 if (!SI) {
2379 SI = dyn_cast<SelectInst>(RHS);
2380 Other = LHS;
2381 }
Chris Lattner42790482007-12-20 01:56:58 +00002382 if (SI && SI->hasOneUse()) {
Christopher Lamb30f017a2007-12-18 09:34:41 +00002383 Value *TV = SI->getTrueValue();
2384 Value *FV = SI->getFalseValue();
Chris Lattner42790482007-12-20 01:56:58 +00002385 Value *A, *N;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002386
2387 // Can we fold the add into the argument of the select?
2388 // We check both true and false select arguments for a matching subtract.
Chris Lattner42790482007-12-20 01:56:58 +00002389 if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Value(A))) &&
2390 A == Other) // Fold the add into the true select value.
2391 return new SelectInst(SI->getCondition(), N, A);
2392 if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Value(A))) &&
2393 A == Other) // Fold the add into the false select value.
2394 return new SelectInst(SI->getCondition(), A, N);
Christopher Lamb30f017a2007-12-18 09:34:41 +00002395 }
2396 }
Chris Lattner2454a2e2008-01-29 06:52:45 +00002397
2398 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2399 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2400 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2401 return ReplaceInstUsesWith(I, LHS);
Andrew Lenharth16d79552006-09-19 18:24:51 +00002402
Chris Lattner7e708292002-06-25 16:13:24 +00002403 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002404}
2405
Chris Lattner1ba5bcd2003-07-22 21:46:59 +00002406// isSignBit - Return true if the value represented by the constant only has the
2407// highest order bit set.
2408static bool isSignBit(ConstantInt *CI) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002409 uint32_t NumBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencer5a1e3e12007-03-19 20:58:18 +00002410 return CI->getValue() == APInt::getSignBit(NumBits);
Chris Lattner1ba5bcd2003-07-22 21:46:59 +00002411}
2412
Chris Lattner7e708292002-06-25 16:13:24 +00002413Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00002414 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002415
Chris Lattner233f7dc2002-08-12 21:17:25 +00002416 if (Op0 == Op1) // sub X, X -> 0
2417 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002418
Chris Lattner233f7dc2002-08-12 21:17:25 +00002419 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattner8d969642003-03-10 23:06:50 +00002420 if (Value *V = dyn_castNegVal(Op1))
Chris Lattner48595f12004-06-10 02:07:29 +00002421 return BinaryOperator::createAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002422
Chris Lattnere87597f2004-10-16 18:11:37 +00002423 if (isa<UndefValue>(Op0))
2424 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2425 if (isa<UndefValue>(Op1))
2426 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2427
Chris Lattnerd65460f2003-11-05 01:06:05 +00002428 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2429 // Replace (-1 - A) with (~A)...
Chris Lattnera2881962003-02-18 19:28:33 +00002430 if (C->isAllOnesValue())
2431 return BinaryOperator::createNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +00002432
Chris Lattnerd65460f2003-11-05 01:06:05 +00002433 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002434 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002435 if (match(Op1, m_Not(m_Value(X))))
Reid Spencer7177c3a2007-03-25 05:33:51 +00002436 return BinaryOperator::createAdd(X, AddOne(C));
2437
Chris Lattner76b7a062007-01-15 07:02:54 +00002438 // -(X >>u 31) -> (X >>s 31)
2439 // -(X >>s 31) -> (X >>u 31)
Zhou Sheng302748d2007-03-30 17:20:39 +00002440 if (C->isZero()) {
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002441 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002442 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002443 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00002444 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002445 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerb83eb642006-10-20 07:07:24 +00002446 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002447 // Ok, the transformation is safe. Insert AShr.
Reid Spencer832254e2007-02-02 02:16:23 +00002448 return BinaryOperator::create(Instruction::AShr,
2449 SI->getOperand(0), CU, SI->getName());
Chris Lattner9c290672004-03-12 23:53:13 +00002450 }
2451 }
Reid Spencer3822ff52006-11-08 06:47:33 +00002452 }
2453 else if (SI->getOpcode() == Instruction::AShr) {
2454 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2455 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002456 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencer3822ff52006-11-08 06:47:33 +00002457 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00002458 // Ok, the transformation is safe. Insert LShr.
Reid Spencercc46cdb2007-02-02 14:08:20 +00002459 return BinaryOperator::createLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00002460 SI->getOperand(0), CU, SI->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00002461 }
2462 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002463 }
2464 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00002465 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002466
2467 // Try to fold constant sub into select arguments.
2468 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002469 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002470 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002471
2472 if (isa<PHINode>(Op0))
2473 if (Instruction *NV = FoldOpIntoPhi(I))
2474 return NV;
Chris Lattnerd65460f2003-11-05 01:06:05 +00002475 }
2476
Chris Lattner43d84d62005-04-07 16:15:25 +00002477 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2478 if (Op1I->getOpcode() == Instruction::Add &&
Chris Lattner9919e3d2006-12-02 00:13:08 +00002479 !Op0->getType()->isFPOrFPVector()) {
Chris Lattner08954a22005-04-07 16:28:01 +00002480 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Chris Lattner43d84d62005-04-07 16:15:25 +00002481 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002482 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Chris Lattner43d84d62005-04-07 16:15:25 +00002483 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002484 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2485 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2486 // C1-(X+C2) --> (C1-C2)-X
Reid Spencer7177c3a2007-03-25 05:33:51 +00002487 return BinaryOperator::createSub(Subtract(CI1, CI2),
Chris Lattner08954a22005-04-07 16:28:01 +00002488 Op1I->getOperand(0));
2489 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002490 }
2491
Chris Lattnerfd059242003-10-15 16:48:29 +00002492 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002493 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2494 // is not used by anyone else...
2495 //
Chris Lattner0517e722004-02-02 20:09:56 +00002496 if (Op1I->getOpcode() == Instruction::Sub &&
Chris Lattner9919e3d2006-12-02 00:13:08 +00002497 !Op1I->getType()->isFPOrFPVector()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002498 // Swap the two operands of the subexpr...
2499 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2500 Op1I->setOperand(0, IIOp1);
2501 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00002502
Chris Lattnera2881962003-02-18 19:28:33 +00002503 // Create the new top level add instruction...
Chris Lattner48595f12004-06-10 02:07:29 +00002504 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00002505 }
2506
2507 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2508 //
2509 if (Op1I->getOpcode() == Instruction::And &&
2510 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2511 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2512
Chris Lattnerf523d062004-06-09 05:08:07 +00002513 Value *NewNot =
2514 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattner48595f12004-06-10 02:07:29 +00002515 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00002516 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00002517
Reid Spencerac5209e2006-10-16 23:08:08 +00002518 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer1628cec2006-10-26 06:15:43 +00002519 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencerb83eb642006-10-20 07:07:24 +00002520 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Zhou Sheng843f07672007-04-19 05:39:12 +00002521 if (CSI->isZero())
Chris Lattner91ccc152004-10-06 15:08:25 +00002522 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Reid Spencer1628cec2006-10-26 06:15:43 +00002523 return BinaryOperator::createSDiv(Op1I->getOperand(0),
Chris Lattner91ccc152004-10-06 15:08:25 +00002524 ConstantExpr::getNeg(DivRHS));
2525
Chris Lattnerad3448c2003-02-18 19:57:07 +00002526 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002527 ConstantInt *C2 = 0;
Chris Lattner50af16a2004-11-13 19:50:12 +00002528 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002529 Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
Chris Lattner48595f12004-06-10 02:07:29 +00002530 return BinaryOperator::createMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00002531 }
Dan Gohman5d066ff2007-09-17 17:31:57 +00002532
2533 // X - ((X / Y) * Y) --> X % Y
2534 if (Op1I->getOpcode() == Instruction::Mul)
2535 if (Instruction *I = dyn_cast<Instruction>(Op1I->getOperand(0)))
2536 if (Op0 == I->getOperand(0) &&
2537 Op1I->getOperand(1) == I->getOperand(1)) {
2538 if (I->getOpcode() == Instruction::SDiv)
2539 return BinaryOperator::createSRem(Op0, Op1I->getOperand(1));
2540 if (I->getOpcode() == Instruction::UDiv)
2541 return BinaryOperator::createURem(Op0, Op1I->getOperand(1));
2542 }
Chris Lattner40371712002-05-09 01:29:19 +00002543 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002544 }
Chris Lattnera2881962003-02-18 19:28:33 +00002545
Chris Lattner9919e3d2006-12-02 00:13:08 +00002546 if (!Op0->getType()->isFPOrFPVector())
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002547 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner7edc8c22005-04-07 17:14:51 +00002548 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00002549 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2550 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2551 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2552 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner7edc8c22005-04-07 17:14:51 +00002553 } else if (Op0I->getOpcode() == Instruction::Sub) {
2554 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
2555 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00002556 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002557 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002558
Chris Lattner50af16a2004-11-13 19:50:12 +00002559 ConstantInt *C1;
2560 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002561 if (X == Op1) // X*C - X --> X * (C-1)
2562 return BinaryOperator::createMul(Op1, SubOne(C1));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002563
Chris Lattner50af16a2004-11-13 19:50:12 +00002564 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2565 if (X == dyn_castFoldableMul(Op1, C2))
Zhou Sheng58d13af2008-02-22 10:00:35 +00002566 return BinaryOperator::createMul(X, Subtract(C1, C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002567 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002568 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002569}
2570
Chris Lattnera0141b92007-07-15 20:42:37 +00002571/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2572/// comparison only checks the sign bit. If it only checks the sign bit, set
2573/// TrueIfSigned if the result of the comparison is true when the input value is
2574/// signed.
2575static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2576 bool &TrueIfSigned) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002577 switch (pred) {
Chris Lattnera0141b92007-07-15 20:42:37 +00002578 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2579 TrueIfSigned = true;
2580 return RHS->isZero();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002581 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2582 TrueIfSigned = true;
2583 return RHS->isAllOnesValue();
Chris Lattnera0141b92007-07-15 20:42:37 +00002584 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2585 TrueIfSigned = false;
2586 return RHS->isAllOnesValue();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002587 case ICmpInst::ICMP_UGT:
2588 // True if LHS u> RHS and RHS == high-bit-mask - 1
2589 TrueIfSigned = true;
2590 return RHS->getValue() ==
2591 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2592 case ICmpInst::ICMP_UGE:
2593 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2594 TrueIfSigned = true;
2595 return RHS->getValue() ==
2596 APInt::getSignBit(RHS->getType()->getPrimitiveSizeInBits());
Chris Lattnera0141b92007-07-15 20:42:37 +00002597 default:
2598 return false;
Chris Lattner4cb170c2004-02-23 06:38:22 +00002599 }
Chris Lattner4cb170c2004-02-23 06:38:22 +00002600}
2601
Chris Lattner7e708292002-06-25 16:13:24 +00002602Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002603 bool Changed = SimplifyCommutative(I);
Chris Lattnera2881962003-02-18 19:28:33 +00002604 Value *Op0 = I.getOperand(0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002605
Chris Lattnere87597f2004-10-16 18:11:37 +00002606 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2607 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2608
Chris Lattner233f7dc2002-08-12 21:17:25 +00002609 // Simplify mul instructions with a constant RHS...
Chris Lattnera2881962003-02-18 19:28:33 +00002610 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2611 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00002612
2613 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer832254e2007-02-02 02:16:23 +00002614 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnere92d2f42003-08-13 04:18:28 +00002615 if (SI->getOpcode() == Instruction::Shl)
2616 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattner48595f12004-06-10 02:07:29 +00002617 return BinaryOperator::createMul(SI->getOperand(0),
2618 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00002619
Zhou Sheng843f07672007-04-19 05:39:12 +00002620 if (CI->isZero())
Chris Lattner515c97c2003-09-11 22:24:54 +00002621 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2622 if (CI->equalsInt(1)) // X * 1 == X
2623 return ReplaceInstUsesWith(I, Op0);
2624 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner0af1fab2003-06-25 17:09:20 +00002625 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00002626
Zhou Sheng97b52c22007-03-29 01:57:21 +00002627 const APInt& Val = cast<ConstantInt>(CI)->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002628 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Reid Spencercc46cdb2007-02-02 14:08:20 +00002629 return BinaryOperator::createShl(Op0,
Reid Spencerbca0e382007-03-23 20:05:17 +00002630 ConstantInt::get(Op0->getType(), Val.logBase2()));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00002631 }
Robert Bocchino71698282004-07-27 21:02:21 +00002632 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattnera2881962003-02-18 19:28:33 +00002633 if (Op1F->isNullValue())
2634 return ReplaceInstUsesWith(I, Op1);
Chris Lattner6c1ce212002-04-29 22:24:47 +00002635
Chris Lattnera2881962003-02-18 19:28:33 +00002636 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2637 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00002638 // We need a better interface for long double here.
2639 if (Op1->getType() == Type::FloatTy || Op1->getType() == Type::DoubleTy)
2640 if (Op1F->isExactlyValue(1.0))
2641 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
Chris Lattnera2881962003-02-18 19:28:33 +00002642 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002643
2644 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2645 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2646 isa<ConstantInt>(Op0I->getOperand(1))) {
2647 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2648 Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
2649 Op1, "tmp");
2650 InsertNewInstBefore(Add, I);
2651 Value *C1C2 = ConstantExpr::getMul(Op1,
2652 cast<Constant>(Op0I->getOperand(1)));
2653 return BinaryOperator::createAdd(Add, C1C2);
2654
2655 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002656
2657 // Try to fold constant mul into select arguments.
2658 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002659 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002660 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002661
2662 if (isa<PHINode>(Op0))
2663 if (Instruction *NV = FoldOpIntoPhi(I))
2664 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002665 }
2666
Chris Lattnera4f445b2003-03-10 23:23:04 +00002667 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2668 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattner48595f12004-06-10 02:07:29 +00002669 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00002670
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002671 // If one of the operands of the multiply is a cast from a boolean value, then
2672 // we know the bool is either zero or one, so this is a 'masking' multiply.
2673 // See if we can simplify things based on how the boolean was originally
2674 // formed.
2675 CastInst *BoolCast = 0;
Reid Spencerc55b2432006-12-13 18:21:21 +00002676 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(0)))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002677 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002678 BoolCast = CI;
2679 if (!BoolCast)
Reid Spencerc55b2432006-12-13 18:21:21 +00002680 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002681 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002682 BoolCast = CI;
2683 if (BoolCast) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002684 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002685 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2686 const Type *SCOpTy = SCIOp0->getType();
Chris Lattnera0141b92007-07-15 20:42:37 +00002687 bool TIS = false;
2688
Reid Spencere4d87aa2006-12-23 06:05:41 +00002689 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattner4cb170c2004-02-23 06:38:22 +00002690 // multiply into a shift/and combination.
2691 if (isa<ConstantInt>(SCIOp1) &&
Chris Lattnera0141b92007-07-15 20:42:37 +00002692 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2693 TIS) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002694 // Shift the X value right to turn it into "all signbits".
Reid Spencer832254e2007-02-02 02:16:23 +00002695 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
Chris Lattner484d3cf2005-04-24 06:59:08 +00002696 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattner4cb170c2004-02-23 06:38:22 +00002697 Value *V =
Reid Spencer832254e2007-02-02 02:16:23 +00002698 InsertNewInstBefore(
2699 BinaryOperator::create(Instruction::AShr, SCIOp0, Amt,
Chris Lattner4cb170c2004-02-23 06:38:22 +00002700 BoolCast->getOperand(0)->getName()+
2701 ".mask"), I);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002702
2703 // If the multiply type is not the same as the source type, sign extend
2704 // or truncate to the multiply type.
Reid Spencer17212df2006-12-12 09:18:51 +00002705 if (I.getType() != V->getType()) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002706 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2707 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +00002708 Instruction::CastOps opcode =
2709 (SrcBits == DstBits ? Instruction::BitCast :
2710 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2711 V = InsertCastBefore(opcode, V, I.getType(), I);
2712 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002713
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002714 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattner48595f12004-06-10 02:07:29 +00002715 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002716 }
2717 }
2718 }
2719
Chris Lattner7e708292002-06-25 16:13:24 +00002720 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002721}
2722
Reid Spencer1628cec2006-10-26 06:15:43 +00002723/// This function implements the transforms on div instructions that work
2724/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2725/// used by the visitors to those instructions.
2726/// @brief Transforms common to all three div instructions
Reid Spencer3da59db2006-11-27 01:05:10 +00002727Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002728 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00002729
Chris Lattner50b2ca42008-02-19 06:12:18 +00002730 // undef / X -> 0 for integer.
2731 // undef / X -> undef for FP (the undef could be a snan).
2732 if (isa<UndefValue>(Op0)) {
2733 if (Op0->getType()->isFPOrFPVector())
2734 return ReplaceInstUsesWith(I, Op0);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002735 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00002736 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002737
2738 // X / undef -> undef
Chris Lattner857e8cd2004-12-12 21:48:58 +00002739 if (isa<UndefValue>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00002740 return ReplaceInstUsesWith(I, Op1);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002741
Chris Lattner25feae52008-01-28 00:58:18 +00002742 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2743 // This does not apply for fdiv.
Chris Lattner8e49e082006-09-09 20:26:32 +00002744 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
Chris Lattner25feae52008-01-28 00:58:18 +00002745 // [su]div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in
2746 // the same basic block, then we replace the select with Y, and the
2747 // condition of the select with false (if the cond value is in the same BB).
2748 // If the select has uses other than the div, this allows them to be
2749 // simplified also. Note that div X, Y is just as good as div X, 0 (undef)
2750 if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(1)))
Chris Lattner8e49e082006-09-09 20:26:32 +00002751 if (ST->isNullValue()) {
2752 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2753 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002754 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Chris Lattner8e49e082006-09-09 20:26:32 +00002755 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2756 I.setOperand(1, SI->getOperand(2));
2757 else
2758 UpdateValueUsesWith(SI, SI->getOperand(2));
2759 return &I;
2760 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002761
Chris Lattner25feae52008-01-28 00:58:18 +00002762 // Likewise for: [su]div X, (Cond ? Y : 0) -> div X, Y
2763 if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(2)))
Chris Lattner8e49e082006-09-09 20:26:32 +00002764 if (ST->isNullValue()) {
2765 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2766 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002767 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Chris Lattner8e49e082006-09-09 20:26:32 +00002768 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2769 I.setOperand(1, SI->getOperand(1));
2770 else
2771 UpdateValueUsesWith(SI, SI->getOperand(1));
2772 return &I;
2773 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002774 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002775
Reid Spencer1628cec2006-10-26 06:15:43 +00002776 return 0;
2777}
Misha Brukmanfd939082005-04-21 23:48:37 +00002778
Reid Spencer1628cec2006-10-26 06:15:43 +00002779/// This function implements the transforms common to both integer division
2780/// instructions (udiv and sdiv). It is called by the visitors to those integer
2781/// division instructions.
2782/// @brief Common integer divide transforms
Reid Spencer3da59db2006-11-27 01:05:10 +00002783Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002784 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2785
2786 if (Instruction *Common = commonDivTransforms(I))
2787 return Common;
2788
2789 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2790 // div X, 1 == X
2791 if (RHS->equalsInt(1))
2792 return ReplaceInstUsesWith(I, Op0);
2793
2794 // (X / C1) / C2 -> X / (C1*C2)
2795 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2796 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2797 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00002798 if (MultiplyOverflows(RHS, LHSRHS, I.getOpcode()==Instruction::SDiv))
2799 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2800 else
2801 return BinaryOperator::create(I.getOpcode(), LHS->getOperand(0),
2802 Multiply(RHS, LHSRHS));
Chris Lattnerbf70b832005-04-08 04:03:26 +00002803 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002804
Reid Spencerbca0e382007-03-23 20:05:17 +00002805 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer1628cec2006-10-26 06:15:43 +00002806 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2807 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2808 return R;
2809 if (isa<PHINode>(Op0))
2810 if (Instruction *NV = FoldOpIntoPhi(I))
2811 return NV;
2812 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002813 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002814
Chris Lattnera2881962003-02-18 19:28:33 +00002815 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00002816 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00002817 if (LHS->equalsInt(0))
2818 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2819
Reid Spencer1628cec2006-10-26 06:15:43 +00002820 return 0;
2821}
2822
2823Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2824 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2825
2826 // Handle the integer div common cases
2827 if (Instruction *Common = commonIDivTransforms(I))
2828 return Common;
2829
2830 // X udiv C^2 -> X >> C
2831 // Check to see if this is an unsigned division with an exact power of 2,
2832 // if so, convert to a right shift.
2833 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Reid Spencer6eb0d992007-03-26 23:58:26 +00002834 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Reid Spencerbca0e382007-03-23 20:05:17 +00002835 return BinaryOperator::createLShr(Op0,
Zhou Sheng0fc50952007-03-25 05:01:29 +00002836 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Reid Spencer1628cec2006-10-26 06:15:43 +00002837 }
2838
2839 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer832254e2007-02-02 02:16:23 +00002840 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002841 if (RHSI->getOpcode() == Instruction::Shl &&
2842 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002843 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002844 if (C1.isPowerOf2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002845 Value *N = RHSI->getOperand(1);
Reid Spencer3da59db2006-11-27 01:05:10 +00002846 const Type *NTy = N->getType();
Reid Spencer2ec619a2007-03-23 21:24:59 +00002847 if (uint32_t C2 = C1.logBase2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002848 Constant *C2V = ConstantInt::get(NTy, C2);
2849 N = InsertNewInstBefore(BinaryOperator::createAdd(N, C2V, "tmp"), I);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002850 }
Reid Spencercc46cdb2007-02-02 14:08:20 +00002851 return BinaryOperator::createLShr(Op0, N);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002852 }
2853 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00002854 }
2855
Reid Spencer1628cec2006-10-26 06:15:43 +00002856 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2857 // where C1&C2 are powers of two.
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002858 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00002859 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002860 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002861 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002862 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002863 // Compute the shift amounts
Reid Spencerbca0e382007-03-23 20:05:17 +00002864 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002865 // Construct the "on true" case of the select
2866 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
2867 Instruction *TSI = BinaryOperator::createLShr(
2868 Op0, TC, SI->getName()+".t");
2869 TSI = InsertNewInstBefore(TSI, I);
2870
2871 // Construct the "on false" case of the select
2872 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
2873 Instruction *FSI = BinaryOperator::createLShr(
2874 Op0, FC, SI->getName()+".f");
2875 FSI = InsertNewInstBefore(FSI, I);
Reid Spencer1628cec2006-10-26 06:15:43 +00002876
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002877 // construct the select instruction and return it.
2878 return new SelectInst(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00002879 }
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002880 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002881 return 0;
2882}
2883
Reid Spencer1628cec2006-10-26 06:15:43 +00002884Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2885 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2886
2887 // Handle the integer div common cases
2888 if (Instruction *Common = commonIDivTransforms(I))
2889 return Common;
2890
2891 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2892 // sdiv X, -1 == -X
2893 if (RHS->isAllOnesValue())
2894 return BinaryOperator::createNeg(Op0);
2895
2896 // -X/C -> X/-C
2897 if (Value *LHSNeg = dyn_castNegVal(Op0))
2898 return BinaryOperator::createSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2899 }
2900
2901 // If the sign bits of both operands are zero (i.e. we can prove they are
2902 // unsigned inputs), turn this into a udiv.
Chris Lattner42a75512007-01-15 02:27:26 +00002903 if (I.getType()->isInteger()) {
Reid Spencerbca0e382007-03-23 20:05:17 +00002904 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Reid Spencer1628cec2006-10-26 06:15:43 +00002905 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Dan Gohmancff55092007-11-05 23:16:33 +00002906 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
Reid Spencer1628cec2006-10-26 06:15:43 +00002907 return BinaryOperator::createUDiv(Op0, Op1, I.getName());
2908 }
2909 }
2910
2911 return 0;
2912}
2913
2914Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2915 return commonDivTransforms(I);
2916}
Chris Lattner3f5b8772002-05-06 16:14:14 +00002917
Reid Spencer0a783f72006-11-02 01:53:59 +00002918/// This function implements the transforms on rem instructions that work
2919/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
2920/// is used by the visitors to those instructions.
2921/// @brief Transforms common to all three rem instructions
2922Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002923 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer0a783f72006-11-02 01:53:59 +00002924
Chris Lattner50b2ca42008-02-19 06:12:18 +00002925 // 0 % X == 0 for integer, we don't need to preserve faults!
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002926 if (Constant *LHS = dyn_cast<Constant>(Op0))
2927 if (LHS->isNullValue())
2928 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2929
Chris Lattner50b2ca42008-02-19 06:12:18 +00002930 if (isa<UndefValue>(Op0)) { // undef % X -> 0
2931 if (I.getType()->isFPOrFPVector())
2932 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002933 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00002934 }
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002935 if (isa<UndefValue>(Op1))
2936 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer0a783f72006-11-02 01:53:59 +00002937
2938 // Handle cases involving: rem X, (select Cond, Y, Z)
2939 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2940 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
2941 // the same basic block, then we replace the select with Y, and the
2942 // condition of the select with false (if the cond value is in the same
2943 // BB). If the select has uses other than the div, this allows them to be
2944 // simplified also.
2945 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2946 if (ST->isNullValue()) {
2947 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2948 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002949 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Reid Spencer0a783f72006-11-02 01:53:59 +00002950 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2951 I.setOperand(1, SI->getOperand(2));
2952 else
2953 UpdateValueUsesWith(SI, SI->getOperand(2));
Chris Lattner5b73c082004-07-06 07:01:22 +00002954 return &I;
2955 }
Reid Spencer0a783f72006-11-02 01:53:59 +00002956 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2957 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2958 if (ST->isNullValue()) {
2959 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2960 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002961 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Reid Spencer0a783f72006-11-02 01:53:59 +00002962 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2963 I.setOperand(1, SI->getOperand(1));
2964 else
2965 UpdateValueUsesWith(SI, SI->getOperand(1));
2966 return &I;
2967 }
Chris Lattner11a49f22005-11-05 07:28:37 +00002968 }
Chris Lattner5b73c082004-07-06 07:01:22 +00002969
Reid Spencer0a783f72006-11-02 01:53:59 +00002970 return 0;
2971}
2972
2973/// This function implements the transforms common to both integer remainder
2974/// instructions (urem and srem). It is called by the visitors to those integer
2975/// remainder instructions.
2976/// @brief Common integer remainder transforms
2977Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2978 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2979
2980 if (Instruction *common = commonRemTransforms(I))
2981 return common;
2982
Chris Lattner857e8cd2004-12-12 21:48:58 +00002983 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002984 // X % 0 == undef, we don't need to preserve faults!
2985 if (RHS->equalsInt(0))
2986 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2987
Chris Lattnera2881962003-02-18 19:28:33 +00002988 if (RHS->equalsInt(1)) // X % 1 == 0
2989 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2990
Chris Lattner97943922006-02-28 05:49:21 +00002991 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2992 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2993 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2994 return R;
2995 } else if (isa<PHINode>(Op0I)) {
2996 if (Instruction *NV = FoldOpIntoPhi(I))
2997 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00002998 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00002999
3000 // See if we can fold away this rem instruction.
3001 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3002 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3003 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3004 KnownZero, KnownOne))
3005 return &I;
Chris Lattner97943922006-02-28 05:49:21 +00003006 }
Chris Lattnera2881962003-02-18 19:28:33 +00003007 }
3008
Reid Spencer0a783f72006-11-02 01:53:59 +00003009 return 0;
3010}
3011
3012Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3013 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3014
3015 if (Instruction *common = commonIRemTransforms(I))
3016 return common;
3017
3018 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3019 // X urem C^2 -> X and C
3020 // Check to see if this is an unsigned remainder with an exact power of 2,
3021 // if so, convert to a bitwise and.
3022 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencerbca0e382007-03-23 20:05:17 +00003023 if (C->getValue().isPowerOf2())
Reid Spencer0a783f72006-11-02 01:53:59 +00003024 return BinaryOperator::createAnd(Op0, SubOne(C));
3025 }
3026
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003027 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003028 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3029 if (RHSI->getOpcode() == Instruction::Shl &&
3030 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng0fc50952007-03-25 05:01:29 +00003031 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003032 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
3033 Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
3034 "tmp"), I);
3035 return BinaryOperator::createAnd(Op0, Add);
3036 }
3037 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003038 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003039
Reid Spencer0a783f72006-11-02 01:53:59 +00003040 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3041 // where C1&C2 are powers of two.
3042 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3043 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3044 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3045 // STO == 0 and SFO == 0 handled above.
Reid Spencerbca0e382007-03-23 20:05:17 +00003046 if ((STO->getValue().isPowerOf2()) &&
3047 (SFO->getValue().isPowerOf2())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003048 Value *TrueAnd = InsertNewInstBefore(
3049 BinaryOperator::createAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
3050 Value *FalseAnd = InsertNewInstBefore(
3051 BinaryOperator::createAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
3052 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
3053 }
3054 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003055 }
3056
Chris Lattner3f5b8772002-05-06 16:14:14 +00003057 return 0;
3058}
3059
Reid Spencer0a783f72006-11-02 01:53:59 +00003060Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3061 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3062
Dan Gohmancff55092007-11-05 23:16:33 +00003063 // Handle the integer rem common cases
Reid Spencer0a783f72006-11-02 01:53:59 +00003064 if (Instruction *common = commonIRemTransforms(I))
3065 return common;
3066
3067 if (Value *RHSNeg = dyn_castNegVal(Op1))
3068 if (!isa<ConstantInt>(RHSNeg) ||
Zhou Sheng0fc50952007-03-25 05:01:29 +00003069 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive()) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003070 // X % -Y -> X % Y
3071 AddUsesToWorkList(I);
3072 I.setOperand(1, RHSNeg);
3073 return &I;
3074 }
3075
Dan Gohmancff55092007-11-05 23:16:33 +00003076 // If the sign bits of both operands are zero (i.e. we can prove they are
Reid Spencer0a783f72006-11-02 01:53:59 +00003077 // unsigned inputs), turn this into a urem.
Dan Gohmancff55092007-11-05 23:16:33 +00003078 if (I.getType()->isInteger()) {
3079 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3080 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3081 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
3082 return BinaryOperator::createURem(Op0, Op1, I.getName());
3083 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003084 }
3085
3086 return 0;
3087}
3088
3089Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003090 return commonRemTransforms(I);
3091}
3092
Chris Lattner8b170942002-08-09 23:47:40 +00003093// isMaxValueMinusOne - return true if this is Max-1
Reid Spencere4d87aa2006-12-23 06:05:41 +00003094static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
Reid Spencer3a2a9fb2007-03-19 21:10:28 +00003095 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattnera0141b92007-07-15 20:42:37 +00003096 if (!isSigned)
3097 return C->getValue() == APInt::getAllOnesValue(TypeBits) - 1;
3098 return C->getValue() == APInt::getSignedMaxValue(TypeBits)-1;
Chris Lattner8b170942002-08-09 23:47:40 +00003099}
3100
3101// isMinValuePlusOne - return true if this is Min+1
Reid Spencere4d87aa2006-12-23 06:05:41 +00003102static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
Chris Lattnera0141b92007-07-15 20:42:37 +00003103 if (!isSigned)
3104 return C->getValue() == 1; // unsigned
3105
3106 // Calculate 1111111111000000000000
3107 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
3108 return C->getValue() == APInt::getSignedMinValue(TypeBits)+1;
Chris Lattner8b170942002-08-09 23:47:40 +00003109}
3110
Chris Lattner457dd822004-06-09 07:59:58 +00003111// isOneBitSet - Return true if there is exactly one bit set in the specified
3112// constant.
3113static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer5f6a8952007-03-20 00:16:52 +00003114 return CI->getValue().isPowerOf2();
Chris Lattner457dd822004-06-09 07:59:58 +00003115}
3116
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003117// isHighOnes - Return true if the constant is of the form 1+0+.
3118// This is the same as lowones(~X).
3119static bool isHighOnes(const ConstantInt *CI) {
Zhou Sheng2cde46c2007-03-20 12:49:06 +00003120 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003121}
3122
Reid Spencere4d87aa2006-12-23 06:05:41 +00003123/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003124/// are carefully arranged to allow folding of expressions such as:
3125///
3126/// (A < B) | (A > B) --> (A != B)
3127///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003128/// Note that this is only valid if the first and second predicates have the
3129/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003130///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003131/// Three bits are used to represent the condition, as follows:
3132/// 0 A > B
3133/// 1 A == B
3134/// 2 A < B
3135///
3136/// <=> Value Definition
3137/// 000 0 Always false
3138/// 001 1 A > B
3139/// 010 2 A == B
3140/// 011 3 A >= B
3141/// 100 4 A < B
3142/// 101 5 A != B
3143/// 110 6 A <= B
3144/// 111 7 Always true
3145///
3146static unsigned getICmpCode(const ICmpInst *ICI) {
3147 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003148 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00003149 case ICmpInst::ICMP_UGT: return 1; // 001
3150 case ICmpInst::ICMP_SGT: return 1; // 001
3151 case ICmpInst::ICMP_EQ: return 2; // 010
3152 case ICmpInst::ICMP_UGE: return 3; // 011
3153 case ICmpInst::ICMP_SGE: return 3; // 011
3154 case ICmpInst::ICMP_ULT: return 4; // 100
3155 case ICmpInst::ICMP_SLT: return 4; // 100
3156 case ICmpInst::ICMP_NE: return 5; // 101
3157 case ICmpInst::ICMP_ULE: return 6; // 110
3158 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003159 // True -> 7
3160 default:
Reid Spencere4d87aa2006-12-23 06:05:41 +00003161 assert(0 && "Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003162 return 0;
3163 }
3164}
3165
Reid Spencere4d87aa2006-12-23 06:05:41 +00003166/// getICmpValue - This is the complement of getICmpCode, which turns an
3167/// opcode and two operands into either a constant true or false, or a brand
Dan Gohman5d066ff2007-09-17 17:31:57 +00003168/// new ICmp instruction. The sign is passed in to determine which kind
Reid Spencere4d87aa2006-12-23 06:05:41 +00003169/// of predicate to use in new icmp instructions.
3170static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3171 switch (code) {
3172 default: assert(0 && "Illegal ICmp code!");
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003173 case 0: return ConstantInt::getFalse();
Reid Spencere4d87aa2006-12-23 06:05:41 +00003174 case 1:
3175 if (sign)
3176 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3177 else
3178 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3179 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
3180 case 3:
3181 if (sign)
3182 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3183 else
3184 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3185 case 4:
3186 if (sign)
3187 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3188 else
3189 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3190 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
3191 case 6:
3192 if (sign)
3193 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3194 else
3195 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003196 case 7: return ConstantInt::getTrue();
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003197 }
3198}
3199
Reid Spencere4d87aa2006-12-23 06:05:41 +00003200static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3201 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3202 (ICmpInst::isSignedPredicate(p1) &&
3203 (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
3204 (ICmpInst::isSignedPredicate(p2) &&
3205 (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
3206}
3207
3208namespace {
3209// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3210struct FoldICmpLogical {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003211 InstCombiner &IC;
3212 Value *LHS, *RHS;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003213 ICmpInst::Predicate pred;
3214 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3215 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3216 pred(ICI->getPredicate()) {}
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003217 bool shouldApply(Value *V) const {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003218 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3219 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003220 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3221 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003222 return false;
3223 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003224 Instruction *apply(Instruction &Log) const {
3225 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3226 if (ICI->getOperand(0) != LHS) {
3227 assert(ICI->getOperand(1) == LHS);
3228 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003229 }
3230
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003231 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003232 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003233 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003234 unsigned Code;
3235 switch (Log.getOpcode()) {
3236 case Instruction::And: Code = LHSCode & RHSCode; break;
3237 case Instruction::Or: Code = LHSCode | RHSCode; break;
3238 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner021c1902003-09-22 20:33:34 +00003239 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003240 }
3241
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003242 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3243 ICmpInst::isSignedPredicate(ICI->getPredicate());
3244
3245 Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003246 if (Instruction *I = dyn_cast<Instruction>(RV))
3247 return I;
3248 // Otherwise, it's a constant boolean value...
3249 return IC.ReplaceInstUsesWith(Log, RV);
3250 }
3251};
Chris Lattnerd23b5ba2006-11-15 04:53:24 +00003252} // end anonymous namespace
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003253
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003254// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3255// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +00003256// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003257Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003258 ConstantInt *OpRHS,
3259 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003260 BinaryOperator &TheAnd) {
3261 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00003262 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +00003263 if (!Op->isShift())
Reid Spencer7177c3a2007-03-25 05:33:51 +00003264 Together = And(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00003265
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003266 switch (Op->getOpcode()) {
3267 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003268 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003269 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Chris Lattner6934a042007-02-11 01:23:03 +00003270 Instruction *And = BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003271 InsertNewInstBefore(And, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003272 And->takeName(Op);
Chris Lattner48595f12004-06-10 02:07:29 +00003273 return BinaryOperator::createXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003274 }
3275 break;
3276 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003277 if (Together == AndRHS) // (X | C) & C --> C
3278 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003279
Chris Lattner6e7ba452005-01-01 16:22:27 +00003280 if (Op->hasOneUse() && Together != OpRHS) {
3281 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Chris Lattner6934a042007-02-11 01:23:03 +00003282 Instruction *Or = BinaryOperator::createOr(X, Together);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003283 InsertNewInstBefore(Or, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003284 Or->takeName(Op);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003285 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003286 }
3287 break;
3288 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00003289 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003290 // Adding a one to a single bit bit-field should be turned into an XOR
3291 // of the bit. First thing to check is to see if this AND is with a
3292 // single bit constant.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003293 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003294
3295 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00003296 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003297 // Ok, at this point, we know that we are masking the result of the
3298 // ADD down to exactly one bit. If the constant we are adding has
3299 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003300 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00003301
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003302 // Check to see if any bits below the one bit set in AndRHSV are set.
3303 if ((AddRHS & (AndRHSV-1)) == 0) {
3304 // If not, the only thing that can effect the output of the AND is
3305 // the bit specified by AndRHSV. If that bit is set, the effect of
3306 // the XOR is to toggle the bit. If it is clear, then the ADD has
3307 // no effect.
3308 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3309 TheAnd.setOperand(0, X);
3310 return &TheAnd;
3311 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003312 // Pull the XOR out of the AND.
Chris Lattner6934a042007-02-11 01:23:03 +00003313 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003314 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003315 NewAnd->takeName(Op);
Chris Lattner48595f12004-06-10 02:07:29 +00003316 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003317 }
3318 }
3319 }
3320 }
3321 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00003322
3323 case Instruction::Shl: {
3324 // We know that the AND will not produce any of the bits shifted in, so if
3325 // the anded constant includes them, clear them now!
3326 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003327 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003328 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003329 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3330 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00003331
Zhou Sheng290bec52007-03-29 08:15:12 +00003332 if (CI->getValue() == ShlMask) {
3333 // Masking out bits that the shift already masks
Chris Lattner0c967662004-09-24 15:21:34 +00003334 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3335 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00003336 TheAnd.setOperand(1, CI);
3337 return &TheAnd;
3338 }
3339 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00003340 }
Reid Spencer3822ff52006-11-08 06:47:33 +00003341 case Instruction::LShr:
3342 {
Chris Lattner62a355c2003-09-19 19:05:02 +00003343 // We know that the AND will not produce any of the bits shifted in, so if
3344 // the anded constant includes them, clear them now! This only applies to
3345 // unsigned shifts, because a signed shr may bring in set bits!
3346 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003347 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003348 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003349 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3350 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00003351
Zhou Sheng290bec52007-03-29 08:15:12 +00003352 if (CI->getValue() == ShrMask) {
3353 // Masking out bits that the shift already masks.
Reid Spencer3822ff52006-11-08 06:47:33 +00003354 return ReplaceInstUsesWith(TheAnd, Op);
3355 } else if (CI != AndRHS) {
3356 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3357 return &TheAnd;
3358 }
3359 break;
3360 }
3361 case Instruction::AShr:
3362 // Signed shr.
3363 // See if this is shifting in some sign extension, then masking it out
3364 // with an and.
3365 if (Op->hasOneUse()) {
Zhou Sheng290bec52007-03-29 08:15:12 +00003366 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003367 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003368 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3369 Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
Reid Spencer7eb76382006-12-13 17:19:09 +00003370 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +00003371 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +00003372 // Make the argument unsigned.
3373 Value *ShVal = Op->getOperand(0);
Reid Spencer832254e2007-02-02 02:16:23 +00003374 ShVal = InsertNewInstBefore(
Reid Spencercc46cdb2007-02-02 14:08:20 +00003375 BinaryOperator::createLShr(ShVal, OpRHS,
Reid Spencer832254e2007-02-02 02:16:23 +00003376 Op->getName()), TheAnd);
Reid Spencer7eb76382006-12-13 17:19:09 +00003377 return BinaryOperator::createAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00003378 }
Chris Lattner62a355c2003-09-19 19:05:02 +00003379 }
3380 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003381 }
3382 return 0;
3383}
3384
Chris Lattner8b170942002-08-09 23:47:40 +00003385
Chris Lattnera96879a2004-09-29 17:40:11 +00003386/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3387/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +00003388/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3389/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +00003390/// insert new instructions.
3391Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003392 bool isSigned, bool Inside,
3393 Instruction &IB) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003394 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +00003395 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +00003396 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003397
Chris Lattnera96879a2004-09-29 17:40:11 +00003398 if (Inside) {
3399 if (Lo == Hi) // Trivially false.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003400 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +00003401
Reid Spencere4d87aa2006-12-23 06:05:41 +00003402 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003403 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4e40032007-03-21 23:19:50 +00003404 ICmpInst::Predicate pred = (isSigned ?
Reid Spencere4d87aa2006-12-23 06:05:41 +00003405 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3406 return new ICmpInst(pred, V, Hi);
3407 }
3408
3409 // Emit V-Lo <u Hi-Lo
3410 Constant *NegLo = ConstantExpr::getNeg(Lo);
3411 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003412 InsertNewInstBefore(Add, IB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003413 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3414 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003415 }
3416
3417 if (Lo == Hi) // Trivially true.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003418 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +00003419
Reid Spencere4e40032007-03-21 23:19:50 +00003420 // V < Min || V >= Hi -> V > Hi-1
Chris Lattnera96879a2004-09-29 17:40:11 +00003421 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003422 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003423 ICmpInst::Predicate pred = (isSigned ?
3424 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3425 return new ICmpInst(pred, V, Hi);
3426 }
Reid Spencerb83eb642006-10-20 07:07:24 +00003427
Reid Spencere4e40032007-03-21 23:19:50 +00003428 // Emit V-Lo >u Hi-1-Lo
3429 // Note that Hi has already had one subtracted from it, above.
3430 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003431 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003432 InsertNewInstBefore(Add, IB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003433 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3434 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003435}
3436
Chris Lattner7203e152005-09-18 07:22:02 +00003437// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3438// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3439// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3440// not, since all 1s are not contiguous.
Zhou Sheng4351c642007-04-02 08:20:41 +00003441static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003442 const APInt& V = Val->getValue();
Reid Spencerf2442522007-03-24 00:42:08 +00003443 uint32_t BitWidth = Val->getType()->getBitWidth();
3444 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattner7203e152005-09-18 07:22:02 +00003445
3446 // look for the first zero bit after the run of ones
Reid Spencerf2442522007-03-24 00:42:08 +00003447 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattner7203e152005-09-18 07:22:02 +00003448 // look for the first non-zero bit
Reid Spencerf2442522007-03-24 00:42:08 +00003449 ME = V.getActiveBits();
Chris Lattner7203e152005-09-18 07:22:02 +00003450 return true;
3451}
3452
Chris Lattner7203e152005-09-18 07:22:02 +00003453/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3454/// where isSub determines whether the operator is a sub. If we can fold one of
3455/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00003456///
3457/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3458/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3459/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3460///
3461/// return (A +/- B).
3462///
3463Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003464 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +00003465 Instruction &I) {
3466 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3467 if (!LHSI || LHSI->getNumOperands() != 2 ||
3468 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3469
3470 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3471
3472 switch (LHSI->getOpcode()) {
3473 default: return 0;
3474 case Instruction::And:
Reid Spencer7177c3a2007-03-25 05:33:51 +00003475 if (And(N, Mask) == Mask) {
Chris Lattner7203e152005-09-18 07:22:02 +00003476 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Sheng00f436c2007-03-24 15:34:37 +00003477 if ((Mask->getValue().countLeadingZeros() +
3478 Mask->getValue().countPopulation()) ==
3479 Mask->getValue().getBitWidth())
Chris Lattner7203e152005-09-18 07:22:02 +00003480 break;
3481
3482 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3483 // part, we don't need any explicit masks to take them out of A. If that
3484 // is all N is, ignore it.
Zhou Sheng4351c642007-04-02 08:20:41 +00003485 uint32_t MB = 0, ME = 0;
Chris Lattner7203e152005-09-18 07:22:02 +00003486 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerb35ae032007-03-23 18:46:34 +00003487 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Sheng290bec52007-03-29 08:15:12 +00003488 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattner3bedbd92006-02-07 07:27:52 +00003489 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00003490 break;
3491 }
3492 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00003493 return 0;
3494 case Instruction::Or:
3495 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00003496 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Sheng00f436c2007-03-24 15:34:37 +00003497 if ((Mask->getValue().countLeadingZeros() +
3498 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Reid Spencer6eb0d992007-03-26 23:58:26 +00003499 && And(N, Mask)->isZero())
Chris Lattnerc8e77562005-09-18 04:24:45 +00003500 break;
3501 return 0;
3502 }
3503
3504 Instruction *New;
3505 if (isSub)
3506 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
3507 else
3508 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
3509 return InsertNewInstBefore(New, I);
3510}
3511
Chris Lattner7e708292002-06-25 16:13:24 +00003512Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003513 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00003514 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003515
Chris Lattnere87597f2004-10-16 18:11:37 +00003516 if (isa<UndefValue>(Op1)) // X & undef -> 0
3517 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3518
Chris Lattner6e7ba452005-01-01 16:22:27 +00003519 // and X, X = X
3520 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00003521 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003522
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003523 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00003524 // purpose is to compute bits we don't care about.
Reid Spencer9d6565a2007-02-15 02:26:10 +00003525 if (!isa<VectorType>(I.getType())) {
Reid Spencera03d45f2007-03-22 22:19:58 +00003526 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3527 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3528 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
Chris Lattner696ee0a2007-01-18 22:16:33 +00003529 KnownZero, KnownOne))
Reid Spencer6eb0d992007-03-26 23:58:26 +00003530 return &I;
Chris Lattner696ee0a2007-01-18 22:16:33 +00003531 } else {
Reid Spencer9d6565a2007-02-15 02:26:10 +00003532 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
Chris Lattner041a6c92007-06-15 05:26:55 +00003533 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
Chris Lattner696ee0a2007-01-18 22:16:33 +00003534 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner041a6c92007-06-15 05:26:55 +00003535 } else if (isa<ConstantAggregateZero>(Op1)) {
3536 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
Chris Lattner696ee0a2007-01-18 22:16:33 +00003537 }
3538 }
Chris Lattner9ca96412006-02-08 03:25:32 +00003539
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003540 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003541 const APInt& AndRHSMask = AndRHS->getValue();
3542 APInt NotAndRHS(~AndRHSMask);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003543
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003544 // Optimize a variety of ((val OP C1) & C2) combinations...
Reid Spencer832254e2007-02-02 02:16:23 +00003545 if (isa<BinaryOperator>(Op0)) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003546 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003547 Value *Op0LHS = Op0I->getOperand(0);
3548 Value *Op0RHS = Op0I->getOperand(1);
3549 switch (Op0I->getOpcode()) {
3550 case Instruction::Xor:
3551 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00003552 // If the mask is only needed on one incoming arm, push it up.
3553 if (Op0I->hasOneUse()) {
3554 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3555 // Not masking anything out for the LHS, move to RHS.
3556 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
3557 Op0RHS->getName()+".masked");
3558 InsertNewInstBefore(NewRHS, I);
3559 return BinaryOperator::create(
3560 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003561 }
Chris Lattner3bedbd92006-02-07 07:27:52 +00003562 if (!isa<Constant>(Op0RHS) &&
Chris Lattnerad1e3022005-01-23 20:26:55 +00003563 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3564 // Not masking anything out for the RHS, move to LHS.
3565 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
3566 Op0LHS->getName()+".masked");
3567 InsertNewInstBefore(NewLHS, I);
3568 return BinaryOperator::create(
3569 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3570 }
3571 }
3572
Chris Lattner6e7ba452005-01-01 16:22:27 +00003573 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00003574 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00003575 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3576 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3577 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3578 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3579 return BinaryOperator::createAnd(V, AndRHS);
3580 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3581 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00003582 break;
3583
3584 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00003585 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3586 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3587 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3588 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3589 return BinaryOperator::createAnd(V, AndRHS);
Chris Lattnerc8e77562005-09-18 04:24:45 +00003590 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00003591 }
3592
Chris Lattner58403262003-07-23 19:25:52 +00003593 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003594 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003595 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00003596 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00003597 // If this is an integer truncation or change from signed-to-unsigned, and
3598 // if the source is an and/or with immediate, transform it. This
3599 // frequently occurs for bitfield accesses.
3600 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00003601 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00003602 CastOp->getNumOperands() == 2)
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003603 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
Chris Lattner2b83af22005-08-07 07:03:10 +00003604 if (CastOp->getOpcode() == Instruction::And) {
3605 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00003606 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
3607 // This will fold the two constants together, which may allow
3608 // other simplifications.
Reid Spencerd977d862006-12-12 23:36:14 +00003609 Instruction *NewCast = CastInst::createTruncOrBitCast(
3610 CastOp->getOperand(0), I.getType(),
3611 CastOp->getName()+".shrunk");
Chris Lattner2b83af22005-08-07 07:03:10 +00003612 NewCast = InsertNewInstBefore(NewCast, I);
Reid Spencer3da59db2006-11-27 01:05:10 +00003613 // trunc_or_bitcast(C1)&C2
Reid Spencerd977d862006-12-12 23:36:14 +00003614 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00003615 C3 = ConstantExpr::getAnd(C3, AndRHS);
Chris Lattner2b83af22005-08-07 07:03:10 +00003616 return BinaryOperator::createAnd(NewCast, C3);
3617 } else if (CastOp->getOpcode() == Instruction::Or) {
3618 // Change: and (cast (or X, C1) to T), C2
3619 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattnerbb4e7b22006-12-12 19:11:20 +00003620 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Chris Lattner2b83af22005-08-07 07:03:10 +00003621 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3622 return ReplaceInstUsesWith(I, AndRHS);
3623 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003624 }
Chris Lattner2b83af22005-08-07 07:03:10 +00003625 }
Chris Lattner06782f82003-07-23 19:36:21 +00003626 }
Chris Lattner2eefe512004-04-09 19:05:30 +00003627
3628 // Try to fold constant and into select arguments.
3629 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003630 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00003631 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00003632 if (isa<PHINode>(Op0))
3633 if (Instruction *NV = FoldOpIntoPhi(I))
3634 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00003635 }
3636
Chris Lattner8d969642003-03-10 23:06:50 +00003637 Value *Op0NotVal = dyn_castNotVal(Op0);
3638 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00003639
Chris Lattner5b62aa72004-06-18 06:07:51 +00003640 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3641 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3642
Misha Brukmancb6267b2004-07-30 12:50:08 +00003643 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00003644 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattner48595f12004-06-10 02:07:29 +00003645 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
3646 I.getName()+".demorgan");
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00003647 InsertNewInstBefore(Or, I);
Chris Lattnera2881962003-02-18 19:28:33 +00003648 return BinaryOperator::createNot(Or);
3649 }
Chris Lattner2082ad92006-02-13 23:07:23 +00003650
3651 {
Chris Lattner003b6202007-06-15 05:58:24 +00003652 Value *A = 0, *B = 0, *C = 0, *D = 0;
3653 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00003654 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3655 return ReplaceInstUsesWith(I, Op1);
Chris Lattner003b6202007-06-15 05:58:24 +00003656
3657 // (A|B) & ~(A&B) -> A^B
3658 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
3659 if ((A == C && B == D) || (A == D && B == C))
3660 return BinaryOperator::createXor(A, B);
3661 }
3662 }
3663
3664 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00003665 if (A == Op0 || B == Op0) // A & (A | ?) --> A
3666 return ReplaceInstUsesWith(I, Op0);
Chris Lattner003b6202007-06-15 05:58:24 +00003667
3668 // ~(A&B) & (A|B) -> A^B
3669 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
3670 if ((A == C && B == D) || (A == D && B == C))
3671 return BinaryOperator::createXor(A, B);
3672 }
3673 }
Chris Lattner64daab52006-04-01 08:03:55 +00003674
3675 if (Op0->hasOneUse() &&
3676 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3677 if (A == Op1) { // (A^B)&A -> A&(A^B)
3678 I.swapOperands(); // Simplify below
3679 std::swap(Op0, Op1);
3680 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
3681 cast<BinaryOperator>(Op0)->swapOperands();
3682 I.swapOperands(); // Simplify below
3683 std::swap(Op0, Op1);
3684 }
3685 }
3686 if (Op1->hasOneUse() &&
3687 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3688 if (B == Op0) { // B&(A^B) -> B&(B^A)
3689 cast<BinaryOperator>(Op1)->swapOperands();
3690 std::swap(A, B);
3691 }
3692 if (A == Op0) { // A&(A^B) -> A & ~B
3693 Instruction *NotB = BinaryOperator::createNot(B, "tmp");
3694 InsertNewInstBefore(NotB, I);
3695 return BinaryOperator::createAnd(A, NotB);
3696 }
3697 }
Chris Lattner2082ad92006-02-13 23:07:23 +00003698 }
3699
Reid Spencere4d87aa2006-12-23 06:05:41 +00003700 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3701 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3702 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003703 return R;
3704
Chris Lattner955f3312004-09-28 21:48:02 +00003705 Value *LHSVal, *RHSVal;
3706 ConstantInt *LHSCst, *RHSCst;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003707 ICmpInst::Predicate LHSCC, RHSCC;
3708 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3709 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3710 if (LHSVal == RHSVal && // Found (X icmp C1) & (X icmp C2)
3711 // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3712 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3713 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3714 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
Chris Lattnereec8b9a2007-11-22 23:47:13 +00003715 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
3716
3717 // Don't try to fold ICMP_SLT + ICMP_ULT.
3718 (ICmpInst::isEquality(LHSCC) || ICmpInst::isEquality(RHSCC) ||
3719 ICmpInst::isSignedPredicate(LHSCC) ==
3720 ICmpInst::isSignedPredicate(RHSCC))) {
Chris Lattner955f3312004-09-28 21:48:02 +00003721 // Ensure that the larger constant is on the RHS.
Chris Lattneree2b7a42008-01-13 20:59:02 +00003722 ICmpInst::Predicate GT;
3723 if (ICmpInst::isSignedPredicate(LHSCC) ||
3724 (ICmpInst::isEquality(LHSCC) &&
3725 ICmpInst::isSignedPredicate(RHSCC)))
3726 GT = ICmpInst::ICMP_SGT;
3727 else
3728 GT = ICmpInst::ICMP_UGT;
3729
Reid Spencere4d87aa2006-12-23 06:05:41 +00003730 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3731 ICmpInst *LHS = cast<ICmpInst>(Op0);
Reid Spencer579dca12007-01-12 04:24:46 +00003732 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
Chris Lattner955f3312004-09-28 21:48:02 +00003733 std::swap(LHS, RHS);
3734 std::swap(LHSCst, RHSCst);
3735 std::swap(LHSCC, RHSCC);
3736 }
3737
Reid Spencere4d87aa2006-12-23 06:05:41 +00003738 // At this point, we know we have have two icmp instructions
Chris Lattner955f3312004-09-28 21:48:02 +00003739 // comparing a value against two constants and and'ing the result
3740 // together. Because of the above check, we know that we only have
Reid Spencere4d87aa2006-12-23 06:05:41 +00003741 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3742 // (from the FoldICmpLogical check above), that the two constants
3743 // are not equal and that the larger constant is on the RHS
Chris Lattner955f3312004-09-28 21:48:02 +00003744 assert(LHSCst != RHSCst && "Compares not folded above?");
3745
3746 switch (LHSCC) {
3747 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003748 case ICmpInst::ICMP_EQ:
Chris Lattner955f3312004-09-28 21:48:02 +00003749 switch (RHSCC) {
3750 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003751 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3752 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3753 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003754 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00003755 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3756 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3757 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
Chris Lattner955f3312004-09-28 21:48:02 +00003758 return ReplaceInstUsesWith(I, LHS);
3759 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003760 case ICmpInst::ICMP_NE:
Chris Lattner955f3312004-09-28 21:48:02 +00003761 switch (RHSCC) {
3762 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003763 case ICmpInst::ICMP_ULT:
3764 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3765 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
3766 break; // (X != 13 & X u< 15) -> no change
3767 case ICmpInst::ICMP_SLT:
3768 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3769 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
3770 break; // (X != 13 & X s< 15) -> no change
3771 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3772 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3773 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
Chris Lattner955f3312004-09-28 21:48:02 +00003774 return ReplaceInstUsesWith(I, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003775 case ICmpInst::ICMP_NE:
3776 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Chris Lattner955f3312004-09-28 21:48:02 +00003777 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3778 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3779 LHSVal->getName()+".off");
3780 InsertNewInstBefore(Add, I);
Chris Lattner424db022007-01-27 23:08:34 +00003781 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3782 ConstantInt::get(Add->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +00003783 }
3784 break; // (X != 13 & X != 15) -> no change
3785 }
3786 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003787 case ICmpInst::ICMP_ULT:
Chris Lattner955f3312004-09-28 21:48:02 +00003788 switch (RHSCC) {
3789 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003790 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3791 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003792 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00003793 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3794 break;
3795 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3796 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
Chris Lattner955f3312004-09-28 21:48:02 +00003797 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003798 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3799 break;
Chris Lattner955f3312004-09-28 21:48:02 +00003800 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003801 break;
3802 case ICmpInst::ICMP_SLT:
Chris Lattner955f3312004-09-28 21:48:02 +00003803 switch (RHSCC) {
3804 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003805 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3806 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003807 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00003808 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3809 break;
3810 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3811 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
Chris Lattner955f3312004-09-28 21:48:02 +00003812 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003813 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3814 break;
Chris Lattner955f3312004-09-28 21:48:02 +00003815 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003816 break;
3817 case ICmpInst::ICMP_UGT:
3818 switch (RHSCC) {
3819 default: assert(0 && "Unknown integer condition code!");
3820 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X > 13
3821 return ReplaceInstUsesWith(I, LHS);
3822 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3823 return ReplaceInstUsesWith(I, RHS);
3824 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3825 break;
3826 case ICmpInst::ICMP_NE:
3827 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3828 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3829 break; // (X u> 13 & X != 15) -> no change
3830 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) ->(X-14) <u 1
3831 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false,
3832 true, I);
3833 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3834 break;
3835 }
3836 break;
3837 case ICmpInst::ICMP_SGT:
3838 switch (RHSCC) {
3839 default: assert(0 && "Unknown integer condition code!");
Chris Lattnera7d1ab02007-11-16 06:04:17 +00003840 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
Reid Spencere4d87aa2006-12-23 06:05:41 +00003841 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3842 return ReplaceInstUsesWith(I, RHS);
3843 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3844 break;
3845 case ICmpInst::ICMP_NE:
3846 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3847 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3848 break; // (X s> 13 & X != 15) -> no change
3849 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) ->(X-14) s< 1
3850 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true,
3851 true, I);
3852 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3853 break;
3854 }
3855 break;
Chris Lattner955f3312004-09-28 21:48:02 +00003856 }
3857 }
3858 }
3859
Chris Lattner6fc205f2006-05-05 06:39:07 +00003860 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003861 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3862 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3863 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3864 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00003865 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003866 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003867 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
3868 I.getType(), TD) &&
3869 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
3870 I.getType(), TD)) {
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003871 Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
3872 Op1C->getOperand(0),
3873 I.getName());
3874 InsertNewInstBefore(NewOp, I);
3875 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3876 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00003877 }
Chris Lattnere511b742006-11-14 07:46:50 +00003878
3879 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00003880 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3881 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3882 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00003883 SI0->getOperand(1) == SI1->getOperand(1) &&
3884 (SI0->hasOneUse() || SI1->hasOneUse())) {
3885 Instruction *NewOp =
3886 InsertNewInstBefore(BinaryOperator::createAnd(SI0->getOperand(0),
3887 SI1->getOperand(0),
3888 SI0->getName()), I);
Reid Spencer832254e2007-02-02 02:16:23 +00003889 return BinaryOperator::create(SI1->getOpcode(), NewOp,
3890 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00003891 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00003892 }
3893
Chris Lattner99c65742007-10-24 05:38:08 +00003894 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
3895 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
3896 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
3897 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
3898 RHS->getPredicate() == FCmpInst::FCMP_ORD)
3899 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3900 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3901 // If either of the constants are nans, then the whole thing returns
3902 // false.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00003903 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner99c65742007-10-24 05:38:08 +00003904 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3905 return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
3906 RHS->getOperand(0));
3907 }
3908 }
3909 }
3910
Chris Lattner7e708292002-06-25 16:13:24 +00003911 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00003912}
3913
Chris Lattnerafe91a52006-06-15 19:07:26 +00003914/// CollectBSwapParts - Look to see if the specified value defines a single byte
3915/// in the result. If it does, and if the specified byte hasn't been filled in
3916/// yet, fill it in and return false.
Chris Lattner535014f2007-02-15 22:52:10 +00003917static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00003918 Instruction *I = dyn_cast<Instruction>(V);
3919 if (I == 0) return true;
3920
3921 // If this is an or instruction, it is an inner node of the bswap.
3922 if (I->getOpcode() == Instruction::Or)
3923 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3924 CollectBSwapParts(I->getOperand(1), ByteValues);
3925
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003926 uint32_t BitWidth = I->getType()->getPrimitiveSizeInBits();
Chris Lattnerafe91a52006-06-15 19:07:26 +00003927 // If this is a shift by a constant int, and it is "24", then its operand
3928 // defines a byte. We only handle unsigned types here.
Reid Spencer832254e2007-02-02 02:16:23 +00003929 if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00003930 // Not shifting the entire input by N-1 bytes?
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003931 if (cast<ConstantInt>(I->getOperand(1))->getLimitedValue(BitWidth) !=
Chris Lattnerafe91a52006-06-15 19:07:26 +00003932 8*(ByteValues.size()-1))
3933 return true;
3934
3935 unsigned DestNo;
3936 if (I->getOpcode() == Instruction::Shl) {
3937 // X << 24 defines the top byte with the lowest of the input bytes.
3938 DestNo = ByteValues.size()-1;
3939 } else {
3940 // X >>u 24 defines the low byte with the highest of the input bytes.
3941 DestNo = 0;
3942 }
3943
3944 // If the destination byte value is already defined, the values are or'd
3945 // together, which isn't a bswap (unless it's an or of the same bits).
3946 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3947 return true;
3948 ByteValues[DestNo] = I->getOperand(0);
3949 return false;
3950 }
3951
3952 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
3953 // don't have this.
3954 Value *Shift = 0, *ShiftLHS = 0;
3955 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3956 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3957 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3958 return true;
3959 Instruction *SI = cast<Instruction>(Shift);
3960
3961 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003962 if (ShiftAmt->getLimitedValue(BitWidth) & 7 ||
3963 ShiftAmt->getLimitedValue(BitWidth) > 8*ByteValues.size())
Chris Lattnerafe91a52006-06-15 19:07:26 +00003964 return true;
3965
3966 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3967 unsigned DestByte;
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003968 if (AndAmt->getValue().getActiveBits() > 64)
3969 return true;
3970 uint64_t AndAmtVal = AndAmt->getZExtValue();
Chris Lattnerafe91a52006-06-15 19:07:26 +00003971 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003972 if (AndAmtVal == uint64_t(0xFF) << 8*DestByte)
Chris Lattnerafe91a52006-06-15 19:07:26 +00003973 break;
3974 // Unknown mask for bswap.
3975 if (DestByte == ByteValues.size()) return true;
3976
Reid Spencerb83eb642006-10-20 07:07:24 +00003977 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
Chris Lattnerafe91a52006-06-15 19:07:26 +00003978 unsigned SrcByte;
3979 if (SI->getOpcode() == Instruction::Shl)
3980 SrcByte = DestByte - ShiftBytes;
3981 else
3982 SrcByte = DestByte + ShiftBytes;
3983
3984 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3985 if (SrcByte != ByteValues.size()-DestByte-1)
3986 return true;
3987
3988 // If the destination byte value is already defined, the values are or'd
3989 // together, which isn't a bswap (unless it's an or of the same bits).
3990 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3991 return true;
3992 ByteValues[DestByte] = SI->getOperand(0);
3993 return false;
3994}
3995
3996/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3997/// If so, insert the new bswap intrinsic and return it.
3998Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattner55fc8c42007-04-01 20:57:36 +00003999 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
4000 if (!ITy || ITy->getBitWidth() % 16)
4001 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004002
4003 /// ByteValues - For each byte of the result, we keep track of which value
4004 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00004005 SmallVector<Value*, 8> ByteValues;
Chris Lattner55fc8c42007-04-01 20:57:36 +00004006 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004007
4008 // Try to find all the pieces corresponding to the bswap.
4009 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
4010 CollectBSwapParts(I.getOperand(1), ByteValues))
4011 return 0;
4012
4013 // Check to see if all of the bytes come from the same value.
4014 Value *V = ByteValues[0];
4015 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4016
4017 // Check to make sure that all of the bytes come from the same value.
4018 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4019 if (ByteValues[i] != V)
4020 return 0;
Chandler Carruth69940402007-08-04 01:51:18 +00004021 const Type *Tys[] = { ITy };
Chris Lattnerafe91a52006-06-15 19:07:26 +00004022 Module *M = I.getParent()->getParent()->getParent();
Chandler Carruth69940402007-08-04 01:51:18 +00004023 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004024 return new CallInst(F, V);
4025}
4026
4027
Chris Lattner7e708292002-06-25 16:13:24 +00004028Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004029 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004030 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004031
Chris Lattner42593e62007-03-24 23:56:43 +00004032 if (isa<UndefValue>(Op1)) // X | undef -> -1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004033 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004034
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004035 // or X, X = X
4036 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00004037 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004038
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004039 // See if we can simplify any instructions used by the instruction whose sole
4040 // purpose is to compute bits we don't care about.
Chris Lattner42593e62007-03-24 23:56:43 +00004041 if (!isa<VectorType>(I.getType())) {
4042 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4043 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4044 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4045 KnownZero, KnownOne))
4046 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00004047 } else if (isa<ConstantAggregateZero>(Op1)) {
4048 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4049 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4050 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4051 return ReplaceInstUsesWith(I, I.getOperand(1));
Chris Lattner42593e62007-03-24 23:56:43 +00004052 }
Chris Lattner041a6c92007-06-15 05:26:55 +00004053
4054
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004055
Chris Lattner3f5b8772002-05-06 16:14:14 +00004056 // or X, -1 == -1
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004057 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00004058 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004059 // (X & C1) | C2 --> (X | C2) & (C1|C2)
4060 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattner6934a042007-02-11 01:23:03 +00004061 Instruction *Or = BinaryOperator::createOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004062 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00004063 Or->takeName(Op0);
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004064 return BinaryOperator::createAnd(Or,
4065 ConstantInt::get(RHS->getValue() | C1->getValue()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004066 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004067
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004068 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4069 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattner6934a042007-02-11 01:23:03 +00004070 Instruction *Or = BinaryOperator::createOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004071 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00004072 Or->takeName(Op0);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004073 return BinaryOperator::createXor(Or,
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004074 ConstantInt::get(C1->getValue() & ~RHS->getValue()));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004075 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004076
4077 // Try to fold constant and into select arguments.
4078 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004079 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004080 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004081 if (isa<PHINode>(Op0))
4082 if (Instruction *NV = FoldOpIntoPhi(I))
4083 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004084 }
4085
Chris Lattner4f637d42006-01-06 17:59:59 +00004086 Value *A = 0, *B = 0;
4087 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004088
4089 if (match(Op0, m_And(m_Value(A), m_Value(B))))
4090 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4091 return ReplaceInstUsesWith(I, Op1);
4092 if (match(Op1, m_And(m_Value(A), m_Value(B))))
4093 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4094 return ReplaceInstUsesWith(I, Op0);
4095
Chris Lattner6423d4c2006-07-10 20:25:24 +00004096 // (A | B) | C and A | (B | C) -> bswap if possible.
4097 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004098 if (match(Op0, m_Or(m_Value(), m_Value())) ||
Chris Lattner6423d4c2006-07-10 20:25:24 +00004099 match(Op1, m_Or(m_Value(), m_Value())) ||
4100 (match(Op0, m_Shift(m_Value(), m_Value())) &&
4101 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00004102 if (Instruction *BSwap = MatchBSwap(I))
4103 return BSwap;
4104 }
4105
Chris Lattner6e4c6492005-05-09 04:58:36 +00004106 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4107 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004108 MaskedValueIsZero(Op1, C1->getValue())) {
Chris Lattner6934a042007-02-11 01:23:03 +00004109 Instruction *NOr = BinaryOperator::createOr(A, Op1);
4110 InsertNewInstBefore(NOr, I);
4111 NOr->takeName(Op0);
4112 return BinaryOperator::createXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004113 }
4114
4115 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4116 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004117 MaskedValueIsZero(Op0, C1->getValue())) {
Chris Lattner6934a042007-02-11 01:23:03 +00004118 Instruction *NOr = BinaryOperator::createOr(A, Op0);
4119 InsertNewInstBefore(NOr, I);
4120 NOr->takeName(Op0);
4121 return BinaryOperator::createXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004122 }
4123
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004124 // (A & C)|(B & D)
Chris Lattner2384d7b2007-06-19 05:43:49 +00004125 Value *C = 0, *D = 0;
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004126 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4127 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004128 Value *V1 = 0, *V2 = 0, *V3 = 0;
4129 C1 = dyn_cast<ConstantInt>(C);
4130 C2 = dyn_cast<ConstantInt>(D);
4131 if (C1 && C2) { // (A & C1)|(B & C2)
4132 // If we have: ((V + N) & C1) | (V & C2)
4133 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4134 // replace with V+N.
4135 if (C1->getValue() == ~C2->getValue()) {
4136 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4137 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4138 // Add commutes, try both ways.
4139 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4140 return ReplaceInstUsesWith(I, A);
4141 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4142 return ReplaceInstUsesWith(I, A);
4143 }
4144 // Or commutes, try both ways.
4145 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4146 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4147 // Add commutes, try both ways.
4148 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4149 return ReplaceInstUsesWith(I, B);
4150 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4151 return ReplaceInstUsesWith(I, B);
4152 }
4153 }
Chris Lattner044e5332007-04-08 08:01:49 +00004154 V1 = 0; V2 = 0; V3 = 0;
Chris Lattner6cae0e02007-04-08 07:55:22 +00004155 }
4156
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004157 // Check to see if we have any common things being and'ed. If so, find the
4158 // terms for V1 & (V2|V3).
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004159 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4160 if (A == B) // (A & C)|(A & D) == A & (C|D)
4161 V1 = A, V2 = C, V3 = D;
4162 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4163 V1 = A, V2 = B, V3 = C;
4164 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4165 V1 = C, V2 = A, V3 = D;
4166 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4167 V1 = C, V2 = A, V3 = B;
4168
4169 if (V1) {
4170 Value *Or =
4171 InsertNewInstBefore(BinaryOperator::createOr(V2, V3, "tmp"), I);
4172 return BinaryOperator::createAnd(V1, Or);
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00004173 }
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004174 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004175 }
Chris Lattnere511b742006-11-14 07:46:50 +00004176
4177 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004178 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4179 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4180 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004181 SI0->getOperand(1) == SI1->getOperand(1) &&
4182 (SI0->hasOneUse() || SI1->hasOneUse())) {
4183 Instruction *NewOp =
4184 InsertNewInstBefore(BinaryOperator::createOr(SI0->getOperand(0),
4185 SI1->getOperand(0),
4186 SI0->getName()), I);
Reid Spencer832254e2007-02-02 02:16:23 +00004187 return BinaryOperator::create(SI1->getOpcode(), NewOp,
4188 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004189 }
4190 }
Chris Lattner67ca7682003-08-12 19:11:07 +00004191
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004192 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
4193 if (A == Op1) // ~A | A == -1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004194 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004195 } else {
4196 A = 0;
4197 }
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004198 // Note, A is still live here!
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004199 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
4200 if (Op0 == B)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004201 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera27231a2003-03-10 23:13:59 +00004202
Misha Brukmancb6267b2004-07-30 12:50:08 +00004203 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004204 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4205 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
4206 I.getName()+".demorgan"), I);
4207 return BinaryOperator::createNot(And);
4208 }
Chris Lattnera27231a2003-03-10 23:13:59 +00004209 }
Chris Lattnera2881962003-02-18 19:28:33 +00004210
Reid Spencere4d87aa2006-12-23 06:05:41 +00004211 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4212 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4213 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004214 return R;
4215
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004216 Value *LHSVal, *RHSVal;
4217 ConstantInt *LHSCst, *RHSCst;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004218 ICmpInst::Predicate LHSCC, RHSCC;
4219 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
4220 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
4221 if (LHSVal == RHSVal && // Found (X icmp C1) | (X icmp C2)
4222 // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
4223 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
4224 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
4225 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
Chris Lattner88858872007-05-11 05:55:56 +00004226 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
4227 // We can't fold (ugt x, C) | (sgt x, C2).
4228 PredicatesFoldable(LHSCC, RHSCC)) {
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004229 // Ensure that the larger constant is on the RHS.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004230 ICmpInst *LHS = cast<ICmpInst>(Op0);
Chris Lattner88858872007-05-11 05:55:56 +00004231 bool NeedsSwap;
4232 if (ICmpInst::isSignedPredicate(LHSCC))
Chris Lattner3aea1bd2007-05-11 16:58:45 +00004233 NeedsSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner88858872007-05-11 05:55:56 +00004234 else
Chris Lattner3aea1bd2007-05-11 16:58:45 +00004235 NeedsSwap = LHSCst->getValue().ugt(RHSCst->getValue());
Chris Lattner88858872007-05-11 05:55:56 +00004236
4237 if (NeedsSwap) {
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004238 std::swap(LHS, RHS);
4239 std::swap(LHSCst, RHSCst);
4240 std::swap(LHSCC, RHSCC);
4241 }
4242
Reid Spencere4d87aa2006-12-23 06:05:41 +00004243 // At this point, we know we have have two icmp instructions
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004244 // comparing a value against two constants and or'ing the result
4245 // together. Because of the above check, we know that we only have
Reid Spencere4d87aa2006-12-23 06:05:41 +00004246 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4247 // FoldICmpLogical check above), that the two constants are not
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004248 // equal.
4249 assert(LHSCst != RHSCst && "Compares not folded above?");
4250
4251 switch (LHSCC) {
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 switch (RHSCC) {
4255 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004256 case ICmpInst::ICMP_EQ:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004257 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
4258 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4259 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
4260 LHSVal->getName()+".off");
4261 InsertNewInstBefore(Add, I);
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004262 AddCST = Subtract(AddOne(RHSCst), LHSCst);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004263 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004264 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004265 break; // (X == 13 | X == 15) -> no change
4266 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4267 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
Chris Lattner240d6f42005-04-19 06:04:18 +00004268 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004269 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4270 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4271 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004272 return ReplaceInstUsesWith(I, RHS);
4273 }
4274 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004275 case ICmpInst::ICMP_NE:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004276 switch (RHSCC) {
4277 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004278 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4279 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4280 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004281 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004282 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4283 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4284 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004285 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004286 }
4287 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004288 case ICmpInst::ICMP_ULT:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004289 switch (RHSCC) {
4290 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004291 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004292 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004293 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) ->(X-13) u> 2
Chris Lattner74e012a2007-11-01 02:18:41 +00004294 // If RHSCst is [us]MAXINT, it is always false. Not handling
4295 // this can cause overflow.
4296 if (RHSCst->isMaxValue(false))
4297 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004298 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false,
4299 false, I);
4300 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4301 break;
4302 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4303 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004304 return ReplaceInstUsesWith(I, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004305 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4306 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004307 }
4308 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004309 case ICmpInst::ICMP_SLT:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004310 switch (RHSCC) {
4311 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004312 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4313 break;
4314 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) ->(X-13) s> 2
Chris Lattner74e012a2007-11-01 02:18:41 +00004315 // If RHSCst is [us]MAXINT, it is always false. Not handling
4316 // this can cause overflow.
4317 if (RHSCst->isMaxValue(true))
4318 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004319 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true,
4320 false, I);
4321 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4322 break;
4323 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4324 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4325 return ReplaceInstUsesWith(I, RHS);
4326 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4327 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004328 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004329 break;
4330 case ICmpInst::ICMP_UGT:
4331 switch (RHSCC) {
4332 default: assert(0 && "Unknown integer condition code!");
4333 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4334 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4335 return ReplaceInstUsesWith(I, LHS);
4336 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4337 break;
4338 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4339 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004340 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004341 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4342 break;
4343 }
4344 break;
4345 case ICmpInst::ICMP_SGT:
4346 switch (RHSCC) {
4347 default: assert(0 && "Unknown integer condition code!");
4348 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4349 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4350 return ReplaceInstUsesWith(I, LHS);
4351 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4352 break;
4353 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4354 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004355 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004356 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4357 break;
4358 }
4359 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004360 }
4361 }
4362 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004363
4364 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00004365 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00004366 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004367 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chengb98a10e2008-03-24 00:21:34 +00004368 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4369 !isa<ICmpInst>(Op1C->getOperand(0))) {
4370 const Type *SrcTy = Op0C->getOperand(0)->getType();
4371 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4372 // Only do this if the casts both really cause code to be
4373 // generated.
4374 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4375 I.getType(), TD) &&
4376 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4377 I.getType(), TD)) {
4378 Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
4379 Op1C->getOperand(0),
4380 I.getName());
4381 InsertNewInstBefore(NewOp, I);
4382 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4383 }
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004384 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004385 }
Chris Lattner99c65742007-10-24 05:38:08 +00004386 }
4387
4388
4389 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4390 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4391 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4392 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
Chris Lattner5ebd9362008-02-29 06:09:11 +00004393 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
4394 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType())
Chris Lattner99c65742007-10-24 05:38:08 +00004395 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4396 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4397 // If either of the constants are nans, then the whole thing returns
4398 // true.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00004399 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner99c65742007-10-24 05:38:08 +00004400 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4401
4402 // Otherwise, no need to compare the two constants, compare the
4403 // rest.
4404 return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4405 RHS->getOperand(0));
4406 }
4407 }
4408 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004409
Chris Lattner7e708292002-06-25 16:13:24 +00004410 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004411}
4412
Chris Lattnerc317d392004-02-16 01:20:27 +00004413// XorSelf - Implements: X ^ X --> 0
4414struct XorSelf {
4415 Value *RHS;
4416 XorSelf(Value *rhs) : RHS(rhs) {}
4417 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4418 Instruction *apply(BinaryOperator &Xor) const {
4419 return &Xor;
4420 }
4421};
Chris Lattner3f5b8772002-05-06 16:14:14 +00004422
4423
Chris Lattner7e708292002-06-25 16:13:24 +00004424Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004425 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004426 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004427
Evan Chengd34af782008-03-25 20:07:13 +00004428 if (isa<UndefValue>(Op1)) {
4429 if (isa<UndefValue>(Op0))
4430 // Handle undef ^ undef -> 0 special case. This is a common
4431 // idiom (misuse).
4432 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004433 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chengd34af782008-03-25 20:07:13 +00004434 }
Chris Lattnere87597f2004-10-16 18:11:37 +00004435
Chris Lattnerc317d392004-02-16 01:20:27 +00004436 // xor X, X = 0, even if X is nested in a sequence of Xor's.
4437 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00004438 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Chris Lattner233f7dc2002-08-12 21:17:25 +00004439 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00004440 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004441
4442 // See if we can simplify any instructions used by the instruction whose sole
4443 // purpose is to compute bits we don't care about.
Reid Spencera03d45f2007-03-22 22:19:58 +00004444 if (!isa<VectorType>(I.getType())) {
4445 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4446 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4447 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4448 KnownZero, KnownOne))
4449 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00004450 } else if (isa<ConstantAggregateZero>(Op1)) {
4451 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Reid Spencera03d45f2007-03-22 22:19:58 +00004452 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00004453
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004454 // Is this a ~ operation?
4455 if (Value *NotOp = dyn_castNotVal(&I)) {
4456 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4457 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4458 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4459 if (Op0I->getOpcode() == Instruction::And ||
4460 Op0I->getOpcode() == Instruction::Or) {
4461 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4462 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4463 Instruction *NotY =
4464 BinaryOperator::createNot(Op0I->getOperand(1),
4465 Op0I->getOperand(1)->getName()+".not");
4466 InsertNewInstBefore(NotY, I);
4467 if (Op0I->getOpcode() == Instruction::And)
4468 return BinaryOperator::createOr(Op0NotVal, NotY);
4469 else
4470 return BinaryOperator::createAnd(Op0NotVal, NotY);
4471 }
4472 }
4473 }
4474 }
4475
4476
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004477 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00004478 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
4479 if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
4480 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00004481 return new ICmpInst(ICI->getInversePredicate(),
4482 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00004483
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00004484 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
4485 return new FCmpInst(FCI->getInversePredicate(),
4486 FCI->getOperand(0), FCI->getOperand(1));
4487 }
4488
Reid Spencere4d87aa2006-12-23 06:05:41 +00004489 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00004490 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00004491 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4492 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattner48595f12004-06-10 02:07:29 +00004493 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4494 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattner7c4049c2004-01-12 19:35:11 +00004495 ConstantInt::get(I.getType(), 1));
Chris Lattner48595f12004-06-10 02:07:29 +00004496 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00004497 }
Chris Lattner5c6e2db2007-04-02 05:36:22 +00004498
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004499 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004500 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00004501 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00004502 if (RHS->isAllOnesValue()) {
Chris Lattner48595f12004-06-10 02:07:29 +00004503 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
4504 return BinaryOperator::createSub(
4505 ConstantExpr::getSub(NegOp0CI,
Chris Lattner7c4049c2004-01-12 19:35:11 +00004506 ConstantInt::get(I.getType(), 1)),
Chris Lattner689d24b2003-11-04 23:37:10 +00004507 Op0I->getOperand(0));
Chris Lattneracf4e072007-04-02 05:42:22 +00004508 } else if (RHS->getValue().isSignBit()) {
Chris Lattner5c6e2db2007-04-02 05:36:22 +00004509 // (X + C) ^ signbit -> (X + C + signbit)
4510 Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
4511 return BinaryOperator::createAdd(Op0I->getOperand(0), C);
Chris Lattnercd1d6d52007-04-02 05:48:58 +00004512
Chris Lattner7c4049c2004-01-12 19:35:11 +00004513 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00004514 } else if (Op0I->getOpcode() == Instruction::Or) {
4515 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencera03d45f2007-03-22 22:19:58 +00004516 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Chris Lattner02bd1b32006-02-26 19:57:54 +00004517 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4518 // Anything in both C1 and C2 is known to be zero, remove it from
4519 // NewRHS.
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004520 Constant *CommonBits = And(Op0CI, RHS);
Chris Lattner02bd1b32006-02-26 19:57:54 +00004521 NewRHS = ConstantExpr::getAnd(NewRHS,
4522 ConstantExpr::getNot(CommonBits));
Chris Lattnerdbab3862007-03-02 21:28:56 +00004523 AddToWorkList(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00004524 I.setOperand(0, Op0I->getOperand(0));
4525 I.setOperand(1, NewRHS);
4526 return &I;
4527 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00004528 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004529 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00004530 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004531
4532 // Try to fold constant and into select arguments.
4533 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004534 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004535 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004536 if (isa<PHINode>(Op0))
4537 if (Instruction *NV = FoldOpIntoPhi(I))
4538 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004539 }
4540
Chris Lattner8d969642003-03-10 23:06:50 +00004541 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00004542 if (X == Op1)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004543 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00004544
Chris Lattner8d969642003-03-10 23:06:50 +00004545 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00004546 if (X == Op0)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004547 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00004548
Chris Lattner318bf792007-03-18 22:51:34 +00004549
4550 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
4551 if (Op1I) {
4552 Value *A, *B;
4553 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
4554 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00004555 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00004556 I.swapOperands();
4557 std::swap(Op0, Op1);
Chris Lattner318bf792007-03-18 22:51:34 +00004558 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00004559 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00004560 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00004561 }
Chris Lattner318bf792007-03-18 22:51:34 +00004562 } else if (match(Op1I, m_Xor(m_Value(A), m_Value(B)))) {
4563 if (Op0 == A) // A^(A^B) == B
4564 return ReplaceInstUsesWith(I, B);
4565 else if (Op0 == B) // A^(B^A) == B
4566 return ReplaceInstUsesWith(I, A);
4567 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
Chris Lattner6abbdf92007-04-01 05:36:37 +00004568 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattner64daab52006-04-01 08:03:55 +00004569 Op1I->swapOperands();
Chris Lattner6abbdf92007-04-01 05:36:37 +00004570 std::swap(A, B);
4571 }
Chris Lattner318bf792007-03-18 22:51:34 +00004572 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattner64daab52006-04-01 08:03:55 +00004573 I.swapOperands(); // Simplified below.
4574 std::swap(Op0, Op1);
4575 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00004576 }
Chris Lattner318bf792007-03-18 22:51:34 +00004577 }
4578
4579 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
4580 if (Op0I) {
4581 Value *A, *B;
4582 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
4583 if (A == Op1) // (B|A)^B == (A|B)^B
4584 std::swap(A, B);
4585 if (B == Op1) { // (A|B)^B == A & ~B
4586 Instruction *NotB =
4587 InsertNewInstBefore(BinaryOperator::createNot(Op1, "tmp"), I);
4588 return BinaryOperator::createAnd(A, NotB);
Chris Lattnercb40a372003-03-10 18:24:17 +00004589 }
Chris Lattner318bf792007-03-18 22:51:34 +00004590 } else if (match(Op0I, m_Xor(m_Value(A), m_Value(B)))) {
4591 if (Op1 == A) // (A^B)^A == B
4592 return ReplaceInstUsesWith(I, B);
4593 else if (Op1 == B) // (B^A)^A == B
4594 return ReplaceInstUsesWith(I, A);
4595 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
4596 if (A == Op1) // (A&B)^A -> (B&A)^A
4597 std::swap(A, B);
4598 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattnerae1ab392006-04-01 22:05:01 +00004599 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner318bf792007-03-18 22:51:34 +00004600 Instruction *N =
4601 InsertNewInstBefore(BinaryOperator::createNot(A, "tmp"), I);
Chris Lattner64daab52006-04-01 08:03:55 +00004602 return BinaryOperator::createAnd(N, Op1);
4603 }
Chris Lattnercb40a372003-03-10 18:24:17 +00004604 }
Chris Lattner318bf792007-03-18 22:51:34 +00004605 }
4606
4607 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
4608 if (Op0I && Op1I && Op0I->isShift() &&
4609 Op0I->getOpcode() == Op1I->getOpcode() &&
4610 Op0I->getOperand(1) == Op1I->getOperand(1) &&
4611 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
4612 Instruction *NewOp =
4613 InsertNewInstBefore(BinaryOperator::createXor(Op0I->getOperand(0),
4614 Op1I->getOperand(0),
4615 Op0I->getName()), I);
4616 return BinaryOperator::create(Op1I->getOpcode(), NewOp,
4617 Op1I->getOperand(1));
4618 }
4619
4620 if (Op0I && Op1I) {
4621 Value *A, *B, *C, *D;
4622 // (A & B)^(A | B) -> A ^ B
4623 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4624 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
4625 if ((A == C && B == D) || (A == D && B == C))
4626 return BinaryOperator::createXor(A, B);
4627 }
4628 // (A | B)^(A & B) -> A ^ B
4629 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
4630 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4631 if ((A == C && B == D) || (A == D && B == C))
4632 return BinaryOperator::createXor(A, B);
4633 }
4634
4635 // (A & B)^(C & D)
4636 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
4637 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4638 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4639 // (X & Y)^(X & Y) -> (Y^Z) & X
4640 Value *X = 0, *Y = 0, *Z = 0;
4641 if (A == C)
4642 X = A, Y = B, Z = D;
4643 else if (A == D)
4644 X = A, Y = B, Z = C;
4645 else if (B == C)
4646 X = B, Y = A, Z = D;
4647 else if (B == D)
4648 X = B, Y = A, Z = C;
4649
4650 if (X) {
4651 Instruction *NewOp =
4652 InsertNewInstBefore(BinaryOperator::createXor(Y, Z, Op0->getName()), I);
4653 return BinaryOperator::createAnd(NewOp, X);
4654 }
4655 }
4656 }
4657
Reid Spencere4d87aa2006-12-23 06:05:41 +00004658 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4659 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4660 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004661 return R;
4662
Chris Lattner6fc205f2006-05-05 06:39:07 +00004663 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00004664 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00004665 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004666 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4667 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00004668 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004669 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004670 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4671 I.getType(), TD) &&
4672 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4673 I.getType(), TD)) {
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004674 Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
4675 Op1C->getOperand(0),
4676 I.getName());
4677 InsertNewInstBefore(NewOp, I);
4678 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4679 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004680 }
Chris Lattner99c65742007-10-24 05:38:08 +00004681 }
Chris Lattner7e708292002-06-25 16:13:24 +00004682 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004683}
4684
Chris Lattnera96879a2004-09-29 17:40:11 +00004685/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4686/// overflowed for this type.
4687static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
Reid Spencere4e40032007-03-21 23:19:50 +00004688 ConstantInt *In2, bool IsSigned = false) {
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004689 Result = cast<ConstantInt>(Add(In1, In2));
Chris Lattnera96879a2004-09-29 17:40:11 +00004690
Reid Spencere4e40032007-03-21 23:19:50 +00004691 if (IsSigned)
4692 if (In2->getValue().isNegative())
4693 return Result->getValue().sgt(In1->getValue());
4694 else
4695 return Result->getValue().slt(In1->getValue());
4696 else
4697 return Result->getValue().ult(In1->getValue());
Chris Lattnera96879a2004-09-29 17:40:11 +00004698}
4699
Chris Lattner574da9b2005-01-13 20:14:25 +00004700/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4701/// code necessary to compute the offset from the base pointer (without adding
4702/// in the base pointer). Return the result as a signed integer of intptr size.
4703static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4704 TargetData &TD = IC.getTargetData();
4705 gep_type_iterator GTI = gep_type_begin(GEP);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004706 const Type *IntPtrTy = TD.getIntPtrType();
4707 Value *Result = Constant::getNullValue(IntPtrTy);
Chris Lattner574da9b2005-01-13 20:14:25 +00004708
4709 // Build a mask for high order bits.
Chris Lattnere62f0212007-04-28 04:52:43 +00004710 unsigned IntPtrWidth = TD.getPointerSize()*8;
4711 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Chris Lattner574da9b2005-01-13 20:14:25 +00004712
Chris Lattner574da9b2005-01-13 20:14:25 +00004713 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
4714 Value *Op = GEP->getOperand(i);
Duncan Sands514ab342007-11-01 20:53:16 +00004715 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattnere62f0212007-04-28 04:52:43 +00004716 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
4717 if (OpC->isZero()) continue;
4718
4719 // Handle a struct index, which adds its field offset to the pointer.
4720 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4721 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
4722
4723 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
4724 Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
Chris Lattner9bc14642007-04-28 00:57:34 +00004725 else
Chris Lattnere62f0212007-04-28 04:52:43 +00004726 Result = IC.InsertNewInstBefore(
4727 BinaryOperator::createAdd(Result,
4728 ConstantInt::get(IntPtrTy, Size),
4729 GEP->getName()+".offs"), I);
4730 continue;
Chris Lattner9bc14642007-04-28 00:57:34 +00004731 }
Chris Lattnere62f0212007-04-28 04:52:43 +00004732
4733 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4734 Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
4735 Scale = ConstantExpr::getMul(OC, Scale);
4736 if (Constant *RC = dyn_cast<Constant>(Result))
4737 Result = ConstantExpr::getAdd(RC, Scale);
4738 else {
4739 // Emit an add instruction.
4740 Result = IC.InsertNewInstBefore(
4741 BinaryOperator::createAdd(Result, Scale,
4742 GEP->getName()+".offs"), I);
Chris Lattner9bc14642007-04-28 00:57:34 +00004743 }
Chris Lattnere62f0212007-04-28 04:52:43 +00004744 continue;
Chris Lattner574da9b2005-01-13 20:14:25 +00004745 }
Chris Lattnere62f0212007-04-28 04:52:43 +00004746 // Convert to correct type.
4747 if (Op->getType() != IntPtrTy) {
4748 if (Constant *OpC = dyn_cast<Constant>(Op))
4749 Op = ConstantExpr::getSExt(OpC, IntPtrTy);
4750 else
4751 Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
4752 Op->getName()+".c"), I);
4753 }
4754 if (Size != 1) {
4755 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4756 if (Constant *OpC = dyn_cast<Constant>(Op))
4757 Op = ConstantExpr::getMul(OpC, Scale);
4758 else // We'll let instcombine(mul) convert this to a shl if possible.
4759 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
4760 GEP->getName()+".idx"), I);
4761 }
4762
4763 // Emit an add instruction.
4764 if (isa<Constant>(Op) && isa<Constant>(Result))
4765 Result = ConstantExpr::getAdd(cast<Constant>(Op),
4766 cast<Constant>(Result));
4767 else
4768 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
4769 GEP->getName()+".offs"), I);
Chris Lattner574da9b2005-01-13 20:14:25 +00004770 }
4771 return Result;
4772}
4773
Reid Spencere4d87aa2006-12-23 06:05:41 +00004774/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner574da9b2005-01-13 20:14:25 +00004775/// else. At this point we know that the GEP is on the LHS of the comparison.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004776Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
4777 ICmpInst::Predicate Cond,
4778 Instruction &I) {
Chris Lattner574da9b2005-01-13 20:14:25 +00004779 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattnere9d782b2005-01-13 22:25:21 +00004780
4781 if (CastInst *CI = dyn_cast<CastInst>(RHS))
4782 if (isa<PointerType>(CI->getOperand(0)->getType()))
4783 RHS = CI->getOperand(0);
4784
Chris Lattner574da9b2005-01-13 20:14:25 +00004785 Value *PtrBase = GEPLHS->getOperand(0);
4786 if (PtrBase == RHS) {
Chris Lattner7c95deb2008-02-05 04:45:32 +00004787 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
4788 // This transformation is valid because we know pointers can't overflow.
4789 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
4790 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
4791 Constant::getNullValue(Offset->getType()));
Chris Lattner574da9b2005-01-13 20:14:25 +00004792 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00004793 // If the base pointers are different, but the indices are the same, just
4794 // compare the base pointer.
4795 if (PtrBase != GEPRHS->getOperand(0)) {
4796 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00004797 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00004798 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00004799 if (IndicesTheSame)
4800 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4801 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4802 IndicesTheSame = false;
4803 break;
4804 }
4805
4806 // If all indices are the same, just compare the base pointers.
4807 if (IndicesTheSame)
Reid Spencere4d87aa2006-12-23 06:05:41 +00004808 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
4809 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera70b66d2005-04-25 20:17:30 +00004810
4811 // Otherwise, the base pointers are different and the indices are
4812 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00004813 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00004814 }
Chris Lattner574da9b2005-01-13 20:14:25 +00004815
Chris Lattnere9d782b2005-01-13 22:25:21 +00004816 // If one of the GEPs has all zero indices, recurse.
4817 bool AllZeros = true;
4818 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4819 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4820 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4821 AllZeros = false;
4822 break;
4823 }
4824 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00004825 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
4826 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00004827
4828 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00004829 AllZeros = true;
4830 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4831 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4832 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4833 AllZeros = false;
4834 break;
4835 }
4836 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00004837 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattnere9d782b2005-01-13 22:25:21 +00004838
Chris Lattner4401c9c2005-01-14 00:20:05 +00004839 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4840 // If the GEPs only differ by one index, compare it.
4841 unsigned NumDifferences = 0; // Keep track of # differences.
4842 unsigned DiffOperand = 0; // The operand that differs.
4843 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4844 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00004845 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4846 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00004847 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00004848 NumDifferences = 2;
4849 break;
4850 } else {
4851 if (NumDifferences++) break;
4852 DiffOperand = i;
4853 }
4854 }
4855
4856 if (NumDifferences == 0) // SAME GEP?
4857 return ReplaceInstUsesWith(I, // No comparison is needed here.
Nick Lewycky455e1762007-09-06 02:40:25 +00004858 ConstantInt::get(Type::Int1Ty,
4859 isTrueWhenEqual(Cond)));
4860
Chris Lattner4401c9c2005-01-14 00:20:05 +00004861 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00004862 Value *LHSV = GEPLHS->getOperand(DiffOperand);
4863 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004864 // Make sure we do a signed comparison here.
4865 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00004866 }
4867 }
4868
Reid Spencere4d87aa2006-12-23 06:05:41 +00004869 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00004870 // the result to fold to a constant!
4871 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4872 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4873 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
4874 Value *L = EmitGEPOffset(GEPLHS, I, *this);
4875 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004876 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner574da9b2005-01-13 20:14:25 +00004877 }
4878 }
4879 return 0;
4880}
4881
Reid Spencere4d87aa2006-12-23 06:05:41 +00004882Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
4883 bool Changed = SimplifyCompare(I);
Chris Lattner8b170942002-08-09 23:47:40 +00004884 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004885
Chris Lattner58e97462007-01-14 19:42:17 +00004886 // Fold trivial predicates.
4887 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
4888 return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
4889 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
4890 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4891
4892 // Simplify 'fcmp pred X, X'
4893 if (Op0 == Op1) {
4894 switch (I.getPredicate()) {
4895 default: assert(0 && "Unknown predicate!");
4896 case FCmpInst::FCMP_UEQ: // True if unordered or equal
4897 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
4898 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
4899 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4900 case FCmpInst::FCMP_OGT: // True if ordered and greater than
4901 case FCmpInst::FCMP_OLT: // True if ordered and less than
4902 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
4903 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4904
4905 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
4906 case FCmpInst::FCMP_ULT: // True if unordered or less than
4907 case FCmpInst::FCMP_UGT: // True if unordered or greater than
4908 case FCmpInst::FCMP_UNE: // True if unordered or not equal
4909 // Canonicalize these to be 'fcmp uno %X, 0.0'.
4910 I.setPredicate(FCmpInst::FCMP_UNO);
4911 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4912 return &I;
4913
4914 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
4915 case FCmpInst::FCMP_OEQ: // True if ordered and equal
4916 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
4917 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
4918 // Canonicalize these to be 'fcmp ord %X, 0.0'.
4919 I.setPredicate(FCmpInst::FCMP_ORD);
4920 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4921 return &I;
4922 }
4923 }
4924
Reid Spencere4d87aa2006-12-23 06:05:41 +00004925 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Reid Spencer4fe16d62007-01-11 18:21:29 +00004926 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Chris Lattnere87597f2004-10-16 18:11:37 +00004927
Reid Spencere4d87aa2006-12-23 06:05:41 +00004928 // Handle fcmp with constant RHS
4929 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4930 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4931 switch (LHSI->getOpcode()) {
4932 case Instruction::PHI:
4933 if (Instruction *NV = FoldOpIntoPhi(I))
4934 return NV;
4935 break;
4936 case Instruction::Select:
4937 // If either operand of the select is a constant, we can fold the
4938 // comparison into the select arms, which will cause one to be
4939 // constant folded and the select turned into a bitwise or.
4940 Value *Op1 = 0, *Op2 = 0;
4941 if (LHSI->hasOneUse()) {
4942 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4943 // Fold the known value into the constant operand.
4944 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4945 // Insert a new FCmp of the other select operand.
4946 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4947 LHSI->getOperand(2), RHSC,
4948 I.getName()), I);
4949 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4950 // Fold the known value into the constant operand.
4951 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4952 // Insert a new FCmp of the other select operand.
4953 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4954 LHSI->getOperand(1), RHSC,
4955 I.getName()), I);
4956 }
4957 }
4958
4959 if (Op1)
4960 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4961 break;
4962 }
4963 }
4964
4965 return Changed ? &I : 0;
4966}
4967
4968Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
4969 bool Changed = SimplifyCompare(I);
4970 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4971 const Type *Ty = Op0->getType();
4972
4973 // icmp X, X
4974 if (Op0 == Op1)
Reid Spencer579dca12007-01-12 04:24:46 +00004975 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4976 isTrueWhenEqual(I)));
Reid Spencere4d87aa2006-12-23 06:05:41 +00004977
4978 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Reid Spencer4fe16d62007-01-11 18:21:29 +00004979 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Christopher Lamb7a0678c2007-12-18 21:32:20 +00004980
Reid Spencere4d87aa2006-12-23 06:05:41 +00004981 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner711b3402004-11-14 07:33:16 +00004982 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanfd939082005-04-21 23:48:37 +00004983 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
4984 isa<ConstantPointerNull>(Op0)) &&
4985 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner711b3402004-11-14 07:33:16 +00004986 isa<ConstantPointerNull>(Op1)))
Reid Spencer579dca12007-01-12 04:24:46 +00004987 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4988 !isTrueWhenEqual(I)));
Chris Lattner8b170942002-08-09 23:47:40 +00004989
Reid Spencere4d87aa2006-12-23 06:05:41 +00004990 // icmp's with boolean values can always be turned into bitwise operations
Reid Spencer4fe16d62007-01-11 18:21:29 +00004991 if (Ty == Type::Int1Ty) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00004992 switch (I.getPredicate()) {
4993 default: assert(0 && "Invalid icmp instruction!");
4994 case ICmpInst::ICMP_EQ: { // icmp eq bool %A, %B -> ~(A^B)
Chris Lattner48595f12004-06-10 02:07:29 +00004995 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner8b170942002-08-09 23:47:40 +00004996 InsertNewInstBefore(Xor, I);
Chris Lattnerde90b762003-11-03 04:25:02 +00004997 return BinaryOperator::createNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00004998 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004999 case ICmpInst::ICMP_NE: // icmp eq bool %A, %B -> A^B
Chris Lattner5dbef222004-08-11 00:50:51 +00005000 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00005001
Reid Spencere4d87aa2006-12-23 06:05:41 +00005002 case ICmpInst::ICMP_UGT:
5003 case ICmpInst::ICMP_SGT:
5004 std::swap(Op0, Op1); // Change icmp gt -> icmp lt
Chris Lattner5dbef222004-08-11 00:50:51 +00005005 // FALL THROUGH
Reid Spencere4d87aa2006-12-23 06:05:41 +00005006 case ICmpInst::ICMP_ULT:
5007 case ICmpInst::ICMP_SLT: { // icmp lt bool A, B -> ~X & Y
Chris Lattner5dbef222004-08-11 00:50:51 +00005008 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
5009 InsertNewInstBefore(Not, I);
5010 return BinaryOperator::createAnd(Not, Op1);
5011 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00005012 case ICmpInst::ICMP_UGE:
5013 case ICmpInst::ICMP_SGE:
5014 std::swap(Op0, Op1); // Change icmp ge -> icmp le
Chris Lattner5dbef222004-08-11 00:50:51 +00005015 // FALL THROUGH
Reid Spencere4d87aa2006-12-23 06:05:41 +00005016 case ICmpInst::ICMP_ULE:
5017 case ICmpInst::ICMP_SLE: { // icmp le bool %A, %B -> ~A | B
Chris Lattner5dbef222004-08-11 00:50:51 +00005018 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
5019 InsertNewInstBefore(Not, I);
5020 return BinaryOperator::createOr(Not, Op1);
5021 }
5022 }
Chris Lattner8b170942002-08-09 23:47:40 +00005023 }
5024
Chris Lattner2be51ae2004-06-09 04:24:29 +00005025 // See if we are doing a comparison between a constant and an instruction that
5026 // can be folded into the comparison.
Chris Lattner8b170942002-08-09 23:47:40 +00005027 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Christopher Lamb103e1a32007-12-20 07:21:11 +00005028 Value *A, *B;
5029
Chris Lattnerb6566012008-01-05 01:18:20 +00005030 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5031 if (I.isEquality() && CI->isNullValue() &&
5032 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
5033 // (icmp cond A B) if cond is equality
5034 return new ICmpInst(I.getPredicate(), A, B);
Owen Andersonf5783f82007-12-28 07:42:12 +00005035 }
Christopher Lamb103e1a32007-12-20 07:21:11 +00005036
Reid Spencere4d87aa2006-12-23 06:05:41 +00005037 switch (I.getPredicate()) {
5038 default: break;
5039 case ICmpInst::ICMP_ULT: // A <u MIN -> FALSE
5040 if (CI->isMinValue(false))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005041 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005042 if (CI->isMaxValue(false)) // A <u MAX -> A != MAX
5043 return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
5044 if (isMinValuePlusOne(CI,false)) // A <u MIN+1 -> A == MIN
5045 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
Chris Lattnerba417832007-04-11 06:12:58 +00005046 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
5047 if (CI->isMinValue(true))
5048 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
5049 ConstantInt::getAllOnesValue(Op0->getType()));
5050
Reid Spencere4d87aa2006-12-23 06:05:41 +00005051 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005052
Reid Spencere4d87aa2006-12-23 06:05:41 +00005053 case ICmpInst::ICMP_SLT:
5054 if (CI->isMinValue(true)) // A <s MIN -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005055 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005056 if (CI->isMaxValue(true)) // A <s MAX -> A != MAX
5057 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5058 if (isMinValuePlusOne(CI,true)) // A <s MIN+1 -> A == MIN
5059 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5060 break;
5061
5062 case ICmpInst::ICMP_UGT:
5063 if (CI->isMaxValue(false)) // A >u MAX -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005064 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005065 if (CI->isMinValue(false)) // A >u MIN -> A != MIN
5066 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5067 if (isMaxValueMinusOne(CI, false)) // A >u MAX-1 -> A == MAX
5068 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
Chris Lattnerba417832007-04-11 06:12:58 +00005069
5070 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
5071 if (CI->isMaxValue(true))
5072 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
5073 ConstantInt::getNullValue(Op0->getType()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00005074 break;
5075
5076 case ICmpInst::ICMP_SGT:
5077 if (CI->isMaxValue(true)) // A >s MAX -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005078 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005079 if (CI->isMinValue(true)) // A >s MIN -> A != MIN
5080 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5081 if (isMaxValueMinusOne(CI, true)) // A >s MAX-1 -> A == MAX
5082 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5083 break;
5084
5085 case ICmpInst::ICMP_ULE:
5086 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005087 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005088 if (CI->isMinValue(false)) // A <=u MIN -> A == MIN
5089 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5090 if (isMaxValueMinusOne(CI,false)) // A <=u MAX-1 -> A != MAX
5091 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5092 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005093
Reid Spencere4d87aa2006-12-23 06:05:41 +00005094 case ICmpInst::ICMP_SLE:
5095 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005096 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005097 if (CI->isMinValue(true)) // A <=s MIN -> A == MIN
5098 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5099 if (isMaxValueMinusOne(CI,true)) // A <=s MAX-1 -> A != MAX
5100 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5101 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005102
Reid Spencere4d87aa2006-12-23 06:05:41 +00005103 case ICmpInst::ICMP_UGE:
5104 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005105 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005106 if (CI->isMaxValue(false)) // A >=u MAX -> A == MAX
5107 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5108 if (isMinValuePlusOne(CI,false)) // A >=u MIN-1 -> A != MIN
5109 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5110 break;
5111
5112 case ICmpInst::ICMP_SGE:
5113 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005114 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005115 if (CI->isMaxValue(true)) // A >=s MAX -> A == MAX
5116 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5117 if (isMinValuePlusOne(CI,true)) // A >=s MIN-1 -> A != MIN
5118 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5119 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005120 }
5121
Reid Spencere4d87aa2006-12-23 06:05:41 +00005122 // If we still have a icmp le or icmp ge instruction, turn it into the
5123 // appropriate icmp lt or icmp gt instruction. Since the border cases have
Chris Lattnera96879a2004-09-29 17:40:11 +00005124 // already been handled above, this requires little checking.
5125 //
Reid Spencer2149a9d2007-03-25 19:55:33 +00005126 switch (I.getPredicate()) {
Chris Lattner4241e4d2007-07-15 20:54:51 +00005127 default: break;
5128 case ICmpInst::ICMP_ULE:
5129 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5130 case ICmpInst::ICMP_SLE:
5131 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5132 case ICmpInst::ICMP_UGE:
5133 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5134 case ICmpInst::ICMP_SGE:
5135 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
Reid Spencer2149a9d2007-03-25 19:55:33 +00005136 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005137
5138 // See if we can fold the comparison based on bits known to be zero or one
Chris Lattner4241e4d2007-07-15 20:54:51 +00005139 // in the input. If this comparison is a normal comparison, it demands all
5140 // bits, if it is a sign bit comparison, it only demands the sign bit.
5141
5142 bool UnusedBit;
5143 bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5144
Reid Spencer0460fb32007-03-22 20:36:03 +00005145 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
5146 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
Chris Lattner4241e4d2007-07-15 20:54:51 +00005147 if (SimplifyDemandedBits(Op0,
5148 isSignBit ? APInt::getSignBit(BitWidth)
5149 : APInt::getAllOnesValue(BitWidth),
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005150 KnownZero, KnownOne, 0))
5151 return &I;
5152
5153 // Given the known and unknown bits, compute a range that the LHS could be
5154 // in.
Reid Spencer0460fb32007-03-22 20:36:03 +00005155 if ((KnownOne | KnownZero) != 0) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005156 // Compute the Min, Max and RHS values based on the known bits. For the
5157 // EQ and NE we use unsigned values.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00005158 APInt Min(BitWidth, 0), Max(BitWidth, 0);
5159 const APInt& RHSVal = CI->getValue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00005160 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
Reid Spencer0460fb32007-03-22 20:36:03 +00005161 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
5162 Max);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005163 } else {
Reid Spencer0460fb32007-03-22 20:36:03 +00005164 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
5165 Max);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005166 }
5167 switch (I.getPredicate()) { // LE/GE have been folded already.
5168 default: assert(0 && "Unknown icmp opcode!");
5169 case ICmpInst::ICMP_EQ:
Reid Spencer0460fb32007-03-22 20:36:03 +00005170 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005171 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005172 break;
5173 case ICmpInst::ICMP_NE:
Reid Spencer0460fb32007-03-22 20:36:03 +00005174 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005175 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005176 break;
5177 case ICmpInst::ICMP_ULT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005178 if (Max.ult(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005179 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00005180 if (Min.uge(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_UGT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005184 if (Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005185 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00005186 if (Max.ule(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005187 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005188 break;
5189 case ICmpInst::ICMP_SLT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005190 if (Max.slt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005191 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer0460fb32007-03-22 20:36:03 +00005192 if (Min.sgt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005193 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005194 break;
5195 case ICmpInst::ICMP_SGT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005196 if (Min.sgt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005197 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00005198 if (Max.sle(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005199 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005200 break;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005201 }
5202 }
5203
Reid Spencere4d87aa2006-12-23 06:05:41 +00005204 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer1628cec2006-10-26 06:15:43 +00005205 // instruction, see if that instruction also has constants so that the
Reid Spencere4d87aa2006-12-23 06:05:41 +00005206 // instruction can be folded into the icmp
Chris Lattner3c6a0d42004-05-25 06:32:08 +00005207 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner01deb9d2007-04-03 17:43:25 +00005208 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
5209 return Res;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005210 }
5211
Chris Lattner01deb9d2007-04-03 17:43:25 +00005212 // Handle icmp with constant (but not simple integer constant) RHS
Chris Lattner6970b662005-04-23 15:31:55 +00005213 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5214 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5215 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00005216 case Instruction::GetElementPtr:
5217 if (RHSC->isNullValue()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005218 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattner9fb25db2005-05-01 04:42:15 +00005219 bool isAllZeros = true;
5220 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5221 if (!isa<Constant>(LHSI->getOperand(i)) ||
5222 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5223 isAllZeros = false;
5224 break;
5225 }
5226 if (isAllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005227 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Chris Lattner9fb25db2005-05-01 04:42:15 +00005228 Constant::getNullValue(LHSI->getOperand(0)->getType()));
5229 }
5230 break;
5231
Chris Lattner6970b662005-04-23 15:31:55 +00005232 case Instruction::PHI:
5233 if (Instruction *NV = FoldOpIntoPhi(I))
5234 return NV;
5235 break;
Chris Lattner4802d902007-04-06 18:57:34 +00005236 case Instruction::Select: {
Chris Lattner6970b662005-04-23 15:31:55 +00005237 // If either operand of the select is a constant, we can fold the
5238 // comparison into the select arms, which will cause one to be
5239 // constant folded and the select turned into a bitwise or.
5240 Value *Op1 = 0, *Op2 = 0;
5241 if (LHSI->hasOneUse()) {
5242 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5243 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005244 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5245 // Insert a new ICmp of the other select operand.
5246 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5247 LHSI->getOperand(2), RHSC,
5248 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00005249 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5250 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005251 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5252 // Insert a new ICmp of the other select operand.
5253 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5254 LHSI->getOperand(1), RHSC,
5255 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00005256 }
5257 }
Jeff Cohen9d809302005-04-23 21:38:35 +00005258
Chris Lattner6970b662005-04-23 15:31:55 +00005259 if (Op1)
5260 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
5261 break;
5262 }
Chris Lattner4802d902007-04-06 18:57:34 +00005263 case Instruction::Malloc:
5264 // If we have (malloc != null), and if the malloc has a single use, we
5265 // can assume it is successful and remove the malloc.
5266 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
5267 AddToWorkList(LHSI);
5268 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5269 !isTrueWhenEqual(I)));
5270 }
5271 break;
5272 }
Chris Lattner6970b662005-04-23 15:31:55 +00005273 }
5274
Reid Spencere4d87aa2006-12-23 06:05:41 +00005275 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Chris Lattner574da9b2005-01-13 20:14:25 +00005276 if (User *GEP = dyn_castGetElementPtr(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005277 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00005278 return NI;
5279 if (User *GEP = dyn_castGetElementPtr(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005280 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5281 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00005282 return NI;
5283
Reid Spencere4d87aa2006-12-23 06:05:41 +00005284 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner57d86372007-01-06 01:45:59 +00005285 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
5286 // now.
5287 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5288 if (isa<PointerType>(Op0->getType()) &&
5289 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattnerde90b762003-11-03 04:25:02 +00005290 // We keep moving the cast from the left operand over to the right
5291 // operand, where it can often be eliminated completely.
Chris Lattner57d86372007-01-06 01:45:59 +00005292 Op0 = CI->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00005293
Chris Lattner57d86372007-01-06 01:45:59 +00005294 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5295 // so eliminate it as well.
5296 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5297 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00005298
Chris Lattnerde90b762003-11-03 04:25:02 +00005299 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005300 if (Op0->getType() != Op1->getType()) {
Chris Lattnerde90b762003-11-03 04:25:02 +00005301 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Reid Spencerd977d862006-12-12 23:36:14 +00005302 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00005303 } else {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005304 // Otherwise, cast the RHS right before the icmp
Chris Lattner6d0339d2008-01-13 22:23:22 +00005305 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
Chris Lattnerde90b762003-11-03 04:25:02 +00005306 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005307 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00005308 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattnerde90b762003-11-03 04:25:02 +00005309 }
Chris Lattner57d86372007-01-06 01:45:59 +00005310 }
5311
5312 if (isa<CastInst>(Op0)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005313 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner68708052003-11-03 05:17:03 +00005314 // This comes up when you have code like
5315 // int X = A < B;
5316 // if (X) ...
5317 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00005318 // with a constant or another cast from the same type.
5319 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005320 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattner484d3cf2005-04-24 06:59:08 +00005321 return R;
Chris Lattner68708052003-11-03 05:17:03 +00005322 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00005323
Chris Lattner65b72ba2006-09-18 04:22:48 +00005324 if (I.isEquality()) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005325 Value *A, *B, *C, *D;
5326 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
5327 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
5328 Value *OtherVal = A == Op1 ? B : A;
5329 return new ICmpInst(I.getPredicate(), OtherVal,
5330 Constant::getNullValue(A->getType()));
5331 }
5332
5333 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5334 // A^c1 == C^c2 --> A == C^(c1^c2)
5335 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
5336 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
5337 if (Op1->hasOneUse()) {
Zhou Sheng4a1822a2007-04-02 13:45:30 +00005338 Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005339 Instruction *Xor = BinaryOperator::createXor(C, NC, "tmp");
5340 return new ICmpInst(I.getPredicate(), A,
5341 InsertNewInstBefore(Xor, I));
5342 }
5343
5344 // A^B == A^D -> B == D
5345 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
5346 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
5347 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
5348 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
5349 }
5350 }
5351
5352 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5353 (A == Op0 || B == Op0)) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00005354 // A == (A^B) -> B == 0
5355 Value *OtherVal = A == Op0 ? B : A;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005356 return new ICmpInst(I.getPredicate(), OtherVal,
5357 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005358 }
5359 if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00005360 // (A-B) == A -> B == 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00005361 return new ICmpInst(I.getPredicate(), B,
5362 Constant::getNullValue(B->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005363 }
5364 if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00005365 // A == (A-B) -> B == 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00005366 return new ICmpInst(I.getPredicate(), B,
5367 Constant::getNullValue(B->getType()));
Chris Lattner26ab9a92006-02-27 01:44:11 +00005368 }
Chris Lattner9c2328e2006-11-14 06:06:06 +00005369
Chris Lattner9c2328e2006-11-14 06:06:06 +00005370 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5371 if (Op0->hasOneUse() && Op1->hasOneUse() &&
5372 match(Op0, m_And(m_Value(A), m_Value(B))) &&
5373 match(Op1, m_And(m_Value(C), m_Value(D)))) {
5374 Value *X = 0, *Y = 0, *Z = 0;
5375
5376 if (A == C) {
5377 X = B; Y = D; Z = A;
5378 } else if (A == D) {
5379 X = B; Y = C; Z = A;
5380 } else if (B == C) {
5381 X = A; Y = D; Z = B;
5382 } else if (B == D) {
5383 X = A; Y = C; Z = B;
5384 }
5385
5386 if (X) { // Build (X^Y) & Z
5387 Op1 = InsertNewInstBefore(BinaryOperator::createXor(X, Y, "tmp"), I);
5388 Op1 = InsertNewInstBefore(BinaryOperator::createAnd(Op1, Z, "tmp"), I);
5389 I.setOperand(0, Op1);
5390 I.setOperand(1, Constant::getNullValue(Op1->getType()));
5391 return &I;
5392 }
5393 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00005394 }
Chris Lattner7e708292002-06-25 16:13:24 +00005395 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005396}
5397
Chris Lattner562ef782007-06-20 23:46:26 +00005398
5399/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
5400/// and CmpRHS are both known to be integer constants.
5401Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
5402 ConstantInt *DivRHS) {
5403 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
5404 const APInt &CmpRHSV = CmpRHS->getValue();
5405
5406 // FIXME: If the operand types don't match the type of the divide
5407 // then don't attempt this transform. The code below doesn't have the
5408 // logic to deal with a signed divide and an unsigned compare (and
5409 // vice versa). This is because (x /s C1) <s C2 produces different
5410 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
5411 // (x /u C1) <u C2. Simply casting the operands and result won't
5412 // work. :( The if statement below tests that condition and bails
5413 // if it finds it.
5414 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
5415 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
5416 return 0;
5417 if (DivRHS->isZero())
Chris Lattner1dbfd482007-06-21 18:11:19 +00005418 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattner562ef782007-06-20 23:46:26 +00005419
5420 // Compute Prod = CI * DivRHS. We are essentially solving an equation
5421 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
5422 // C2 (CI). By solving for X we can turn this into a range check
5423 // instead of computing a divide.
5424 ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
5425
5426 // Determine if the product overflows by seeing if the product is
5427 // not equal to the divide. Make sure we do the same kind of divide
5428 // as in the LHS instruction that we're folding.
5429 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
5430 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
5431
5432 // Get the ICmp opcode
Chris Lattner1dbfd482007-06-21 18:11:19 +00005433 ICmpInst::Predicate Pred = ICI.getPredicate();
Chris Lattner562ef782007-06-20 23:46:26 +00005434
Chris Lattner1dbfd482007-06-21 18:11:19 +00005435 // Figure out the interval that is being checked. For example, a comparison
5436 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
5437 // Compute this interval based on the constants involved and the signedness of
5438 // the compare/divide. This computes a half-open interval, keeping track of
5439 // whether either value in the interval overflows. After analysis each
5440 // overflow variable is set to 0 if it's corresponding bound variable is valid
5441 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
5442 int LoOverflow = 0, HiOverflow = 0;
5443 ConstantInt *LoBound = 0, *HiBound = 0;
5444
5445
Chris Lattner562ef782007-06-20 23:46:26 +00005446 if (!DivIsSigned) { // udiv
Chris Lattner1dbfd482007-06-21 18:11:19 +00005447 // e.g. X/5 op 3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00005448 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00005449 HiOverflow = LoOverflow = ProdOV;
5450 if (!HiOverflow)
5451 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
Dan Gohman76491272008-02-13 22:09:18 +00005452 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Chris Lattner562ef782007-06-20 23:46:26 +00005453 if (CmpRHSV == 0) { // (X / pos) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00005454 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Chris Lattner562ef782007-06-20 23:46:26 +00005455 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
5456 HiBound = DivRHS;
Dan Gohman76491272008-02-13 22:09:18 +00005457 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00005458 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
5459 HiOverflow = LoOverflow = ProdOV;
5460 if (!HiOverflow)
5461 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
Chris Lattner562ef782007-06-20 23:46:26 +00005462 } else { // (X / pos) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00005463 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Chris Lattner562ef782007-06-20 23:46:26 +00005464 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
5465 LoOverflow = AddWithOverflow(LoBound, Prod,
Chris Lattner1dbfd482007-06-21 18:11:19 +00005466 cast<ConstantInt>(DivRHSH), true) ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005467 HiBound = AddOne(Prod);
Chris Lattner1dbfd482007-06-21 18:11:19 +00005468 HiOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005469 }
Dan Gohman76491272008-02-13 22:09:18 +00005470 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Chris Lattner562ef782007-06-20 23:46:26 +00005471 if (CmpRHSV == 0) { // (X / neg) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00005472 // e.g. X/-5 op 0 --> [-4, 5)
Chris Lattner562ef782007-06-20 23:46:26 +00005473 LoBound = AddOne(DivRHS);
5474 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner1dbfd482007-06-21 18:11:19 +00005475 if (HiBound == DivRHS) { // -INTMIN = INTMIN
5476 HiOverflow = 1; // [INTMIN+1, overflow)
5477 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
5478 }
Dan Gohman76491272008-02-13 22:09:18 +00005479 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00005480 // e.g. X/-5 op 3 --> [-19, -14)
5481 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005482 if (!LoOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00005483 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS), true) ?-1:0;
Chris Lattner562ef782007-06-20 23:46:26 +00005484 HiBound = AddOne(Prod);
5485 } else { // (X / neg) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00005486 // e.g. X/-5 op -3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00005487 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00005488 LoOverflow = HiOverflow = ProdOV ? 1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005489 HiBound = Subtract(Prod, DivRHS);
5490 }
5491
Chris Lattner1dbfd482007-06-21 18:11:19 +00005492 // Dividing by a negative swaps the condition. LT <-> GT
5493 Pred = ICmpInst::getSwappedPredicate(Pred);
Chris Lattner562ef782007-06-20 23:46:26 +00005494 }
5495
5496 Value *X = DivI->getOperand(0);
Chris Lattner1dbfd482007-06-21 18:11:19 +00005497 switch (Pred) {
Chris Lattner562ef782007-06-20 23:46:26 +00005498 default: assert(0 && "Unhandled icmp opcode!");
5499 case ICmpInst::ICMP_EQ:
5500 if (LoOverflow && HiOverflow)
5501 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5502 else if (HiOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00005503 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00005504 ICmpInst::ICMP_UGE, X, LoBound);
5505 else if (LoOverflow)
5506 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
5507 ICmpInst::ICMP_ULT, X, HiBound);
5508 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00005509 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00005510 case ICmpInst::ICMP_NE:
5511 if (LoOverflow && HiOverflow)
5512 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5513 else if (HiOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00005514 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00005515 ICmpInst::ICMP_ULT, X, LoBound);
5516 else if (LoOverflow)
5517 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
5518 ICmpInst::ICMP_UGE, X, HiBound);
5519 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00005520 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00005521 case ICmpInst::ICMP_ULT:
5522 case ICmpInst::ICMP_SLT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00005523 if (LoOverflow == +1) // Low bound is greater than input range.
5524 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5525 if (LoOverflow == -1) // Low bound is less than input range.
Chris Lattner562ef782007-06-20 23:46:26 +00005526 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00005527 return new ICmpInst(Pred, X, LoBound);
Chris Lattner562ef782007-06-20 23:46:26 +00005528 case ICmpInst::ICMP_UGT:
5529 case ICmpInst::ICMP_SGT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00005530 if (HiOverflow == +1) // High bound greater than input range.
Chris Lattner562ef782007-06-20 23:46:26 +00005531 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00005532 else if (HiOverflow == -1) // High bound less than input range.
5533 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5534 if (Pred == ICmpInst::ICMP_UGT)
Chris Lattner562ef782007-06-20 23:46:26 +00005535 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
5536 else
5537 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
5538 }
5539}
5540
5541
Chris Lattner01deb9d2007-04-03 17:43:25 +00005542/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
5543///
5544Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
5545 Instruction *LHSI,
5546 ConstantInt *RHS) {
5547 const APInt &RHSV = RHS->getValue();
5548
5549 switch (LHSI->getOpcode()) {
Duncan Sands0091bf22007-04-04 06:42:45 +00005550 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
Chris Lattner01deb9d2007-04-03 17:43:25 +00005551 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
5552 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
5553 // fold the xor.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005554 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
5555 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00005556 Value *CompareVal = LHSI->getOperand(0);
5557
5558 // If the sign bit of the XorCST is not set, there is no change to
5559 // the operation, just stop using the Xor.
5560 if (!XorCST->getValue().isNegative()) {
5561 ICI.setOperand(0, CompareVal);
5562 AddToWorkList(LHSI);
5563 return &ICI;
5564 }
5565
5566 // Was the old condition true if the operand is positive?
5567 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
5568
5569 // If so, the new one isn't.
5570 isTrueIfPositive ^= true;
5571
5572 if (isTrueIfPositive)
5573 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
5574 else
5575 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
5576 }
5577 }
5578 break;
5579 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
5580 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
5581 LHSI->getOperand(0)->hasOneUse()) {
5582 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
5583
5584 // If the LHS is an AND of a truncating cast, we can widen the
5585 // and/compare to be the input width without changing the value
5586 // produced, eliminating a cast.
5587 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
5588 // We can do this transformation if either the AND constant does not
5589 // have its sign bit set or if it is an equality comparison.
5590 // Extending a relational comparison when we're checking the sign
5591 // bit would not work.
5592 if (Cast->hasOneUse() &&
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00005593 (ICI.isEquality() ||
5594 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00005595 uint32_t BitWidth =
5596 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
5597 APInt NewCST = AndCST->getValue();
5598 NewCST.zext(BitWidth);
5599 APInt NewCI = RHSV;
5600 NewCI.zext(BitWidth);
5601 Instruction *NewAnd =
5602 BinaryOperator::createAnd(Cast->getOperand(0),
5603 ConstantInt::get(NewCST),LHSI->getName());
5604 InsertNewInstBefore(NewAnd, ICI);
5605 return new ICmpInst(ICI.getPredicate(), NewAnd,
5606 ConstantInt::get(NewCI));
5607 }
5608 }
5609
5610 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
5611 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
5612 // happens a LOT in code produced by the C front-end, for bitfield
5613 // access.
5614 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
5615 if (Shift && !Shift->isShift())
5616 Shift = 0;
5617
5618 ConstantInt *ShAmt;
5619 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
5620 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
5621 const Type *AndTy = AndCST->getType(); // Type of the and.
5622
5623 // We can fold this as long as we can't shift unknown bits
5624 // into the mask. This can only happen with signed shift
5625 // rights, as they sign-extend.
5626 if (ShAmt) {
5627 bool CanFold = Shift->isLogicalShift();
5628 if (!CanFold) {
5629 // To test for the bad case of the signed shr, see if any
5630 // of the bits shifted in could be tested after the mask.
5631 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
5632 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
5633
5634 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
5635 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
5636 AndCST->getValue()) == 0)
5637 CanFold = true;
5638 }
5639
5640 if (CanFold) {
5641 Constant *NewCst;
5642 if (Shift->getOpcode() == Instruction::Shl)
5643 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
5644 else
5645 NewCst = ConstantExpr::getShl(RHS, ShAmt);
5646
5647 // Check to see if we are shifting out any of the bits being
5648 // compared.
5649 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
5650 // If we shifted bits out, the fold is not going to work out.
5651 // As a special case, check to see if this means that the
5652 // result is always true or false now.
5653 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
5654 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5655 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
5656 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5657 } else {
5658 ICI.setOperand(1, NewCst);
5659 Constant *NewAndCST;
5660 if (Shift->getOpcode() == Instruction::Shl)
5661 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
5662 else
5663 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
5664 LHSI->setOperand(1, NewAndCST);
5665 LHSI->setOperand(0, Shift->getOperand(0));
5666 AddToWorkList(Shift); // Shift is dead.
5667 AddUsesToWorkList(ICI);
5668 return &ICI;
5669 }
5670 }
5671 }
5672
5673 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
5674 // preferable because it allows the C<<Y expression to be hoisted out
5675 // of a loop if Y is invariant and X is not.
5676 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
5677 ICI.isEquality() && !Shift->isArithmeticShift() &&
5678 isa<Instruction>(Shift->getOperand(0))) {
5679 // Compute C << Y.
5680 Value *NS;
5681 if (Shift->getOpcode() == Instruction::LShr) {
5682 NS = BinaryOperator::createShl(AndCST,
5683 Shift->getOperand(1), "tmp");
5684 } else {
5685 // Insert a logical shift.
5686 NS = BinaryOperator::createLShr(AndCST,
5687 Shift->getOperand(1), "tmp");
5688 }
5689 InsertNewInstBefore(cast<Instruction>(NS), ICI);
5690
5691 // Compute X & (C << Y).
5692 Instruction *NewAnd =
5693 BinaryOperator::createAnd(Shift->getOperand(0), NS, LHSI->getName());
5694 InsertNewInstBefore(NewAnd, ICI);
5695
5696 ICI.setOperand(0, NewAnd);
5697 return &ICI;
5698 }
5699 }
5700 break;
5701
Chris Lattnera0141b92007-07-15 20:42:37 +00005702 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
5703 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5704 if (!ShAmt) break;
5705
5706 uint32_t TypeBits = RHSV.getBitWidth();
5707
5708 // Check that the shift amount is in range. If not, don't perform
5709 // undefined shifts. When the shift is visited it will be
5710 // simplified.
5711 if (ShAmt->uge(TypeBits))
5712 break;
5713
5714 if (ICI.isEquality()) {
5715 // If we are comparing against bits always shifted out, the
5716 // comparison cannot succeed.
5717 Constant *Comp =
5718 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
5719 if (Comp != RHS) {// Comparing against a bit that we know is zero.
5720 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5721 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5722 return ReplaceInstUsesWith(ICI, Cst);
5723 }
5724
5725 if (LHSI->hasOneUse()) {
5726 // Otherwise strength reduce the shift into an and.
5727 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
5728 Constant *Mask =
5729 ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
Chris Lattner01deb9d2007-04-03 17:43:25 +00005730
Chris Lattnera0141b92007-07-15 20:42:37 +00005731 Instruction *AndI =
5732 BinaryOperator::createAnd(LHSI->getOperand(0),
5733 Mask, LHSI->getName()+".mask");
5734 Value *And = InsertNewInstBefore(AndI, ICI);
5735 return new ICmpInst(ICI.getPredicate(), And,
5736 ConstantInt::get(RHSV.lshr(ShAmtVal)));
Chris Lattner01deb9d2007-04-03 17:43:25 +00005737 }
5738 }
Chris Lattnera0141b92007-07-15 20:42:37 +00005739
5740 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
5741 bool TrueIfSigned = false;
5742 if (LHSI->hasOneUse() &&
5743 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
5744 // (X << 31) <s 0 --> (X&1) != 0
5745 Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
5746 (TypeBits-ShAmt->getZExtValue()-1));
5747 Instruction *AndI =
5748 BinaryOperator::createAnd(LHSI->getOperand(0),
5749 Mask, LHSI->getName()+".mask");
5750 Value *And = InsertNewInstBefore(AndI, ICI);
5751
5752 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
5753 And, Constant::getNullValue(And->getType()));
5754 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00005755 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00005756 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00005757
5758 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Chris Lattnera0141b92007-07-15 20:42:37 +00005759 case Instruction::AShr: {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00005760 // Only handle equality comparisons of shift-by-constant.
Chris Lattnera0141b92007-07-15 20:42:37 +00005761 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00005762 if (!ShAmt || !ICI.isEquality()) break;
Chris Lattnera0141b92007-07-15 20:42:37 +00005763
Chris Lattner41dc0fc2008-03-21 05:19:58 +00005764 // Check that the shift amount is in range. If not, don't perform
5765 // undefined shifts. When the shift is visited it will be
5766 // simplified.
5767 uint32_t TypeBits = RHSV.getBitWidth();
5768 if (ShAmt->uge(TypeBits))
5769 break;
5770
5771 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattnera0141b92007-07-15 20:42:37 +00005772
Chris Lattner41dc0fc2008-03-21 05:19:58 +00005773 // If we are comparing against bits always shifted out, the
5774 // comparison cannot succeed.
5775 APInt Comp = RHSV << ShAmtVal;
5776 if (LHSI->getOpcode() == Instruction::LShr)
5777 Comp = Comp.lshr(ShAmtVal);
5778 else
5779 Comp = Comp.ashr(ShAmtVal);
5780
5781 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
5782 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5783 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5784 return ReplaceInstUsesWith(ICI, Cst);
5785 }
5786
5787 // Otherwise, check to see if the bits shifted out are known to be zero.
5788 // If so, we can compare against the unshifted value:
5789 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
5790 if (MaskedValueIsZero(LHSI->getOperand(0),
5791 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
5792 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
5793 ConstantExpr::getShl(RHS, ShAmt));
5794 }
Chris Lattnera0141b92007-07-15 20:42:37 +00005795
Chris Lattner41dc0fc2008-03-21 05:19:58 +00005796 if (LHSI->hasOneUse() || RHSV == 0) {
5797 // Otherwise strength reduce the shift into an and.
5798 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
5799 Constant *Mask = ConstantInt::get(Val);
Chris Lattnera0141b92007-07-15 20:42:37 +00005800
Chris Lattner41dc0fc2008-03-21 05:19:58 +00005801 Instruction *AndI =
5802 BinaryOperator::createAnd(LHSI->getOperand(0),
5803 Mask, LHSI->getName()+".mask");
5804 Value *And = InsertNewInstBefore(AndI, ICI);
5805 return new ICmpInst(ICI.getPredicate(), And,
5806 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner01deb9d2007-04-03 17:43:25 +00005807 }
5808 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00005809 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00005810
5811 case Instruction::SDiv:
5812 case Instruction::UDiv:
5813 // Fold: icmp pred ([us]div X, C1), C2 -> range test
5814 // Fold this div into the comparison, producing a range check.
5815 // Determine, based on the divide type, what the range is being
5816 // checked. If there is an overflow on the low or high side, remember
5817 // it, otherwise compute the range [low, hi) bounding the new value.
5818 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner562ef782007-06-20 23:46:26 +00005819 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
5820 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
5821 DivRHS))
5822 return R;
Chris Lattner01deb9d2007-04-03 17:43:25 +00005823 break;
Nick Lewycky5be29202008-02-03 16:33:09 +00005824
5825 case Instruction::Add:
5826 // Fold: icmp pred (add, X, C1), C2
5827
5828 if (!ICI.isEquality()) {
5829 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5830 if (!LHSC) break;
5831 const APInt &LHSV = LHSC->getValue();
5832
5833 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
5834 .subtract(LHSV);
5835
5836 if (ICI.isSignedPredicate()) {
5837 if (CR.getLower().isSignBit()) {
5838 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
5839 ConstantInt::get(CR.getUpper()));
5840 } else if (CR.getUpper().isSignBit()) {
5841 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
5842 ConstantInt::get(CR.getLower()));
5843 }
5844 } else {
5845 if (CR.getLower().isMinValue()) {
5846 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
5847 ConstantInt::get(CR.getUpper()));
5848 } else if (CR.getUpper().isMinValue()) {
5849 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
5850 ConstantInt::get(CR.getLower()));
5851 }
5852 }
5853 }
5854 break;
Chris Lattner01deb9d2007-04-03 17:43:25 +00005855 }
5856
5857 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
5858 if (ICI.isEquality()) {
5859 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5860
5861 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
5862 // the second operand is a constant, simplify a bit.
5863 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
5864 switch (BO->getOpcode()) {
5865 case Instruction::SRem:
5866 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
5867 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
5868 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
5869 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
5870 Instruction *NewRem =
5871 BinaryOperator::createURem(BO->getOperand(0), BO->getOperand(1),
5872 BO->getName());
5873 InsertNewInstBefore(NewRem, ICI);
5874 return new ICmpInst(ICI.getPredicate(), NewRem,
5875 Constant::getNullValue(BO->getType()));
5876 }
5877 }
5878 break;
5879 case Instruction::Add:
5880 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
5881 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
5882 if (BO->hasOneUse())
5883 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
5884 Subtract(RHS, BOp1C));
5885 } else if (RHSV == 0) {
5886 // Replace ((add A, B) != 0) with (A != -B) if A or B is
5887 // efficiently invertible, or if the add has just this one use.
5888 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
5889
5890 if (Value *NegVal = dyn_castNegVal(BOp1))
5891 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
5892 else if (Value *NegVal = dyn_castNegVal(BOp0))
5893 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
5894 else if (BO->hasOneUse()) {
5895 Instruction *Neg = BinaryOperator::createNeg(BOp1);
5896 InsertNewInstBefore(Neg, ICI);
5897 Neg->takeName(BO);
5898 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
5899 }
5900 }
5901 break;
5902 case Instruction::Xor:
5903 // For the xor case, we can xor two constants together, eliminating
5904 // the explicit xor.
5905 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
5906 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
5907 ConstantExpr::getXor(RHS, BOC));
5908
5909 // FALLTHROUGH
5910 case Instruction::Sub:
5911 // Replace (([sub|xor] A, B) != 0) with (A != B)
5912 if (RHSV == 0)
5913 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
5914 BO->getOperand(1));
5915 break;
5916
5917 case Instruction::Or:
5918 // If bits are being or'd in that are not present in the constant we
5919 // are comparing against, then the comparison could never succeed!
5920 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
5921 Constant *NotCI = ConstantExpr::getNot(RHS);
5922 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
5923 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
5924 isICMP_NE));
5925 }
5926 break;
5927
5928 case Instruction::And:
5929 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
5930 // If bits are being compared against that are and'd out, then the
5931 // comparison can never succeed!
5932 if ((RHSV & ~BOC->getValue()) != 0)
5933 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
5934 isICMP_NE));
5935
5936 // If we have ((X & C) == C), turn it into ((X & C) != 0).
5937 if (RHS == BOC && RHSV.isPowerOf2())
5938 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
5939 ICmpInst::ICMP_NE, LHSI,
5940 Constant::getNullValue(RHS->getType()));
5941
5942 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
5943 if (isSignBit(BOC)) {
5944 Value *X = BO->getOperand(0);
5945 Constant *Zero = Constant::getNullValue(X->getType());
5946 ICmpInst::Predicate pred = isICMP_NE ?
5947 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
5948 return new ICmpInst(pred, X, Zero);
5949 }
5950
5951 // ((X & ~7) == 0) --> X < 8
5952 if (RHSV == 0 && isHighOnes(BOC)) {
5953 Value *X = BO->getOperand(0);
5954 Constant *NegX = ConstantExpr::getNeg(BOC);
5955 ICmpInst::Predicate pred = isICMP_NE ?
5956 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
5957 return new ICmpInst(pred, X, NegX);
5958 }
5959 }
5960 default: break;
5961 }
5962 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
5963 // Handle icmp {eq|ne} <intrinsic>, intcst.
5964 if (II->getIntrinsicID() == Intrinsic::bswap) {
5965 AddToWorkList(II);
5966 ICI.setOperand(0, II->getOperand(1));
5967 ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
5968 return &ICI;
5969 }
5970 }
5971 } else { // Not a ICMP_EQ/ICMP_NE
Chris Lattnere34e9a22007-04-14 23:32:02 +00005972 // If the LHS is a cast from an integral value of the same size,
5973 // then since we know the RHS is a constant, try to simlify.
Chris Lattner01deb9d2007-04-03 17:43:25 +00005974 if (CastInst *Cast = dyn_cast<CastInst>(LHSI)) {
5975 Value *CastOp = Cast->getOperand(0);
5976 const Type *SrcTy = CastOp->getType();
5977 uint32_t SrcTySize = SrcTy->getPrimitiveSizeInBits();
5978 if (SrcTy->isInteger() &&
5979 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
5980 // If this is an unsigned comparison, try to make the comparison use
5981 // smaller constant values.
5982 if (ICI.getPredicate() == ICmpInst::ICMP_ULT && RHSV.isSignBit()) {
5983 // X u< 128 => X s> -1
5984 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp,
5985 ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
5986 } else if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
5987 RHSV == APInt::getSignedMaxValue(SrcTySize)) {
5988 // X u> 127 => X s< 0
5989 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp,
5990 Constant::getNullValue(SrcTy));
5991 }
5992 }
5993 }
5994 }
5995 return 0;
5996}
5997
5998/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
5999/// We only handle extending casts so far.
6000///
Reid Spencere4d87aa2006-12-23 06:05:41 +00006001Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
6002 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +00006003 Value *LHSCIOp = LHSCI->getOperand(0);
6004 const Type *SrcTy = LHSCIOp->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00006005 const Type *DestTy = LHSCI->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00006006 Value *RHSCIOp;
6007
Chris Lattner8c756c12007-05-05 22:41:33 +00006008 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
6009 // integer type is the same size as the pointer type.
6010 if (LHSCI->getOpcode() == Instruction::PtrToInt &&
6011 getTargetData().getPointerSizeInBits() ==
6012 cast<IntegerType>(DestTy)->getBitWidth()) {
6013 Value *RHSOp = 0;
6014 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Chris Lattner6f6f5122007-05-06 07:24:03 +00006015 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Chris Lattner8c756c12007-05-05 22:41:33 +00006016 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
6017 RHSOp = RHSC->getOperand(0);
6018 // If the pointer types don't match, insert a bitcast.
6019 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner6d0339d2008-01-13 22:23:22 +00006020 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
Chris Lattner8c756c12007-05-05 22:41:33 +00006021 }
6022
6023 if (RHSOp)
6024 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
6025 }
6026
6027 // The code below only handles extension cast instructions, so far.
6028 // Enforce this.
Reid Spencere4d87aa2006-12-23 06:05:41 +00006029 if (LHSCI->getOpcode() != Instruction::ZExt &&
6030 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattnerb352fa52005-01-17 03:20:02 +00006031 return 0;
6032
Reid Spencere4d87aa2006-12-23 06:05:41 +00006033 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
6034 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattner484d3cf2005-04-24 06:59:08 +00006035
Reid Spencere4d87aa2006-12-23 06:05:41 +00006036 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00006037 // Not an extension from the same type?
6038 RHSCIOp = CI->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006039 if (RHSCIOp->getType() != LHSCIOp->getType())
6040 return 0;
Chris Lattnera5c5e772007-01-13 23:11:38 +00006041
Nick Lewycky4189a532008-01-28 03:48:02 +00006042 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Chris Lattnera5c5e772007-01-13 23:11:38 +00006043 // and the other is a zext), then we can't handle this.
6044 if (CI->getOpcode() != LHSCI->getOpcode())
6045 return 0;
6046
Nick Lewycky4189a532008-01-28 03:48:02 +00006047 // Deal with equality cases early.
6048 if (ICI.isEquality())
6049 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6050
6051 // A signed comparison of sign extended values simplifies into a
6052 // signed comparison.
6053 if (isSignedCmp && isSignedExt)
6054 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6055
6056 // The other three cases all fold into an unsigned comparison.
6057 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer6731d5c2004-11-28 21:31:15 +00006058 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00006059
Reid Spencere4d87aa2006-12-23 06:05:41 +00006060 // If we aren't dealing with a constant on the RHS, exit early
6061 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
6062 if (!CI)
6063 return 0;
6064
6065 // Compute the constant that would happen if we truncated to SrcTy then
6066 // reextended to DestTy.
6067 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
6068 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
6069
6070 // If the re-extended constant didn't change...
6071 if (Res2 == CI) {
6072 // Make sure that sign of the Cmp and the sign of the Cast are the same.
6073 // For example, we might have:
6074 // %A = sext short %X to uint
6075 // %B = icmp ugt uint %A, 1330
6076 // It is incorrect to transform this into
6077 // %B = icmp ugt short %X, 1330
6078 // because %A may have negative value.
6079 //
6080 // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
6081 // OR operation is EQ/NE.
Reid Spencer4fe16d62007-01-11 18:21:29 +00006082 if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
Reid Spencere4d87aa2006-12-23 06:05:41 +00006083 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
6084 else
6085 return 0;
6086 }
6087
6088 // The re-extended constant changed so the constant cannot be represented
6089 // in the shorter type. Consequently, we cannot emit a simple comparison.
6090
6091 // First, handle some easy cases. We know the result cannot be equal at this
6092 // point so handle the ICI.isEquality() cases
6093 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006094 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006095 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006096 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006097
6098 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
6099 // should have been folded away previously and not enter in here.
6100 Value *Result;
6101 if (isSignedCmp) {
6102 // We're performing a signed comparison.
Reid Spencer0460fb32007-03-22 20:36:03 +00006103 if (cast<ConstantInt>(CI)->getValue().isNegative())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006104 Result = ConstantInt::getFalse(); // X < (small) --> false
Reid Spencere4d87aa2006-12-23 06:05:41 +00006105 else
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006106 Result = ConstantInt::getTrue(); // X < (large) --> true
Reid Spencere4d87aa2006-12-23 06:05:41 +00006107 } else {
6108 // We're performing an unsigned comparison.
6109 if (isSignedExt) {
6110 // We're performing an unsigned comp with a sign extended value.
6111 // This is true if the input is >= 0. [aka >s -1]
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006112 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006113 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
6114 NegOne, ICI.getName()), ICI);
6115 } else {
6116 // Unsigned extend & unsigned compare -> always true.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006117 Result = ConstantInt::getTrue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00006118 }
6119 }
6120
6121 // Finally, return the value computed.
6122 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
6123 ICI.getPredicate() == ICmpInst::ICMP_SLT) {
6124 return ReplaceInstUsesWith(ICI, Result);
6125 } else {
6126 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
6127 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
6128 "ICmp should be folded!");
6129 if (Constant *CI = dyn_cast<Constant>(Result))
6130 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
6131 else
6132 return BinaryOperator::createNot(Result);
6133 }
Chris Lattner484d3cf2005-04-24 06:59:08 +00006134}
Chris Lattner3f5b8772002-05-06 16:14:14 +00006135
Reid Spencer832254e2007-02-02 02:16:23 +00006136Instruction *InstCombiner::visitShl(BinaryOperator &I) {
6137 return commonShiftTransforms(I);
6138}
6139
6140Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
6141 return commonShiftTransforms(I);
6142}
6143
6144Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner348f6652007-12-06 01:59:46 +00006145 if (Instruction *R = commonShiftTransforms(I))
6146 return R;
6147
6148 Value *Op0 = I.getOperand(0);
6149
6150 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
6151 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
6152 if (CSI->isAllOnesValue())
6153 return ReplaceInstUsesWith(I, CSI);
6154
6155 // See if we can turn a signed shr into an unsigned shr.
6156 if (MaskedValueIsZero(Op0,
6157 APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
6158 return BinaryOperator::createLShr(Op0, I.getOperand(1));
6159
6160 return 0;
Reid Spencer832254e2007-02-02 02:16:23 +00006161}
6162
6163Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
6164 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00006165 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00006166
6167 // shl X, 0 == X and shr X, 0 == X
6168 // shl 0, X == 0 and shr 0, X == 0
Reid Spencer832254e2007-02-02 02:16:23 +00006169 if (Op1 == Constant::getNullValue(Op1->getType()) ||
Chris Lattner233f7dc2002-08-12 21:17:25 +00006170 Op0 == Constant::getNullValue(Op0->getType()))
6171 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006172
Reid Spencere4d87aa2006-12-23 06:05:41 +00006173 if (isa<UndefValue>(Op0)) {
6174 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00006175 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006176 else // undef << X -> 0, undef >>u X -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00006177 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6178 }
6179 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006180 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
6181 return ReplaceInstUsesWith(I, Op0);
6182 else // X << undef, X >>u undef -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00006183 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00006184 }
6185
Chris Lattner2eefe512004-04-09 19:05:30 +00006186 // Try to fold constant and into select arguments.
6187 if (isa<Constant>(Op0))
6188 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00006189 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00006190 return R;
6191
Reid Spencerb83eb642006-10-20 07:07:24 +00006192 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00006193 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
6194 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006195 return 0;
6196}
6197
Reid Spencerb83eb642006-10-20 07:07:24 +00006198Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00006199 BinaryOperator &I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006200 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006201
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006202 // See if we can simplify any instructions used by the instruction whose sole
6203 // purpose is to compute bits we don't care about.
Reid Spencerb35ae032007-03-23 18:46:34 +00006204 uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
6205 APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
6206 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006207 KnownZero, KnownOne))
6208 return &I;
6209
Chris Lattner4d5542c2006-01-06 07:12:35 +00006210 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
6211 // of a signed value.
6212 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00006213 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00006214 if (I.getOpcode() != Instruction::AShr)
Chris Lattner4d5542c2006-01-06 07:12:35 +00006215 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
6216 else {
Chris Lattner0737c242007-02-02 05:29:55 +00006217 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00006218 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00006219 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006220 }
6221
6222 // ((X*C1) << C2) == (X * (C1 << C2))
6223 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
6224 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
6225 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
6226 return BinaryOperator::createMul(BO->getOperand(0),
6227 ConstantExpr::getShl(BOOp, Op1));
6228
6229 // Try to fold constant and into select arguments.
6230 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
6231 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6232 return R;
6233 if (isa<PHINode>(Op0))
6234 if (Instruction *NV = FoldOpIntoPhi(I))
6235 return NV;
6236
Chris Lattner8999dd32007-12-22 09:07:47 +00006237 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
6238 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
6239 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
6240 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
6241 // place. Don't try to do this transformation in this case. Also, we
6242 // require that the input operand is a shift-by-constant so that we have
6243 // confidence that the shifts will get folded together. We could do this
6244 // xform in more cases, but it is unlikely to be profitable.
6245 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
6246 isa<ConstantInt>(TrOp->getOperand(1))) {
6247 // Okay, we'll do this xform. Make the shift of shift.
6248 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
6249 Instruction *NSh = BinaryOperator::create(I.getOpcode(), TrOp, ShAmt,
6250 I.getName());
6251 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
6252
6253 // For logical shifts, the truncation has the effect of making the high
6254 // part of the register be zeros. Emulate this by inserting an AND to
6255 // clear the top bits as needed. This 'and' will usually be zapped by
6256 // other xforms later if dead.
6257 unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
6258 unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
6259 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
6260
6261 // The mask we constructed says what the trunc would do if occurring
6262 // between the shifts. We want to know the effect *after* the second
6263 // shift. We know that it is a logical shift by a constant, so adjust the
6264 // mask as appropriate.
6265 if (I.getOpcode() == Instruction::Shl)
6266 MaskV <<= Op1->getZExtValue();
6267 else {
6268 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
6269 MaskV = MaskV.lshr(Op1->getZExtValue());
6270 }
6271
6272 Instruction *And = BinaryOperator::createAnd(NSh, ConstantInt::get(MaskV),
6273 TI->getName());
6274 InsertNewInstBefore(And, I); // shift1 & 0x00FF
6275
6276 // Return the value truncated to the interesting size.
6277 return new TruncInst(And, I.getType());
6278 }
6279 }
6280
Chris Lattner4d5542c2006-01-06 07:12:35 +00006281 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00006282 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
6283 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
6284 Value *V1, *V2;
6285 ConstantInt *CC;
6286 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00006287 default: break;
6288 case Instruction::Add:
6289 case Instruction::And:
6290 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00006291 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00006292 // These operators commute.
6293 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00006294 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
6295 match(Op0BO->getOperand(1),
Chris Lattner4d5542c2006-01-06 07:12:35 +00006296 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Reid Spencercc46cdb2007-02-02 14:08:20 +00006297 Instruction *YS = BinaryOperator::createShl(
Chris Lattner4d5542c2006-01-06 07:12:35 +00006298 Op0BO->getOperand(0), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00006299 Op0BO->getName());
6300 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006301 Instruction *X =
6302 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
6303 Op0BO->getOperand(1)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006304 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00006305 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Zhou Sheng90b96812007-03-30 05:45:18 +00006306 return BinaryOperator::createAnd(X, ConstantInt::get(
6307 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00006308 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006309
Chris Lattner150f12a2005-09-18 06:30:59 +00006310 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00006311 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00006312 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00006313 match(Op0BOOp1,
6314 m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
Chris Lattner3c698492007-03-05 00:11:19 +00006315 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
6316 V2 == Op1) {
Reid Spencercc46cdb2007-02-02 14:08:20 +00006317 Instruction *YS = BinaryOperator::createShl(
Reid Spencer832254e2007-02-02 02:16:23 +00006318 Op0BO->getOperand(0), Op1,
6319 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006320 InsertNewInstBefore(YS, I); // (Y << C)
6321 Instruction *XM =
Chris Lattner4d5542c2006-01-06 07:12:35 +00006322 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00006323 V1->getName()+".mask");
6324 InsertNewInstBefore(XM, I); // X & (CC << C)
6325
6326 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
6327 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00006328 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006329
Reid Spencera07cb7d2007-02-02 14:41:37 +00006330 // FALL THROUGH.
6331 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00006332 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00006333 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6334 match(Op0BO->getOperand(0),
Chris Lattner4d5542c2006-01-06 07:12:35 +00006335 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Reid Spencercc46cdb2007-02-02 14:08:20 +00006336 Instruction *YS = BinaryOperator::createShl(
Reid Spencer832254e2007-02-02 02:16:23 +00006337 Op0BO->getOperand(1), Op1,
6338 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006339 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006340 Instruction *X =
Chris Lattner13d4ab42006-05-31 21:14:00 +00006341 BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006342 Op0BO->getOperand(0)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006343 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00006344 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Zhou Sheng90b96812007-03-30 05:45:18 +00006345 return BinaryOperator::createAnd(X, ConstantInt::get(
6346 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00006347 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006348
Chris Lattner13d4ab42006-05-31 21:14:00 +00006349 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00006350 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6351 match(Op0BO->getOperand(0),
6352 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner4d5542c2006-01-06 07:12:35 +00006353 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006354 cast<BinaryOperator>(Op0BO->getOperand(0))
6355 ->getOperand(0)->hasOneUse()) {
Reid Spencercc46cdb2007-02-02 14:08:20 +00006356 Instruction *YS = BinaryOperator::createShl(
Reid Spencer832254e2007-02-02 02:16:23 +00006357 Op0BO->getOperand(1), Op1,
6358 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006359 InsertNewInstBefore(YS, I); // (Y << C)
6360 Instruction *XM =
Chris Lattner4d5542c2006-01-06 07:12:35 +00006361 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00006362 V1->getName()+".mask");
6363 InsertNewInstBefore(XM, I); // X & (CC << C)
6364
Chris Lattner13d4ab42006-05-31 21:14:00 +00006365 return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00006366 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006367
Chris Lattner11021cb2005-09-18 05:12:10 +00006368 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00006369 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006370 }
6371
6372
6373 // If the operand is an bitwise operator with a constant RHS, and the
6374 // shift is the only use, we can pull it out of the shift.
6375 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
6376 bool isValid = true; // Valid only for And, Or, Xor
6377 bool highBitSet = false; // Transform if high bit of constant set?
6378
6379 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00006380 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00006381 case Instruction::Add:
6382 isValid = isLeftShift;
6383 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00006384 case Instruction::Or:
6385 case Instruction::Xor:
6386 highBitSet = false;
6387 break;
6388 case Instruction::And:
6389 highBitSet = true;
6390 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006391 }
6392
6393 // If this is a signed shift right, and the high bit is modified
6394 // by the logical operation, do not perform the transformation.
6395 // The highBitSet boolean indicates the value of the high bit of
6396 // the constant which would cause it to be modified for this
6397 // operation.
6398 //
Chris Lattnerc95ba442007-12-06 06:25:04 +00006399 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Shenge9e03f62007-03-28 15:02:20 +00006400 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006401
6402 if (isValid) {
6403 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
6404
6405 Instruction *NewShift =
Chris Lattner6934a042007-02-11 01:23:03 +00006406 BinaryOperator::create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00006407 InsertNewInstBefore(NewShift, I);
Chris Lattner6934a042007-02-11 01:23:03 +00006408 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00006409
6410 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
6411 NewRHS);
6412 }
6413 }
6414 }
6415 }
6416
Chris Lattnerad0124c2006-01-06 07:52:12 +00006417 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00006418 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
6419 if (ShiftOp && !ShiftOp->isShift())
6420 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00006421
Reid Spencerb83eb642006-10-20 07:07:24 +00006422 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00006423 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00006424 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
6425 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00006426 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
6427 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
6428 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00006429
Zhou Sheng4351c642007-04-02 08:20:41 +00006430 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Reid Spencerb35ae032007-03-23 18:46:34 +00006431 if (AmtSum > TypeBits)
6432 AmtSum = TypeBits;
Chris Lattnerb87056f2007-02-05 00:57:54 +00006433
6434 const IntegerType *Ty = cast<IntegerType>(I.getType());
6435
6436 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00006437 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattnerb87056f2007-02-05 00:57:54 +00006438 return BinaryOperator::create(I.getOpcode(), X,
6439 ConstantInt::get(Ty, AmtSum));
6440 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
6441 I.getOpcode() == Instruction::AShr) {
6442 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
6443 return BinaryOperator::createLShr(X, ConstantInt::get(Ty, AmtSum));
6444 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
6445 I.getOpcode() == Instruction::LShr) {
6446 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
6447 Instruction *Shift =
6448 BinaryOperator::createAShr(X, ConstantInt::get(Ty, AmtSum));
6449 InsertNewInstBefore(Shift, I);
6450
Zhou Shenge9e03f62007-03-28 15:02:20 +00006451 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Reid Spencerb35ae032007-03-23 18:46:34 +00006452 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00006453 }
6454
Chris Lattnerb87056f2007-02-05 00:57:54 +00006455 // Okay, if we get here, one shift must be left, and the other shift must be
6456 // right. See if the amounts are equal.
6457 if (ShiftAmt1 == ShiftAmt2) {
6458 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
6459 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00006460 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Reid Spencerb35ae032007-03-23 18:46:34 +00006461 return BinaryOperator::createAnd(X, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006462 }
6463 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
6464 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00006465 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Reid Spencerb35ae032007-03-23 18:46:34 +00006466 return BinaryOperator::createAnd(X, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006467 }
6468 // We can simplify ((X << C) >>s C) into a trunc + sext.
6469 // NOTE: we could do this for any C, but that would make 'unusual' integer
6470 // types. For now, just stick to ones well-supported by the code
6471 // generators.
6472 const Type *SExtType = 0;
6473 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00006474 case 1 :
6475 case 8 :
6476 case 16 :
6477 case 32 :
6478 case 64 :
6479 case 128:
6480 SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
6481 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00006482 default: break;
6483 }
6484 if (SExtType) {
6485 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
6486 InsertNewInstBefore(NewTrunc, I);
6487 return new SExtInst(NewTrunc, Ty);
6488 }
6489 // Otherwise, we can't handle it yet.
6490 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00006491 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00006492
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006493 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006494 if (I.getOpcode() == Instruction::Shl) {
6495 assert(ShiftOp->getOpcode() == Instruction::LShr ||
6496 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnere8d56c52006-01-07 01:32:28 +00006497 Instruction *Shift =
Chris Lattnerb87056f2007-02-05 00:57:54 +00006498 BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00006499 InsertNewInstBefore(Shift, I);
6500
Reid Spencer55702aa2007-03-25 21:11:44 +00006501 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
6502 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00006503 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00006504
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006505 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006506 if (I.getOpcode() == Instruction::LShr) {
6507 assert(ShiftOp->getOpcode() == Instruction::Shl);
6508 Instruction *Shift =
6509 BinaryOperator::createLShr(X, ConstantInt::get(Ty, ShiftDiff));
6510 InsertNewInstBefore(Shift, I);
Chris Lattnerad0124c2006-01-06 07:52:12 +00006511
Reid Spencerd5e30f02007-03-26 17:18:58 +00006512 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Reid Spencerb35ae032007-03-23 18:46:34 +00006513 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00006514 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00006515
6516 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
6517 } else {
6518 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00006519 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00006520
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006521 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006522 if (I.getOpcode() == Instruction::Shl) {
6523 assert(ShiftOp->getOpcode() == Instruction::LShr ||
6524 ShiftOp->getOpcode() == Instruction::AShr);
6525 Instruction *Shift =
6526 BinaryOperator::create(ShiftOp->getOpcode(), X,
6527 ConstantInt::get(Ty, ShiftDiff));
6528 InsertNewInstBefore(Shift, I);
6529
Reid Spencer55702aa2007-03-25 21:11:44 +00006530 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Reid Spencerb35ae032007-03-23 18:46:34 +00006531 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006532 }
6533
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006534 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006535 if (I.getOpcode() == Instruction::LShr) {
6536 assert(ShiftOp->getOpcode() == Instruction::Shl);
6537 Instruction *Shift =
6538 BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
6539 InsertNewInstBefore(Shift, I);
6540
Reid Spencer68d27cf2007-03-26 23:45:51 +00006541 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Reid Spencerb35ae032007-03-23 18:46:34 +00006542 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006543 }
6544
6545 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00006546 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00006547 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00006548 return 0;
6549}
6550
Chris Lattnera1be5662002-05-02 17:06:02 +00006551
Chris Lattnercfd65102005-10-29 04:36:15 +00006552/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
6553/// expression. If so, decompose it, returning some value X, such that Val is
6554/// X*Scale+Offset.
6555///
6556static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Jeff Cohen86796be2007-04-04 16:58:57 +00006557 int &Offset) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00006558 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00006559 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00006560 Offset = CI->getZExtValue();
Chris Lattner6a94de22007-10-12 05:30:59 +00006561 Scale = 0;
Reid Spencerc5b206b2006-12-31 05:48:39 +00006562 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattner6a94de22007-10-12 05:30:59 +00006563 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
6564 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
6565 if (I->getOpcode() == Instruction::Shl) {
6566 // This is a value scaled by '1 << the shift amt'.
6567 Scale = 1U << RHS->getZExtValue();
6568 Offset = 0;
6569 return I->getOperand(0);
6570 } else if (I->getOpcode() == Instruction::Mul) {
6571 // This value is scaled by 'RHS'.
6572 Scale = RHS->getZExtValue();
6573 Offset = 0;
6574 return I->getOperand(0);
6575 } else if (I->getOpcode() == Instruction::Add) {
6576 // We have X+C. Check to see if we really have (X*C2)+C1,
6577 // where C1 is divisible by C2.
6578 unsigned SubScale;
6579 Value *SubVal =
6580 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
6581 Offset += RHS->getZExtValue();
6582 Scale = SubScale;
6583 return SubVal;
Chris Lattnercfd65102005-10-29 04:36:15 +00006584 }
6585 }
6586 }
6587
6588 // Otherwise, we can't look past this.
6589 Scale = 1;
6590 Offset = 0;
6591 return Val;
6592}
6593
6594
Chris Lattnerb3f83972005-10-24 06:03:58 +00006595/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
6596/// try to eliminate the cast by moving the type information into the alloc.
Chris Lattnerd3e28342007-04-27 17:44:50 +00006597Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Chris Lattnerb3f83972005-10-24 06:03:58 +00006598 AllocationInst &AI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00006599 const PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattnerb3f83972005-10-24 06:03:58 +00006600
Chris Lattnerb53c2382005-10-24 06:22:12 +00006601 // Remove any uses of AI that are dead.
6602 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner535014f2007-02-15 22:52:10 +00006603
Chris Lattnerb53c2382005-10-24 06:22:12 +00006604 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
6605 Instruction *User = cast<Instruction>(*UI++);
6606 if (isInstructionTriviallyDead(User)) {
6607 while (UI != E && *UI == User)
6608 ++UI; // If this instruction uses AI more than once, don't break UI.
6609
Chris Lattnerb53c2382005-10-24 06:22:12 +00006610 ++NumDeadInst;
Bill Wendlingb7427032006-11-26 09:46:52 +00006611 DOUT << "IC: DCE: " << *User;
Chris Lattnerf22a5c62007-03-02 19:59:19 +00006612 EraseInstFromFunction(*User);
Chris Lattnerb53c2382005-10-24 06:22:12 +00006613 }
6614 }
6615
Chris Lattnerb3f83972005-10-24 06:03:58 +00006616 // Get the type really allocated and the type casted to.
6617 const Type *AllocElTy = AI.getAllocatedType();
6618 const Type *CastElTy = PTy->getElementType();
6619 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00006620
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00006621 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
6622 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00006623 if (CastElTyAlign < AllocElTyAlign) return 0;
6624
Chris Lattner39387a52005-10-24 06:35:18 +00006625 // If the allocation has multiple uses, only promote it if we are strictly
6626 // increasing the alignment of the resultant allocation. If we keep it the
6627 // same, we open the door to infinite loops of various kinds.
6628 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
6629
Duncan Sands514ab342007-11-01 20:53:16 +00006630 uint64_t AllocElTySize = TD->getABITypeSize(AllocElTy);
6631 uint64_t CastElTySize = TD->getABITypeSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00006632 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00006633
Chris Lattner455fcc82005-10-29 03:19:53 +00006634 // See if we can satisfy the modulus by pulling a scale out of the array
6635 // size argument.
Jeff Cohen86796be2007-04-04 16:58:57 +00006636 unsigned ArraySizeScale;
6637 int ArrayOffset;
Chris Lattnercfd65102005-10-29 04:36:15 +00006638 Value *NumElements = // See if the array size is a decomposable linear expr.
6639 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
6640
Chris Lattner455fcc82005-10-29 03:19:53 +00006641 // If we can now satisfy the modulus, by using a non-1 scale, we really can
6642 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00006643 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
6644 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00006645
Chris Lattner455fcc82005-10-29 03:19:53 +00006646 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
6647 Value *Amt = 0;
6648 if (Scale == 1) {
6649 Amt = NumElements;
6650 } else {
Reid Spencerb83eb642006-10-20 07:07:24 +00006651 // If the allocation size is constant, form a constant mul expression
Reid Spencerc5b206b2006-12-31 05:48:39 +00006652 Amt = ConstantInt::get(Type::Int32Ty, Scale);
6653 if (isa<ConstantInt>(NumElements))
Zhou Sheng4a1822a2007-04-02 13:45:30 +00006654 Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
Reid Spencerb83eb642006-10-20 07:07:24 +00006655 // otherwise multiply the amount and the number of elements
Chris Lattner455fcc82005-10-29 03:19:53 +00006656 else if (Scale != 1) {
6657 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
6658 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattner8142b0a2005-10-27 06:12:00 +00006659 }
Chris Lattner0ddac2a2005-10-27 05:53:56 +00006660 }
6661
Jeff Cohen86796be2007-04-04 16:58:57 +00006662 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
6663 Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
Chris Lattnercfd65102005-10-29 04:36:15 +00006664 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
6665 Amt = InsertNewInstBefore(Tmp, AI);
6666 }
6667
Chris Lattnerb3f83972005-10-24 06:03:58 +00006668 AllocationInst *New;
6669 if (isa<MallocInst>(AI))
Chris Lattner6934a042007-02-11 01:23:03 +00006670 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00006671 else
Chris Lattner6934a042007-02-11 01:23:03 +00006672 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00006673 InsertNewInstBefore(New, AI);
Chris Lattner6934a042007-02-11 01:23:03 +00006674 New->takeName(&AI);
Chris Lattner39387a52005-10-24 06:35:18 +00006675
6676 // If the allocation has multiple uses, insert a cast and change all things
6677 // that used it to use the new cast. This will also hack on CI, but it will
6678 // die soon.
6679 if (!AI.hasOneUse()) {
6680 AddUsesToWorkList(AI);
Reid Spencer3da59db2006-11-27 01:05:10 +00006681 // New is the allocation instruction, pointer typed. AI is the original
6682 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
6683 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner39387a52005-10-24 06:35:18 +00006684 InsertNewInstBefore(NewCast, AI);
6685 AI.replaceAllUsesWith(NewCast);
6686 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00006687 return ReplaceInstUsesWith(CI, New);
6688}
6689
Chris Lattner70074e02006-05-13 02:06:03 +00006690/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerc739cd62007-03-03 05:27:34 +00006691/// and return it as type Ty without inserting any new casts and without
6692/// changing the computed value. This is used by code that tries to decide
6693/// whether promoting or shrinking integer operations to wider or smaller types
6694/// will allow us to eliminate a truncate or extend.
6695///
6696/// This is a truncation operation if Ty is smaller than V->getType(), or an
6697/// extension operation if Ty is larger.
6698static bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
Chris Lattner951626b2007-08-02 06:11:14 +00006699 unsigned CastOpc, int &NumCastsRemoved) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00006700 // We can always evaluate constants in another type.
6701 if (isa<ConstantInt>(V))
6702 return true;
Chris Lattner70074e02006-05-13 02:06:03 +00006703
6704 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006705 if (!I) return false;
6706
6707 const IntegerType *OrigTy = cast<IntegerType>(V->getType());
Chris Lattner70074e02006-05-13 02:06:03 +00006708
Chris Lattner951626b2007-08-02 06:11:14 +00006709 // If this is an extension or truncate, we can often eliminate it.
6710 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
6711 // If this is a cast from the destination type, we can trivially eliminate
6712 // it, and this will remove a cast overall.
6713 if (I->getOperand(0)->getType() == Ty) {
6714 // If the first operand is itself a cast, and is eliminable, do not count
6715 // this as an eliminable cast. We would prefer to eliminate those two
6716 // casts first.
6717 if (!isa<CastInst>(I->getOperand(0)))
6718 ++NumCastsRemoved;
6719 return true;
6720 }
6721 }
6722
6723 // We can't extend or shrink something that has multiple uses: doing so would
6724 // require duplicating the instruction in general, which isn't profitable.
6725 if (!I->hasOneUse()) return false;
6726
Chris Lattner70074e02006-05-13 02:06:03 +00006727 switch (I->getOpcode()) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00006728 case Instruction::Add:
6729 case Instruction::Sub:
Chris Lattner70074e02006-05-13 02:06:03 +00006730 case Instruction::And:
6731 case Instruction::Or:
6732 case Instruction::Xor:
6733 // These operators can all arbitrarily be extended or truncated.
Chris Lattner951626b2007-08-02 06:11:14 +00006734 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6735 NumCastsRemoved) &&
6736 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
6737 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006738
Nick Lewyckye6b0c002008-01-22 05:08:48 +00006739 case Instruction::Mul:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00006740 // A multiply can be truncated by truncating its operands.
6741 return Ty->getBitWidth() < OrigTy->getBitWidth() &&
6742 CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6743 NumCastsRemoved) &&
6744 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
6745 NumCastsRemoved);
6746
Chris Lattner46b96052006-11-29 07:18:39 +00006747 case Instruction::Shl:
Chris Lattnerc739cd62007-03-03 05:27:34 +00006748 // If we are truncating the result of this SHL, and if it's a shift of a
6749 // constant amount, we can always perform a SHL in a smaller type.
6750 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00006751 uint32_t BitWidth = Ty->getBitWidth();
6752 if (BitWidth < OrigTy->getBitWidth() &&
6753 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattner951626b2007-08-02 06:11:14 +00006754 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6755 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006756 }
6757 break;
6758 case Instruction::LShr:
Chris Lattnerc739cd62007-03-03 05:27:34 +00006759 // If this is a truncate of a logical shr, we can truncate it to a smaller
6760 // lshr iff we know that the bits we would otherwise be shifting in are
6761 // already zeros.
6762 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00006763 uint32_t OrigBitWidth = OrigTy->getBitWidth();
6764 uint32_t BitWidth = Ty->getBitWidth();
6765 if (BitWidth < OrigBitWidth &&
Chris Lattnerc739cd62007-03-03 05:27:34 +00006766 MaskedValueIsZero(I->getOperand(0),
Zhou Sheng302748d2007-03-30 17:20:39 +00006767 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
6768 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattner951626b2007-08-02 06:11:14 +00006769 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6770 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006771 }
6772 }
Chris Lattner46b96052006-11-29 07:18:39 +00006773 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00006774 case Instruction::ZExt:
6775 case Instruction::SExt:
Chris Lattner951626b2007-08-02 06:11:14 +00006776 case Instruction::Trunc:
6777 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner5543a852007-08-02 17:23:38 +00006778 // can safely replace it. Note that replacing it does not reduce the number
6779 // of casts in the input.
6780 if (I->getOpcode() == CastOpc)
Chris Lattner70074e02006-05-13 02:06:03 +00006781 return true;
Chris Lattner50d9d772007-09-10 23:46:29 +00006782
Reid Spencer3da59db2006-11-27 01:05:10 +00006783 break;
6784 default:
Chris Lattner70074e02006-05-13 02:06:03 +00006785 // TODO: Can handle more cases here.
6786 break;
6787 }
6788
6789 return false;
6790}
6791
6792/// EvaluateInDifferentType - Given an expression that
6793/// CanEvaluateInDifferentType returns true for, actually insert the code to
6794/// evaluate the expression.
Reid Spencerc55b2432006-12-13 18:21:21 +00006795Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerc739cd62007-03-03 05:27:34 +00006796 bool isSigned) {
Chris Lattner70074e02006-05-13 02:06:03 +00006797 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencerc55b2432006-12-13 18:21:21 +00006798 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Chris Lattner70074e02006-05-13 02:06:03 +00006799
6800 // Otherwise, it must be an instruction.
6801 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00006802 Instruction *Res = 0;
Chris Lattner70074e02006-05-13 02:06:03 +00006803 switch (I->getOpcode()) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00006804 case Instruction::Add:
6805 case Instruction::Sub:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00006806 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00006807 case Instruction::And:
6808 case Instruction::Or:
Chris Lattnerc739cd62007-03-03 05:27:34 +00006809 case Instruction::Xor:
Chris Lattner46b96052006-11-29 07:18:39 +00006810 case Instruction::AShr:
6811 case Instruction::LShr:
6812 case Instruction::Shl: {
Reid Spencerc55b2432006-12-13 18:21:21 +00006813 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006814 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
6815 Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
6816 LHS, RHS, I->getName());
Chris Lattner46b96052006-11-29 07:18:39 +00006817 break;
6818 }
Reid Spencer3da59db2006-11-27 01:05:10 +00006819 case Instruction::Trunc:
6820 case Instruction::ZExt:
6821 case Instruction::SExt:
Reid Spencer3da59db2006-11-27 01:05:10 +00006822 // If the source type of the cast is the type we're trying for then we can
Chris Lattner951626b2007-08-02 06:11:14 +00006823 // just return the source. There's no need to insert it because it is not
6824 // new.
Chris Lattner70074e02006-05-13 02:06:03 +00006825 if (I->getOperand(0)->getType() == Ty)
6826 return I->getOperand(0);
6827
Chris Lattner951626b2007-08-02 06:11:14 +00006828 // Otherwise, must be the same type of case, so just reinsert a new one.
6829 Res = CastInst::create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
6830 Ty, I->getName());
6831 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00006832 default:
Chris Lattner70074e02006-05-13 02:06:03 +00006833 // TODO: Can handle more cases here.
6834 assert(0 && "Unreachable!");
6835 break;
6836 }
6837
6838 return InsertNewInstBefore(Res, *I);
6839}
6840
Reid Spencer3da59db2006-11-27 01:05:10 +00006841/// @brief Implement the transforms common to all CastInst visitors.
6842Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00006843 Value *Src = CI.getOperand(0);
6844
Dan Gohman23d9d272007-05-11 21:10:54 +00006845 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
Reid Spencer3da59db2006-11-27 01:05:10 +00006846 // eliminate it now.
Chris Lattner6e7ba452005-01-01 16:22:27 +00006847 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00006848 if (Instruction::CastOps opc =
6849 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
6850 // The first cast (CSrc) is eliminable so we need to fix up or replace
6851 // the second cast (CI). CSrc will then have a good chance of being dead.
6852 return CastInst::create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner8fd217c2002-08-02 20:00:25 +00006853 }
6854 }
Chris Lattnera710ddc2004-05-25 04:29:21 +00006855
Reid Spencer3da59db2006-11-27 01:05:10 +00006856 // If we are casting a select then fold the cast into the select
Chris Lattner6e7ba452005-01-01 16:22:27 +00006857 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
6858 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
6859 return NV;
Reid Spencer3da59db2006-11-27 01:05:10 +00006860
6861 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner4e998b22004-09-29 05:07:12 +00006862 if (isa<PHINode>(Src))
6863 if (Instruction *NV = FoldOpIntoPhi(CI))
6864 return NV;
Chris Lattner9fb92132006-04-12 18:09:35 +00006865
Reid Spencer3da59db2006-11-27 01:05:10 +00006866 return 0;
6867}
6868
Chris Lattnerd3e28342007-04-27 17:44:50 +00006869/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
6870Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
6871 Value *Src = CI.getOperand(0);
6872
Chris Lattnerd3e28342007-04-27 17:44:50 +00006873 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner9bc14642007-04-28 00:57:34 +00006874 // If casting the result of a getelementptr instruction with no offset, turn
6875 // this into a cast of the original pointer!
Chris Lattnerd3e28342007-04-27 17:44:50 +00006876 if (GEP->hasAllZeroIndices()) {
6877 // Changing the cast operand is usually not a good idea but it is safe
6878 // here because the pointer operand is being replaced with another
6879 // pointer operand so the opcode doesn't need to change.
Chris Lattner9bc14642007-04-28 00:57:34 +00006880 AddToWorkList(GEP);
Chris Lattnerd3e28342007-04-27 17:44:50 +00006881 CI.setOperand(0, GEP->getOperand(0));
6882 return &CI;
6883 }
Chris Lattner9bc14642007-04-28 00:57:34 +00006884
6885 // If the GEP has a single use, and the base pointer is a bitcast, and the
6886 // GEP computes a constant offset, see if we can convert these three
6887 // instructions into fewer. This typically happens with unions and other
6888 // non-type-safe code.
6889 if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
6890 if (GEP->hasAllConstantIndices()) {
6891 // We are guaranteed to get a constant from EmitGEPOffset.
6892 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
6893 int64_t Offset = OffsetV->getSExtValue();
6894
6895 // Get the base pointer input of the bitcast, and the type it points to.
6896 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
6897 const Type *GEPIdxTy =
6898 cast<PointerType>(OrigBase->getType())->getElementType();
6899 if (GEPIdxTy->isSized()) {
6900 SmallVector<Value*, 8> NewIndices;
6901
Chris Lattnerc42e2262007-05-05 01:59:31 +00006902 // Start with the index over the outer type. Note that the type size
6903 // might be zero (even if the offset isn't zero) if the indexed type
6904 // is something like [0 x {int, int}]
Chris Lattner9bc14642007-04-28 00:57:34 +00006905 const Type *IntPtrTy = TD->getIntPtrType();
Chris Lattnerc42e2262007-05-05 01:59:31 +00006906 int64_t FirstIdx = 0;
Duncan Sands514ab342007-11-01 20:53:16 +00006907 if (int64_t TySize = TD->getABITypeSize(GEPIdxTy)) {
Chris Lattnerc42e2262007-05-05 01:59:31 +00006908 FirstIdx = Offset/TySize;
6909 Offset %= TySize;
Chris Lattner9bc14642007-04-28 00:57:34 +00006910
Chris Lattnerc42e2262007-05-05 01:59:31 +00006911 // Handle silly modulus not returning values values [0..TySize).
6912 if (Offset < 0) {
6913 --FirstIdx;
6914 Offset += TySize;
6915 assert(Offset >= 0);
6916 }
Chris Lattnerd717c182007-05-05 22:32:24 +00006917 assert((uint64_t)Offset < (uint64_t)TySize &&"Out of range offset");
Chris Lattner9bc14642007-04-28 00:57:34 +00006918 }
6919
6920 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner9bc14642007-04-28 00:57:34 +00006921
6922 // Index into the types. If we fail, set OrigBase to null.
6923 while (Offset) {
6924 if (const StructType *STy = dyn_cast<StructType>(GEPIdxTy)) {
6925 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattner6b6aef82007-05-15 00:16:00 +00006926 if (Offset < (int64_t)SL->getSizeInBytes()) {
6927 unsigned Elt = SL->getElementContainingOffset(Offset);
6928 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
Chris Lattner9bc14642007-04-28 00:57:34 +00006929
Chris Lattner6b6aef82007-05-15 00:16:00 +00006930 Offset -= SL->getElementOffset(Elt);
6931 GEPIdxTy = STy->getElementType(Elt);
6932 } else {
6933 // Otherwise, we can't index into this, bail out.
6934 Offset = 0;
6935 OrigBase = 0;
6936 }
Chris Lattner9bc14642007-04-28 00:57:34 +00006937 } else if (isa<ArrayType>(GEPIdxTy) || isa<VectorType>(GEPIdxTy)) {
6938 const SequentialType *STy = cast<SequentialType>(GEPIdxTy);
Duncan Sands514ab342007-11-01 20:53:16 +00006939 if (uint64_t EltSize = TD->getABITypeSize(STy->getElementType())){
Chris Lattner6b6aef82007-05-15 00:16:00 +00006940 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
6941 Offset %= EltSize;
6942 } else {
6943 NewIndices.push_back(ConstantInt::get(IntPtrTy, 0));
6944 }
Chris Lattner9bc14642007-04-28 00:57:34 +00006945 GEPIdxTy = STy->getElementType();
6946 } else {
6947 // Otherwise, we can't index into this, bail out.
6948 Offset = 0;
6949 OrigBase = 0;
6950 }
6951 }
6952 if (OrigBase) {
6953 // If we were able to index down into an element, create the GEP
6954 // and bitcast the result. This eliminates one bitcast, potentially
6955 // two.
David Greeneb8f74792007-09-04 15:46:09 +00006956 Instruction *NGEP = new GetElementPtrInst(OrigBase,
6957 NewIndices.begin(),
6958 NewIndices.end(), "");
Chris Lattner9bc14642007-04-28 00:57:34 +00006959 InsertNewInstBefore(NGEP, CI);
6960 NGEP->takeName(GEP);
6961
Chris Lattner9bc14642007-04-28 00:57:34 +00006962 if (isa<BitCastInst>(CI))
6963 return new BitCastInst(NGEP, CI.getType());
6964 assert(isa<PtrToIntInst>(CI));
6965 return new PtrToIntInst(NGEP, CI.getType());
6966 }
6967 }
6968 }
6969 }
Chris Lattnerd3e28342007-04-27 17:44:50 +00006970 }
6971
6972 return commonCastTransforms(CI);
6973}
6974
6975
6976
Chris Lattnerc739cd62007-03-03 05:27:34 +00006977/// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
6978/// integer types. This function implements the common transforms for all those
Reid Spencer3da59db2006-11-27 01:05:10 +00006979/// cases.
6980/// @brief Implement the transforms common to CastInst with integer operands
6981Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
6982 if (Instruction *Result = commonCastTransforms(CI))
6983 return Result;
6984
6985 Value *Src = CI.getOperand(0);
6986 const Type *SrcTy = Src->getType();
6987 const Type *DestTy = CI.getType();
Zhou Sheng4351c642007-04-02 08:20:41 +00006988 uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
6989 uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00006990
Reid Spencer3da59db2006-11-27 01:05:10 +00006991 // See if we can simplify any instructions used by the LHS whose sole
6992 // purpose is to compute bits we don't care about.
Reid Spencerad6676e2007-03-22 20:56:53 +00006993 APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
6994 if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
Reid Spencer3da59db2006-11-27 01:05:10 +00006995 KnownZero, KnownOne))
6996 return &CI;
6997
6998 // If the source isn't an instruction or has more than one use then we
6999 // can't do anything more.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007000 Instruction *SrcI = dyn_cast<Instruction>(Src);
7001 if (!SrcI || !Src->hasOneUse())
Reid Spencer3da59db2006-11-27 01:05:10 +00007002 return 0;
7003
Chris Lattnerc739cd62007-03-03 05:27:34 +00007004 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00007005 int NumCastsRemoved = 0;
Chris Lattnerc739cd62007-03-03 05:27:34 +00007006 if (!isa<BitCastInst>(CI) &&
7007 CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
Chris Lattner951626b2007-08-02 06:11:14 +00007008 CI.getOpcode(), NumCastsRemoved)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007009 // If this cast is a truncate, evaluting in a different type always
Chris Lattner951626b2007-08-02 06:11:14 +00007010 // eliminates the cast, so it is always a win. If this is a zero-extension,
7011 // we need to do an AND to maintain the clear top-part of the computation,
7012 // so we require that the input have eliminated at least one cast. If this
7013 // is a sign extension, we insert two new casts (to do the extension) so we
Reid Spencer3da59db2006-11-27 01:05:10 +00007014 // require that two casts have been eliminated.
Chris Lattnerc739cd62007-03-03 05:27:34 +00007015 bool DoXForm;
7016 switch (CI.getOpcode()) {
7017 default:
7018 // All the others use floating point so we shouldn't actually
7019 // get here because of the check above.
7020 assert(0 && "Unknown cast type");
7021 case Instruction::Trunc:
7022 DoXForm = true;
7023 break;
7024 case Instruction::ZExt:
7025 DoXForm = NumCastsRemoved >= 1;
7026 break;
7027 case Instruction::SExt:
7028 DoXForm = NumCastsRemoved >= 2;
7029 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007030 }
7031
7032 if (DoXForm) {
Reid Spencerc55b2432006-12-13 18:21:21 +00007033 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
7034 CI.getOpcode() == Instruction::SExt);
Reid Spencer3da59db2006-11-27 01:05:10 +00007035 assert(Res->getType() == DestTy);
7036 switch (CI.getOpcode()) {
7037 default: assert(0 && "Unknown cast type!");
7038 case Instruction::Trunc:
7039 case Instruction::BitCast:
7040 // Just replace this cast with the result.
7041 return ReplaceInstUsesWith(CI, Res);
7042 case Instruction::ZExt: {
7043 // We need to emit an AND to clear the high bits.
7044 assert(SrcBitSize < DestBitSize && "Not a zext?");
Chris Lattnercd1d6d52007-04-02 05:48:58 +00007045 Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
7046 SrcBitSize));
Reid Spencer3da59db2006-11-27 01:05:10 +00007047 return BinaryOperator::createAnd(Res, C);
7048 }
7049 case Instruction::SExt:
7050 // We need to emit a cast to truncate, then a cast to sext.
7051 return CastInst::create(Instruction::SExt,
Reid Spencer17212df2006-12-12 09:18:51 +00007052 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
7053 CI), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00007054 }
7055 }
7056 }
7057
7058 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
7059 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
7060
7061 switch (SrcI->getOpcode()) {
7062 case Instruction::Add:
7063 case Instruction::Mul:
7064 case Instruction::And:
7065 case Instruction::Or:
7066 case Instruction::Xor:
Chris Lattner01deb9d2007-04-03 17:43:25 +00007067 // If we are discarding information, rewrite.
Reid Spencer3da59db2006-11-27 01:05:10 +00007068 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
7069 // Don't insert two casts if they cannot be eliminated. We allow
7070 // two casts to be inserted if the sizes are the same. This could
7071 // only be converting signedness, which is a noop.
7072 if (DestBitSize == SrcBitSize ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00007073 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
7074 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer7eb76382006-12-13 17:19:09 +00007075 Instruction::CastOps opcode = CI.getOpcode();
Reid Spencer17212df2006-12-12 09:18:51 +00007076 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7077 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
7078 return BinaryOperator::create(
7079 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00007080 }
7081 }
7082
7083 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
7084 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
7085 SrcI->getOpcode() == Instruction::Xor &&
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007086 Op1 == ConstantInt::getTrue() &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00007087 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Reid Spencer17212df2006-12-12 09:18:51 +00007088 Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007089 return BinaryOperator::createXor(New, ConstantInt::get(CI.getType(), 1));
7090 }
7091 break;
7092 case Instruction::SDiv:
7093 case Instruction::UDiv:
7094 case Instruction::SRem:
7095 case Instruction::URem:
7096 // If we are just changing the sign, rewrite.
7097 if (DestBitSize == SrcBitSize) {
7098 // Don't insert two casts if they cannot be eliminated. We allow
7099 // two casts to be inserted if the sizes are the same. This could
7100 // only be converting signedness, which is a noop.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007101 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
7102 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer17212df2006-12-12 09:18:51 +00007103 Value *Op0c = InsertOperandCastBefore(Instruction::BitCast,
7104 Op0, DestTy, SrcI);
7105 Value *Op1c = InsertOperandCastBefore(Instruction::BitCast,
7106 Op1, DestTy, SrcI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007107 return BinaryOperator::create(
7108 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7109 }
7110 }
7111 break;
7112
7113 case Instruction::Shl:
7114 // Allow changing the sign of the source operand. Do not allow
7115 // changing the size of the shift, UNLESS the shift amount is a
7116 // constant. We must not change variable sized shifts to a smaller
7117 // size, because it is undefined to shift more bits out than exist
7118 // in the value.
7119 if (DestBitSize == SrcBitSize ||
7120 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
Reid Spencer17212df2006-12-12 09:18:51 +00007121 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
7122 Instruction::BitCast : Instruction::Trunc);
7123 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
Reid Spencer832254e2007-02-02 02:16:23 +00007124 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
Reid Spencercc46cdb2007-02-02 14:08:20 +00007125 return BinaryOperator::createShl(Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00007126 }
7127 break;
7128 case Instruction::AShr:
7129 // If this is a signed shr, and if all bits shifted in are about to be
7130 // truncated off, turn it into an unsigned shr to allow greater
7131 // simplifications.
7132 if (DestBitSize < SrcBitSize &&
7133 isa<ConstantInt>(Op1)) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007134 uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
Reid Spencer3da59db2006-11-27 01:05:10 +00007135 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
7136 // Insert the new logical shift right.
Reid Spencercc46cdb2007-02-02 14:08:20 +00007137 return BinaryOperator::createLShr(Op0, Op1);
Reid Spencer3da59db2006-11-27 01:05:10 +00007138 }
7139 }
7140 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007141 }
7142 return 0;
7143}
7144
Chris Lattner8a9f5712007-04-11 06:57:46 +00007145Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007146 if (Instruction *Result = commonIntCastTransforms(CI))
7147 return Result;
7148
7149 Value *Src = CI.getOperand(0);
7150 const Type *Ty = CI.getType();
Zhou Sheng4351c642007-04-02 08:20:41 +00007151 uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
7152 uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007153
7154 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
7155 switch (SrcI->getOpcode()) {
7156 default: break;
7157 case Instruction::LShr:
7158 // We can shrink lshr to something smaller if we know the bits shifted in
7159 // are already zeros.
7160 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007161 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007162
7163 // Get a mask for the bits shifting in.
Zhou Shenge82fca02007-03-28 09:19:01 +00007164 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
Reid Spencer17212df2006-12-12 09:18:51 +00007165 Value* SrcIOp0 = SrcI->getOperand(0);
7166 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007167 if (ShAmt >= DestBitWidth) // All zeros.
7168 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
7169
7170 // Okay, we can shrink this. Truncate the input, then return a new
7171 // shift.
Reid Spencer832254e2007-02-02 02:16:23 +00007172 Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
7173 Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
7174 Ty, CI);
Reid Spencercc46cdb2007-02-02 14:08:20 +00007175 return BinaryOperator::createLShr(V1, V2);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007176 }
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007177 } else { // This is a variable shr.
7178
7179 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
7180 // more LLVM instructions, but allows '1 << Y' to be hoisted if
7181 // loop-invariant and CSE'd.
Reid Spencer4fe16d62007-01-11 18:21:29 +00007182 if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007183 Value *One = ConstantInt::get(SrcI->getType(), 1);
7184
Reid Spencer832254e2007-02-02 02:16:23 +00007185 Value *V = InsertNewInstBefore(
Reid Spencercc46cdb2007-02-02 14:08:20 +00007186 BinaryOperator::createShl(One, SrcI->getOperand(1),
Reid Spencer832254e2007-02-02 02:16:23 +00007187 "tmp"), CI);
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007188 V = InsertNewInstBefore(BinaryOperator::createAnd(V,
7189 SrcI->getOperand(0),
7190 "tmp"), CI);
7191 Value *Zero = Constant::getNullValue(V->getType());
Reid Spencere4d87aa2006-12-23 06:05:41 +00007192 return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007193 }
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007194 }
7195 break;
7196 }
7197 }
7198
7199 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007200}
7201
Evan Chengb98a10e2008-03-24 00:21:34 +00007202/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
7203/// in order to eliminate the icmp.
7204Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
7205 bool DoXform) {
7206 // If we are just checking for a icmp eq of a single bit and zext'ing it
7207 // to an integer, then shift the bit to the appropriate place and then
7208 // cast to integer to avoid the comparison.
7209 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7210 const APInt &Op1CV = Op1C->getValue();
7211
7212 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
7213 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
7214 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7215 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
7216 if (!DoXform) return ICI;
7217
7218 Value *In = ICI->getOperand(0);
7219 Value *Sh = ConstantInt::get(In->getType(),
7220 In->getType()->getPrimitiveSizeInBits()-1);
7221 In = InsertNewInstBefore(BinaryOperator::createLShr(In, Sh,
7222 In->getName()+".lobit"),
7223 CI);
7224 if (In->getType() != CI.getType())
7225 In = CastInst::createIntegerCast(In, CI.getType(),
7226 false/*ZExt*/, "tmp", &CI);
7227
7228 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
7229 Constant *One = ConstantInt::get(In->getType(), 1);
7230 In = InsertNewInstBefore(BinaryOperator::createXor(In, One,
7231 In->getName()+".not"),
7232 CI);
7233 }
7234
7235 return ReplaceInstUsesWith(CI, In);
7236 }
7237
7238
7239
7240 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
7241 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7242 // zext (X == 1) to i32 --> X iff X has only the low bit set.
7243 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
7244 // zext (X != 0) to i32 --> X iff X has only the low bit set.
7245 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
7246 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
7247 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7248 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
7249 // This only works for EQ and NE
7250 ICI->isEquality()) {
7251 // If Op1C some other power of two, convert:
7252 uint32_t BitWidth = Op1C->getType()->getBitWidth();
7253 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
7254 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
7255 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
7256
7257 APInt KnownZeroMask(~KnownZero);
7258 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
7259 if (!DoXform) return ICI;
7260
7261 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
7262 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
7263 // (X&4) == 2 --> false
7264 // (X&4) != 2 --> true
7265 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
7266 Res = ConstantExpr::getZExt(Res, CI.getType());
7267 return ReplaceInstUsesWith(CI, Res);
7268 }
7269
7270 uint32_t ShiftAmt = KnownZeroMask.logBase2();
7271 Value *In = ICI->getOperand(0);
7272 if (ShiftAmt) {
7273 // Perform a logical shr by shiftamt.
7274 // Insert the shift to put the result in the low bit.
7275 In = InsertNewInstBefore(BinaryOperator::createLShr(In,
7276 ConstantInt::get(In->getType(), ShiftAmt),
7277 In->getName()+".lobit"), CI);
7278 }
7279
7280 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
7281 Constant *One = ConstantInt::get(In->getType(), 1);
7282 In = BinaryOperator::createXor(In, One, "tmp");
7283 InsertNewInstBefore(cast<Instruction>(In), CI);
7284 }
7285
7286 if (CI.getType() == In->getType())
7287 return ReplaceInstUsesWith(CI, In);
7288 else
7289 return CastInst::createIntegerCast(In, CI.getType(), false/*ZExt*/);
7290 }
7291 }
7292 }
7293
7294 return 0;
7295}
7296
Chris Lattner8a9f5712007-04-11 06:57:46 +00007297Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007298 // If one of the common conversion will work ..
7299 if (Instruction *Result = commonIntCastTransforms(CI))
7300 return Result;
7301
7302 Value *Src = CI.getOperand(0);
7303
7304 // If this is a cast of a cast
7305 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00007306 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
7307 // types and if the sizes are just right we can convert this into a logical
7308 // 'and' which will be much cheaper than the pair of casts.
7309 if (isa<TruncInst>(CSrc)) {
7310 // Get the sizes of the types involved
7311 Value *A = CSrc->getOperand(0);
Zhou Sheng4351c642007-04-02 08:20:41 +00007312 uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
7313 uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
7314 uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00007315 // If we're actually extending zero bits and the trunc is a no-op
7316 if (MidSize < DstSize && SrcSize == DstSize) {
7317 // Replace both of the casts with an And of the type mask.
Zhou Shenge82fca02007-03-28 09:19:01 +00007318 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Reid Spencerad6676e2007-03-22 20:56:53 +00007319 Constant *AndConst = ConstantInt::get(AndValue);
Reid Spencer3da59db2006-11-27 01:05:10 +00007320 Instruction *And =
7321 BinaryOperator::createAnd(CSrc->getOperand(0), AndConst);
7322 // Unfortunately, if the type changed, we need to cast it back.
7323 if (And->getType() != CI.getType()) {
7324 And->setName(CSrc->getName()+".mask");
7325 InsertNewInstBefore(And, CI);
Reid Spencerd977d862006-12-12 23:36:14 +00007326 And = CastInst::createIntegerCast(And, CI.getType(), false/*ZExt*/);
Reid Spencer3da59db2006-11-27 01:05:10 +00007327 }
7328 return And;
7329 }
7330 }
7331 }
7332
Evan Chengb98a10e2008-03-24 00:21:34 +00007333 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
7334 return transformZExtICmp(ICI, CI);
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00007335
Evan Chengb98a10e2008-03-24 00:21:34 +00007336 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
7337 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
7338 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
7339 // of the (zext icmp) will be transformed.
7340 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
7341 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
7342 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
7343 (transformZExtICmp(LHS, CI, false) ||
7344 transformZExtICmp(RHS, CI, false))) {
7345 Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
7346 Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
7347 return BinaryOperator::create(Instruction::Or, LCast, RCast);
Chris Lattner66bc3252007-04-11 05:45:39 +00007348 }
Evan Chengb98a10e2008-03-24 00:21:34 +00007349 }
7350
Reid Spencer3da59db2006-11-27 01:05:10 +00007351 return 0;
7352}
7353
Chris Lattner8a9f5712007-04-11 06:57:46 +00007354Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattnerba417832007-04-11 06:12:58 +00007355 if (Instruction *I = commonIntCastTransforms(CI))
7356 return I;
7357
Chris Lattner8a9f5712007-04-11 06:57:46 +00007358 Value *Src = CI.getOperand(0);
7359
7360 // sext (x <s 0) -> ashr x, 31 -> all ones if signed
7361 // sext (x >s -1) -> ashr x, 31 -> all ones if not signed
7362 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
7363 // If we are just checking for a icmp eq of a single bit and zext'ing it
7364 // to an integer, then shift the bit to the appropriate place and then
7365 // cast to integer to avoid the comparison.
7366 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7367 const APInt &Op1CV = Op1C->getValue();
7368
7369 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
7370 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
7371 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7372 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
7373 Value *In = ICI->getOperand(0);
7374 Value *Sh = ConstantInt::get(In->getType(),
7375 In->getType()->getPrimitiveSizeInBits()-1);
7376 In = InsertNewInstBefore(BinaryOperator::createAShr(In, Sh,
Chris Lattnere34e9a22007-04-14 23:32:02 +00007377 In->getName()+".lobit"),
Chris Lattner8a9f5712007-04-11 06:57:46 +00007378 CI);
7379 if (In->getType() != CI.getType())
7380 In = CastInst::createIntegerCast(In, CI.getType(),
7381 true/*SExt*/, "tmp", &CI);
7382
7383 if (ICI->getPredicate() == ICmpInst::ICMP_SGT)
7384 In = InsertNewInstBefore(BinaryOperator::createNot(In,
7385 In->getName()+".not"), CI);
7386
7387 return ReplaceInstUsesWith(CI, In);
7388 }
7389 }
7390 }
7391
Chris Lattnerba417832007-04-11 06:12:58 +00007392 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007393}
7394
Chris Lattnerb7530652008-01-27 05:29:54 +00007395/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
7396/// in the specified FP type without changing its value.
7397static Constant *FitsInFPType(ConstantFP *CFP, const Type *FPTy,
7398 const fltSemantics &Sem) {
7399 APFloat F = CFP->getValueAPF();
7400 if (F.convert(Sem, APFloat::rmNearestTiesToEven) == APFloat::opOK)
7401 return ConstantFP::get(FPTy, F);
7402 return 0;
7403}
7404
7405/// LookThroughFPExtensions - If this is an fp extension instruction, look
7406/// through it until we get the source value.
7407static Value *LookThroughFPExtensions(Value *V) {
7408 if (Instruction *I = dyn_cast<Instruction>(V))
7409 if (I->getOpcode() == Instruction::FPExt)
7410 return LookThroughFPExtensions(I->getOperand(0));
7411
7412 // If this value is a constant, return the constant in the smallest FP type
7413 // that can accurately represent it. This allows us to turn
7414 // (float)((double)X+2.0) into x+2.0f.
7415 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
7416 if (CFP->getType() == Type::PPC_FP128Ty)
7417 return V; // No constant folding of this.
7418 // See if the value can be truncated to float and then reextended.
7419 if (Value *V = FitsInFPType(CFP, Type::FloatTy, APFloat::IEEEsingle))
7420 return V;
7421 if (CFP->getType() == Type::DoubleTy)
7422 return V; // Won't shrink.
7423 if (Value *V = FitsInFPType(CFP, Type::DoubleTy, APFloat::IEEEdouble))
7424 return V;
7425 // Don't try to shrink to various long double types.
7426 }
7427
7428 return V;
7429}
7430
7431Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
7432 if (Instruction *I = commonCastTransforms(CI))
7433 return I;
7434
7435 // If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are
7436 // smaller than the destination type, we can eliminate the truncate by doing
7437 // the add as the smaller type. This applies to add/sub/mul/div as well as
7438 // many builtins (sqrt, etc).
7439 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
7440 if (OpI && OpI->hasOneUse()) {
7441 switch (OpI->getOpcode()) {
7442 default: break;
7443 case Instruction::Add:
7444 case Instruction::Sub:
7445 case Instruction::Mul:
7446 case Instruction::FDiv:
7447 case Instruction::FRem:
7448 const Type *SrcTy = OpI->getType();
7449 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
7450 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
7451 if (LHSTrunc->getType() != SrcTy &&
7452 RHSTrunc->getType() != SrcTy) {
7453 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
7454 // If the source types were both smaller than the destination type of
7455 // the cast, do this xform.
7456 if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
7457 RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
7458 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
7459 CI.getType(), CI);
7460 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
7461 CI.getType(), CI);
7462 return BinaryOperator::create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
7463 }
7464 }
7465 break;
7466 }
7467 }
7468 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007469}
7470
7471Instruction *InstCombiner::visitFPExt(CastInst &CI) {
7472 return commonCastTransforms(CI);
7473}
7474
7475Instruction *InstCombiner::visitFPToUI(CastInst &CI) {
Reid Spencer44c030a2006-11-30 23:13:36 +00007476 return commonCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007477}
7478
7479Instruction *InstCombiner::visitFPToSI(CastInst &CI) {
Reid Spencer44c030a2006-11-30 23:13:36 +00007480 return commonCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007481}
7482
7483Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
7484 return commonCastTransforms(CI);
7485}
7486
7487Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
7488 return commonCastTransforms(CI);
7489}
7490
7491Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007492 return commonPointerCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007493}
7494
Chris Lattnerf9d9e452008-01-08 07:23:51 +00007495Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
7496 if (Instruction *I = commonCastTransforms(CI))
7497 return I;
7498
7499 const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
7500 if (!DestPointee->isSized()) return 0;
7501
7502 // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
7503 ConstantInt *Cst;
7504 Value *X;
7505 if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
7506 m_ConstantInt(Cst)))) {
7507 // If the source and destination operands have the same type, see if this
7508 // is a single-index GEP.
7509 if (X->getType() == CI.getType()) {
7510 // Get the size of the pointee type.
Bill Wendlingb9d4f8d2008-03-14 05:12:19 +00007511 uint64_t Size = TD->getABITypeSize(DestPointee);
Chris Lattnerf9d9e452008-01-08 07:23:51 +00007512
7513 // Convert the constant to intptr type.
7514 APInt Offset = Cst->getValue();
7515 Offset.sextOrTrunc(TD->getPointerSizeInBits());
7516
7517 // If Offset is evenly divisible by Size, we can do this xform.
7518 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7519 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
7520 return new GetElementPtrInst(X, ConstantInt::get(Offset));
7521 }
7522 }
7523 // TODO: Could handle other cases, e.g. where add is indexing into field of
7524 // struct etc.
7525 } else if (CI.getOperand(0)->hasOneUse() &&
7526 match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
7527 // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
7528 // "inttoptr+GEP" instead of "add+intptr".
7529
7530 // Get the size of the pointee type.
7531 uint64_t Size = TD->getABITypeSize(DestPointee);
7532
7533 // Convert the constant to intptr type.
7534 APInt Offset = Cst->getValue();
7535 Offset.sextOrTrunc(TD->getPointerSizeInBits());
7536
7537 // If Offset is evenly divisible by Size, we can do this xform.
7538 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7539 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
7540
7541 Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
7542 "tmp"), CI);
7543 return new GetElementPtrInst(P, ConstantInt::get(Offset), "tmp");
7544 }
7545 }
7546 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007547}
7548
Chris Lattnerd3e28342007-04-27 17:44:50 +00007549Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007550 // If the operands are integer typed then apply the integer transforms,
7551 // otherwise just apply the common ones.
7552 Value *Src = CI.getOperand(0);
7553 const Type *SrcTy = Src->getType();
7554 const Type *DestTy = CI.getType();
7555
Chris Lattner42a75512007-01-15 02:27:26 +00007556 if (SrcTy->isInteger() && DestTy->isInteger()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007557 if (Instruction *Result = commonIntCastTransforms(CI))
7558 return Result;
Chris Lattnerd3e28342007-04-27 17:44:50 +00007559 } else if (isa<PointerType>(SrcTy)) {
7560 if (Instruction *I = commonPointerCastTransforms(CI))
7561 return I;
Reid Spencer3da59db2006-11-27 01:05:10 +00007562 } else {
7563 if (Instruction *Result = commonCastTransforms(CI))
7564 return Result;
7565 }
7566
7567
7568 // Get rid of casts from one type to the same type. These are useless and can
7569 // be replaced by the operand.
7570 if (DestTy == Src->getType())
7571 return ReplaceInstUsesWith(CI, Src);
7572
Reid Spencer3da59db2006-11-27 01:05:10 +00007573 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007574 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
7575 const Type *DstElTy = DstPTy->getElementType();
7576 const Type *SrcElTy = SrcPTy->getElementType();
7577
Nate Begeman83ad90a2008-03-31 00:22:16 +00007578 // If the address spaces don't match, don't eliminate the bitcast, which is
7579 // required for changing types.
7580 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
7581 return 0;
7582
Chris Lattnerd3e28342007-04-27 17:44:50 +00007583 // If we are casting a malloc or alloca to a pointer to a type of the same
7584 // size, rewrite the allocation instruction to allocate the "right" type.
7585 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
7586 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
7587 return V;
7588
Chris Lattnerd717c182007-05-05 22:32:24 +00007589 // If the source and destination are pointers, and this cast is equivalent
7590 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
Chris Lattnerd3e28342007-04-27 17:44:50 +00007591 // This can enhance SROA and other transforms that want type-safe pointers.
7592 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
7593 unsigned NumZeros = 0;
7594 while (SrcElTy != DstElTy &&
7595 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
7596 SrcElTy->getNumContainedTypes() /* not "{}" */) {
7597 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
7598 ++NumZeros;
7599 }
Chris Lattner4e998b22004-09-29 05:07:12 +00007600
Chris Lattnerd3e28342007-04-27 17:44:50 +00007601 // If we found a path from the src to dest, create the getelementptr now.
7602 if (SrcElTy == DstElTy) {
7603 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Chuck Rose IIIc331d302007-09-05 20:36:41 +00007604 return new GetElementPtrInst(Src, Idxs.begin(), Idxs.end(), "",
7605 ((Instruction*) NULL));
Chris Lattner9fb92132006-04-12 18:09:35 +00007606 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007607 }
Chris Lattner24c8e382003-07-24 17:35:25 +00007608
Reid Spencer3da59db2006-11-27 01:05:10 +00007609 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
7610 if (SVI->hasOneUse()) {
7611 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
7612 // a bitconvert to a vector with the same # elts.
Reid Spencer9d6565a2007-02-15 02:26:10 +00007613 if (isa<VectorType>(DestTy) &&
7614 cast<VectorType>(DestTy)->getNumElements() ==
Reid Spencer3da59db2006-11-27 01:05:10 +00007615 SVI->getType()->getNumElements()) {
7616 CastInst *Tmp;
7617 // If either of the operands is a cast from CI.getType(), then
7618 // evaluating the shuffle in the casted destination's type will allow
7619 // us to eliminate at least one cast.
7620 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
7621 Tmp->getOperand(0)->getType() == DestTy) ||
7622 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
7623 Tmp->getOperand(0)->getType() == DestTy)) {
Reid Spencer17212df2006-12-12 09:18:51 +00007624 Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
7625 SVI->getOperand(0), DestTy, &CI);
7626 Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
7627 SVI->getOperand(1), DestTy, &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007628 // Return a new shuffle vector. Use the same element ID's, as we
7629 // know the vector types match #elts.
7630 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner01575b72006-05-25 23:24:33 +00007631 }
7632 }
7633 }
7634 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00007635 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00007636}
7637
Chris Lattnere576b912004-04-09 23:46:01 +00007638/// GetSelectFoldableOperands - We want to turn code that looks like this:
7639/// %C = or %A, %B
7640/// %D = select %cond, %C, %A
7641/// into:
7642/// %C = select %cond, %B, 0
7643/// %D = or %A, %C
7644///
7645/// Assuming that the specified instruction is an operand to the select, return
7646/// a bitmask indicating which operands of this instruction are foldable if they
7647/// equal the other incoming value of the select.
7648///
7649static unsigned GetSelectFoldableOperands(Instruction *I) {
7650 switch (I->getOpcode()) {
7651 case Instruction::Add:
7652 case Instruction::Mul:
7653 case Instruction::And:
7654 case Instruction::Or:
7655 case Instruction::Xor:
7656 return 3; // Can fold through either operand.
7657 case Instruction::Sub: // Can only fold on the amount subtracted.
7658 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencer3822ff52006-11-08 06:47:33 +00007659 case Instruction::LShr:
7660 case Instruction::AShr:
Misha Brukmanfd939082005-04-21 23:48:37 +00007661 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00007662 default:
7663 return 0; // Cannot fold
7664 }
7665}
7666
7667/// GetSelectFoldableConstant - For the same transformation as the previous
7668/// function, return the identity constant that goes into the select.
7669static Constant *GetSelectFoldableConstant(Instruction *I) {
7670 switch (I->getOpcode()) {
7671 default: assert(0 && "This cannot happen!"); abort();
7672 case Instruction::Add:
7673 case Instruction::Sub:
7674 case Instruction::Or:
7675 case Instruction::Xor:
Chris Lattnere576b912004-04-09 23:46:01 +00007676 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00007677 case Instruction::LShr:
7678 case Instruction::AShr:
Reid Spencer832254e2007-02-02 02:16:23 +00007679 return Constant::getNullValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00007680 case Instruction::And:
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00007681 return Constant::getAllOnesValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00007682 case Instruction::Mul:
7683 return ConstantInt::get(I->getType(), 1);
7684 }
7685}
7686
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007687/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
7688/// have the same opcode and only one use each. Try to simplify this.
7689Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
7690 Instruction *FI) {
7691 if (TI->getNumOperands() == 1) {
7692 // If this is a non-volatile load or a cast from the same type,
7693 // merge.
Reid Spencer3da59db2006-11-27 01:05:10 +00007694 if (TI->isCast()) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007695 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
7696 return 0;
7697 } else {
7698 return 0; // unknown unary op.
7699 }
Misha Brukmanfd939082005-04-21 23:48:37 +00007700
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007701 // Fold this by inserting a select from the input values.
7702 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
7703 FI->getOperand(0), SI.getName()+".v");
7704 InsertNewInstBefore(NewSI, SI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007705 return CastInst::create(Instruction::CastOps(TI->getOpcode()), NewSI,
7706 TI->getType());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007707 }
7708
Reid Spencer832254e2007-02-02 02:16:23 +00007709 // Only handle binary operators here.
7710 if (!isa<BinaryOperator>(TI))
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007711 return 0;
7712
7713 // Figure out if the operations have any operands in common.
7714 Value *MatchOp, *OtherOpT, *OtherOpF;
7715 bool MatchIsOpZero;
7716 if (TI->getOperand(0) == FI->getOperand(0)) {
7717 MatchOp = TI->getOperand(0);
7718 OtherOpT = TI->getOperand(1);
7719 OtherOpF = FI->getOperand(1);
7720 MatchIsOpZero = true;
7721 } else if (TI->getOperand(1) == FI->getOperand(1)) {
7722 MatchOp = TI->getOperand(1);
7723 OtherOpT = TI->getOperand(0);
7724 OtherOpF = FI->getOperand(0);
7725 MatchIsOpZero = false;
7726 } else if (!TI->isCommutative()) {
7727 return 0;
7728 } else if (TI->getOperand(0) == FI->getOperand(1)) {
7729 MatchOp = TI->getOperand(0);
7730 OtherOpT = TI->getOperand(1);
7731 OtherOpF = FI->getOperand(0);
7732 MatchIsOpZero = true;
7733 } else if (TI->getOperand(1) == FI->getOperand(0)) {
7734 MatchOp = TI->getOperand(1);
7735 OtherOpT = TI->getOperand(0);
7736 OtherOpF = FI->getOperand(1);
7737 MatchIsOpZero = true;
7738 } else {
7739 return 0;
7740 }
7741
7742 // If we reach here, they do have operations in common.
7743 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
7744 OtherOpF, SI.getName()+".v");
7745 InsertNewInstBefore(NewSI, SI);
7746
7747 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
7748 if (MatchIsOpZero)
7749 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
7750 else
7751 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007752 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00007753 assert(0 && "Shouldn't get here");
7754 return 0;
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007755}
7756
Chris Lattner3d69f462004-03-12 05:52:32 +00007757Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00007758 Value *CondVal = SI.getCondition();
7759 Value *TrueVal = SI.getTrueValue();
7760 Value *FalseVal = SI.getFalseValue();
7761
7762 // select true, X, Y -> X
7763 // select false, X, Y -> Y
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007764 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencer579dca12007-01-12 04:24:46 +00007765 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00007766
7767 // select C, X, X -> X
7768 if (TrueVal == FalseVal)
7769 return ReplaceInstUsesWith(SI, TrueVal);
7770
Chris Lattnere87597f2004-10-16 18:11:37 +00007771 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
7772 return ReplaceInstUsesWith(SI, FalseVal);
7773 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
7774 return ReplaceInstUsesWith(SI, TrueVal);
7775 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
7776 if (isa<Constant>(TrueVal))
7777 return ReplaceInstUsesWith(SI, TrueVal);
7778 else
7779 return ReplaceInstUsesWith(SI, FalseVal);
7780 }
7781
Reid Spencer4fe16d62007-01-11 18:21:29 +00007782 if (SI.getType() == Type::Int1Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00007783 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00007784 if (C->getZExtValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00007785 // Change: A = select B, true, C --> A = or B, C
Chris Lattner48595f12004-06-10 02:07:29 +00007786 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00007787 } else {
7788 // Change: A = select B, false, C --> A = and !B, C
7789 Value *NotCond =
7790 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
7791 "not."+CondVal->getName()), SI);
Chris Lattner48595f12004-06-10 02:07:29 +00007792 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00007793 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00007794 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00007795 if (C->getZExtValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00007796 // Change: A = select B, C, false --> A = and B, C
Chris Lattner48595f12004-06-10 02:07:29 +00007797 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00007798 } else {
7799 // Change: A = select B, C, true --> A = or !B, C
7800 Value *NotCond =
7801 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
7802 "not."+CondVal->getName()), SI);
Chris Lattner48595f12004-06-10 02:07:29 +00007803 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00007804 }
7805 }
Chris Lattnercfa59752007-11-25 21:27:53 +00007806
7807 // select a, b, a -> a&b
7808 // select a, a, b -> a|b
7809 if (CondVal == TrueVal)
7810 return BinaryOperator::createOr(CondVal, FalseVal);
7811 else if (CondVal == FalseVal)
7812 return BinaryOperator::createAnd(CondVal, TrueVal);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007813 }
Chris Lattner0c199a72004-04-08 04:43:23 +00007814
Chris Lattner2eefe512004-04-09 19:05:30 +00007815 // Selecting between two integer constants?
7816 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
7817 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattnerba417832007-04-11 06:12:58 +00007818 // select C, 1, 0 -> zext C to int
Reid Spencer2ec619a2007-03-23 21:24:59 +00007819 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007820 return CastInst::create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer2ec619a2007-03-23 21:24:59 +00007821 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattnerba417832007-04-11 06:12:58 +00007822 // select C, 0, 1 -> zext !C to int
Chris Lattner2eefe512004-04-09 19:05:30 +00007823 Value *NotCond =
7824 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00007825 "not."+CondVal->getName()), SI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007826 return CastInst::create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00007827 }
Chris Lattnerba417832007-04-11 06:12:58 +00007828
7829 // FIXME: Turn select 0/-1 and -1/0 into sext from condition!
Chris Lattner457dd822004-06-09 07:59:58 +00007830
Reid Spencere4d87aa2006-12-23 06:05:41 +00007831 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattnerb8456462006-09-20 04:44:59 +00007832
Reid Spencere4d87aa2006-12-23 06:05:41 +00007833 // (x <s 0) ? -1 : 0 -> ashr x, 31
Reid Spencer2ec619a2007-03-23 21:24:59 +00007834 if (TrueValC->isAllOnesValue() && FalseValC->isZero())
Chris Lattnerb8456462006-09-20 04:44:59 +00007835 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
Chris Lattnerba417832007-04-11 06:12:58 +00007836 if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
Chris Lattnerb8456462006-09-20 04:44:59 +00007837 // The comparison constant and the result are not neccessarily the
Reid Spencer3da59db2006-11-27 01:05:10 +00007838 // same width. Make an all-ones value by inserting a AShr.
Chris Lattnerb8456462006-09-20 04:44:59 +00007839 Value *X = IC->getOperand(0);
Zhou Sheng4351c642007-04-02 08:20:41 +00007840 uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
Reid Spencer832254e2007-02-02 02:16:23 +00007841 Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
7842 Instruction *SRA = BinaryOperator::create(Instruction::AShr, X,
7843 ShAmt, "ones");
Chris Lattnerb8456462006-09-20 04:44:59 +00007844 InsertNewInstBefore(SRA, SI);
7845
Reid Spencer3da59db2006-11-27 01:05:10 +00007846 // Finally, convert to the type of the select RHS. We figure out
7847 // if this requires a SExt, Trunc or BitCast based on the sizes.
7848 Instruction::CastOps opc = Instruction::BitCast;
Zhou Sheng4351c642007-04-02 08:20:41 +00007849 uint32_t SRASize = SRA->getType()->getPrimitiveSizeInBits();
7850 uint32_t SISize = SI.getType()->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00007851 if (SRASize < SISize)
7852 opc = Instruction::SExt;
7853 else if (SRASize > SISize)
7854 opc = Instruction::Trunc;
7855 return CastInst::create(opc, SRA, SI.getType());
Chris Lattnerb8456462006-09-20 04:44:59 +00007856 }
7857 }
7858
7859
7860 // If one of the constants is zero (we know they can't both be) and we
Chris Lattnerba417832007-04-11 06:12:58 +00007861 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattnerb8456462006-09-20 04:44:59 +00007862 // non-constant value, eliminate this whole mess. This corresponds to
7863 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer2ec619a2007-03-23 21:24:59 +00007864 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattner65b72ba2006-09-18 04:22:48 +00007865 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00007866 cast<Constant>(IC->getOperand(1))->isNullValue())
7867 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
7868 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00007869 isa<ConstantInt>(ICA->getOperand(1)) &&
7870 (ICA->getOperand(1) == TrueValC ||
7871 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00007872 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
7873 // Okay, now we know that everything is set up, we just don't
Reid Spencere4d87aa2006-12-23 06:05:41 +00007874 // know whether we have a icmp_ne or icmp_eq and whether the
7875 // true or false val is the zero.
Reid Spencer2ec619a2007-03-23 21:24:59 +00007876 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencere4d87aa2006-12-23 06:05:41 +00007877 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner457dd822004-06-09 07:59:58 +00007878 Value *V = ICA;
7879 if (ShouldNotVal)
7880 V = InsertNewInstBefore(BinaryOperator::create(
7881 Instruction::Xor, V, ICA->getOperand(1)), SI);
7882 return ReplaceInstUsesWith(SI, V);
7883 }
Chris Lattnerb8456462006-09-20 04:44:59 +00007884 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00007885 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00007886
7887 // See if we are selecting two values based on a comparison of the two values.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007888 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
7889 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattnerd76956d2004-04-10 22:21:27 +00007890 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen5a2174f2007-10-03 17:45:27 +00007891 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
7892 // This is not safe in general for floating point:
7893 // consider X== -0, Y== +0.
7894 // It becomes safe if either operand is a nonzero constant.
7895 ConstantFP *CFPt, *CFPf;
7896 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
7897 !CFPt->getValueAPF().isZero()) ||
7898 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
7899 !CFPf->getValueAPF().isZero()))
Chris Lattnerd76956d2004-04-10 22:21:27 +00007900 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen5a2174f2007-10-03 17:45:27 +00007901 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00007902 // Transform (X != Y) ? X : Y -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00007903 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattnerd76956d2004-04-10 22:21:27 +00007904 return ReplaceInstUsesWith(SI, TrueVal);
7905 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7906
Reid Spencere4d87aa2006-12-23 06:05:41 +00007907 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattnerd76956d2004-04-10 22:21:27 +00007908 // Transform (X == Y) ? Y : X -> X
Dale Johannesen5a2174f2007-10-03 17:45:27 +00007909 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
7910 // This is not safe in general for floating point:
7911 // consider X== -0, Y== +0.
7912 // It becomes safe if either operand is a nonzero constant.
7913 ConstantFP *CFPt, *CFPf;
7914 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
7915 !CFPt->getValueAPF().isZero()) ||
7916 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
7917 !CFPf->getValueAPF().isZero()))
7918 return ReplaceInstUsesWith(SI, FalseVal);
7919 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00007920 // Transform (X != Y) ? Y : X -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00007921 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
7922 return ReplaceInstUsesWith(SI, TrueVal);
7923 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7924 }
7925 }
7926
7927 // See if we are selecting two values based on a comparison of the two values.
7928 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
7929 if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
7930 // Transform (X == Y) ? X : Y -> Y
7931 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
7932 return ReplaceInstUsesWith(SI, FalseVal);
7933 // Transform (X != Y) ? X : Y -> X
7934 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
7935 return ReplaceInstUsesWith(SI, TrueVal);
7936 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7937
7938 } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
7939 // Transform (X == Y) ? Y : X -> X
7940 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
7941 return ReplaceInstUsesWith(SI, FalseVal);
7942 // Transform (X != Y) ? Y : X -> Y
7943 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
Chris Lattnerfbede522004-04-11 01:39:19 +00007944 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerd76956d2004-04-10 22:21:27 +00007945 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7946 }
7947 }
Misha Brukmanfd939082005-04-21 23:48:37 +00007948
Chris Lattner87875da2005-01-13 22:52:24 +00007949 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
7950 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
7951 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattner87875da2005-01-13 22:52:24 +00007952 Instruction *AddOp = 0, *SubOp = 0;
7953
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007954 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
7955 if (TI->getOpcode() == FI->getOpcode())
7956 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
7957 return IV;
7958
7959 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
7960 // even legal for FP.
Chris Lattner87875da2005-01-13 22:52:24 +00007961 if (TI->getOpcode() == Instruction::Sub &&
7962 FI->getOpcode() == Instruction::Add) {
7963 AddOp = FI; SubOp = TI;
7964 } else if (FI->getOpcode() == Instruction::Sub &&
7965 TI->getOpcode() == Instruction::Add) {
7966 AddOp = TI; SubOp = FI;
7967 }
7968
7969 if (AddOp) {
7970 Value *OtherAddOp = 0;
7971 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
7972 OtherAddOp = AddOp->getOperand(1);
7973 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
7974 OtherAddOp = AddOp->getOperand(0);
7975 }
7976
7977 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00007978 // So at this point we know we have (Y -> OtherAddOp):
7979 // select C, (add X, Y), (sub X, Z)
7980 Value *NegVal; // Compute -Z
7981 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
7982 NegVal = ConstantExpr::getNeg(C);
7983 } else {
7984 NegVal = InsertNewInstBefore(
7985 BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00007986 }
Chris Lattner97f37a42006-02-24 18:05:58 +00007987
7988 Value *NewTrueOp = OtherAddOp;
7989 Value *NewFalseOp = NegVal;
7990 if (AddOp != TI)
7991 std::swap(NewTrueOp, NewFalseOp);
7992 Instruction *NewSel =
7993 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
7994
7995 NewSel = InsertNewInstBefore(NewSel, SI);
7996 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00007997 }
7998 }
7999 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008000
Chris Lattnere576b912004-04-09 23:46:01 +00008001 // See if we can fold the select into one of our operands.
Chris Lattner42a75512007-01-15 02:27:26 +00008002 if (SI.getType()->isInteger()) {
Chris Lattnere576b912004-04-09 23:46:01 +00008003 // See the comment above GetSelectFoldableOperands for a description of the
8004 // transformation we are doing here.
8005 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
8006 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
8007 !isa<Constant>(FalseVal))
8008 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
8009 unsigned OpToFold = 0;
8010 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
8011 OpToFold = 1;
8012 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
8013 OpToFold = 2;
8014 }
8015
8016 if (OpToFold) {
8017 Constant *C = GetSelectFoldableConstant(TVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008018 Instruction *NewSel =
Chris Lattner6934a042007-02-11 01:23:03 +00008019 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C);
Chris Lattnere576b912004-04-09 23:46:01 +00008020 InsertNewInstBefore(NewSel, SI);
Chris Lattner6934a042007-02-11 01:23:03 +00008021 NewSel->takeName(TVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008022 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
8023 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
Chris Lattnere576b912004-04-09 23:46:01 +00008024 else {
8025 assert(0 && "Unknown instruction!!");
8026 }
8027 }
8028 }
Chris Lattnera96879a2004-09-29 17:40:11 +00008029
Chris Lattnere576b912004-04-09 23:46:01 +00008030 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
8031 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
8032 !isa<Constant>(TrueVal))
8033 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
8034 unsigned OpToFold = 0;
8035 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
8036 OpToFold = 1;
8037 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
8038 OpToFold = 2;
8039 }
8040
8041 if (OpToFold) {
8042 Constant *C = GetSelectFoldableConstant(FVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008043 Instruction *NewSel =
Chris Lattner6934a042007-02-11 01:23:03 +00008044 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold));
Chris Lattnere576b912004-04-09 23:46:01 +00008045 InsertNewInstBefore(NewSel, SI);
Chris Lattner6934a042007-02-11 01:23:03 +00008046 NewSel->takeName(FVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008047 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
8048 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
Reid Spencer832254e2007-02-02 02:16:23 +00008049 else
Chris Lattnere576b912004-04-09 23:46:01 +00008050 assert(0 && "Unknown instruction!!");
Chris Lattnere576b912004-04-09 23:46:01 +00008051 }
8052 }
8053 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00008054
8055 if (BinaryOperator::isNot(CondVal)) {
8056 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
8057 SI.setOperand(1, FalseVal);
8058 SI.setOperand(2, TrueVal);
8059 return &SI;
8060 }
8061
Chris Lattner3d69f462004-03-12 05:52:32 +00008062 return 0;
8063}
8064
Chris Lattnerf2369f22007-08-09 19:05:49 +00008065/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
8066/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
8067/// and it is more than the alignment of the ultimate object, see if we can
8068/// increase the alignment of the ultimate object, making this check succeed.
8069static unsigned GetOrEnforceKnownAlignment(Value *V, TargetData *TD,
8070 unsigned PrefAlign = 0) {
Chris Lattner95a959d2006-03-06 20:18:44 +00008071 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
8072 unsigned Align = GV->getAlignment();
Andrew Lenharthb410df92007-11-08 18:45:15 +00008073 if (Align == 0 && TD && GV->getType()->getElementType()->isSized())
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00008074 Align = TD->getPrefTypeAlignment(GV->getType()->getElementType());
Chris Lattnerf2369f22007-08-09 19:05:49 +00008075
8076 // If there is a large requested alignment and we can, bump up the alignment
8077 // of the global.
8078 if (PrefAlign > Align && GV->hasInitializer()) {
8079 GV->setAlignment(PrefAlign);
8080 Align = PrefAlign;
8081 }
Chris Lattner95a959d2006-03-06 20:18:44 +00008082 return Align;
8083 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
8084 unsigned Align = AI->getAlignment();
8085 if (Align == 0 && TD) {
8086 if (isa<AllocaInst>(AI))
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00008087 Align = TD->getPrefTypeAlignment(AI->getType()->getElementType());
Chris Lattner95a959d2006-03-06 20:18:44 +00008088 else if (isa<MallocInst>(AI)) {
8089 // Malloc returns maximally aligned memory.
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00008090 Align = TD->getABITypeAlignment(AI->getType()->getElementType());
Chris Lattner58092e32007-01-20 22:35:55 +00008091 Align =
8092 std::max(Align,
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00008093 (unsigned)TD->getABITypeAlignment(Type::DoubleTy));
Chris Lattner58092e32007-01-20 22:35:55 +00008094 Align =
8095 std::max(Align,
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00008096 (unsigned)TD->getABITypeAlignment(Type::Int64Ty));
Chris Lattner95a959d2006-03-06 20:18:44 +00008097 }
8098 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00008099
8100 // If there is a requested alignment and if this is an alloca, round up. We
8101 // don't do this for malloc, because some systems can't respect the request.
8102 if (PrefAlign > Align && isa<AllocaInst>(AI)) {
8103 AI->setAlignment(PrefAlign);
8104 Align = PrefAlign;
8105 }
Chris Lattner95a959d2006-03-06 20:18:44 +00008106 return Align;
Reid Spencer3da59db2006-11-27 01:05:10 +00008107 } else if (isa<BitCastInst>(V) ||
Chris Lattner51c26e92006-03-07 01:28:57 +00008108 (isa<ConstantExpr>(V) &&
Reid Spencer3da59db2006-11-27 01:05:10 +00008109 cast<ConstantExpr>(V)->getOpcode() == Instruction::BitCast)) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00008110 return GetOrEnforceKnownAlignment(cast<User>(V)->getOperand(0),
8111 TD, PrefAlign);
Chris Lattner9bc14642007-04-28 00:57:34 +00008112 } else if (User *GEPI = dyn_castGetElementPtr(V)) {
Chris Lattner95a959d2006-03-06 20:18:44 +00008113 // If all indexes are zero, it is just the alignment of the base pointer.
8114 bool AllZeroOperands = true;
8115 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
8116 if (!isa<Constant>(GEPI->getOperand(i)) ||
8117 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
8118 AllZeroOperands = false;
8119 break;
8120 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00008121
8122 if (AllZeroOperands) {
8123 // Treat this like a bitcast.
8124 return GetOrEnforceKnownAlignment(GEPI->getOperand(0), TD, PrefAlign);
8125 }
8126
8127 unsigned BaseAlignment = GetOrEnforceKnownAlignment(GEPI->getOperand(0),TD);
8128 if (BaseAlignment == 0) return 0;
8129
Chris Lattner95a959d2006-03-06 20:18:44 +00008130 // Otherwise, if the base alignment is >= the alignment we expect for the
8131 // base pointer type, then we know that the resultant pointer is aligned at
8132 // least as much as its type requires.
8133 if (!TD) return 0;
8134
8135 const Type *BasePtrTy = GEPI->getOperand(0)->getType();
Chris Lattner58092e32007-01-20 22:35:55 +00008136 const PointerType *PtrTy = cast<PointerType>(BasePtrTy);
Lauro Ramos Venancioc7d11142007-07-31 20:13:21 +00008137 unsigned Align = TD->getABITypeAlignment(PtrTy->getElementType());
8138 if (Align <= BaseAlignment) {
Chris Lattner51c26e92006-03-07 01:28:57 +00008139 const Type *GEPTy = GEPI->getType();
Chris Lattner58092e32007-01-20 22:35:55 +00008140 const PointerType *GEPPtrTy = cast<PointerType>(GEPTy);
Lauro Ramos Venancioc7d11142007-07-31 20:13:21 +00008141 Align = std::min(Align, (unsigned)
8142 TD->getABITypeAlignment(GEPPtrTy->getElementType()));
8143 return Align;
Chris Lattner51c26e92006-03-07 01:28:57 +00008144 }
Chris Lattner95a959d2006-03-06 20:18:44 +00008145 return 0;
8146 }
8147 return 0;
8148}
8149
Chris Lattnerf497b022008-01-13 23:50:23 +00008150Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
8151 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1), TD);
8152 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2), TD);
8153 unsigned MinAlign = std::min(DstAlign, SrcAlign);
8154 unsigned CopyAlign = MI->getAlignment()->getZExtValue();
8155
8156 if (CopyAlign < MinAlign) {
8157 MI->setAlignment(ConstantInt::get(Type::Int32Ty, MinAlign));
8158 return MI;
8159 }
8160
8161 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
8162 // load/store.
8163 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
8164 if (MemOpLength == 0) return 0;
8165
Chris Lattner37ac6082008-01-14 00:28:35 +00008166 // Source and destination pointer types are always "i8*" for intrinsic. See
8167 // if the size is something we can handle with a single primitive load/store.
8168 // A single load+store correctly handles overlapping memory in the memmove
8169 // case.
Chris Lattnerf497b022008-01-13 23:50:23 +00008170 unsigned Size = MemOpLength->getZExtValue();
8171 if (Size == 0 || Size > 8 || (Size&(Size-1)))
Chris Lattner37ac6082008-01-14 00:28:35 +00008172 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattnerf497b022008-01-13 23:50:23 +00008173
Chris Lattner37ac6082008-01-14 00:28:35 +00008174 // Use an integer load+store unless we can find something better.
Chris Lattnerf497b022008-01-13 23:50:23 +00008175 Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
Chris Lattner37ac6082008-01-14 00:28:35 +00008176
8177 // Memcpy forces the use of i8* for the source and destination. That means
8178 // that if you're using memcpy to move one double around, you'll get a cast
8179 // from double* to i8*. We'd much rather use a double load+store rather than
8180 // an i64 load+store, here because this improves the odds that the source or
8181 // dest address will be promotable. See if we can find a better type than the
8182 // integer datatype.
8183 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
8184 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
8185 if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
8186 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
8187 // down through these levels if so.
8188 while (!SrcETy->isFirstClassType()) {
8189 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
8190 if (STy->getNumElements() == 1)
8191 SrcETy = STy->getElementType(0);
8192 else
8193 break;
8194 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
8195 if (ATy->getNumElements() == 1)
8196 SrcETy = ATy->getElementType();
8197 else
8198 break;
8199 } else
8200 break;
8201 }
8202
8203 if (SrcETy->isFirstClassType())
8204 NewPtrTy = PointerType::getUnqual(SrcETy);
8205 }
8206 }
8207
8208
Chris Lattnerf497b022008-01-13 23:50:23 +00008209 // If the memcpy/memmove provides better alignment info than we can
8210 // infer, use it.
8211 SrcAlign = std::max(SrcAlign, CopyAlign);
8212 DstAlign = std::max(DstAlign, CopyAlign);
8213
8214 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
8215 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
Chris Lattner37ac6082008-01-14 00:28:35 +00008216 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
8217 InsertNewInstBefore(L, *MI);
8218 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
8219
8220 // Set the size of the copy to 0, it will be deleted on the next iteration.
8221 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
8222 return MI;
Chris Lattnerf497b022008-01-13 23:50:23 +00008223}
Chris Lattner3d69f462004-03-12 05:52:32 +00008224
Chris Lattner8b0ea312006-01-13 20:11:04 +00008225/// visitCallInst - CallInst simplification. This mostly only handles folding
8226/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
8227/// the heavy lifting.
8228///
Chris Lattner9fe38862003-06-19 17:00:31 +00008229Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattner8b0ea312006-01-13 20:11:04 +00008230 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
8231 if (!II) return visitCallSite(&CI);
8232
Chris Lattner7bcc0e72004-02-28 05:22:00 +00008233 // Intrinsics cannot occur in an invoke, so handle them here instead of in
8234 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00008235 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00008236 bool Changed = false;
8237
8238 // memmove/cpy/set of zero bytes is a noop.
8239 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
8240 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
8241
Chris Lattner35b9e482004-10-12 04:52:52 +00008242 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +00008243 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +00008244 // Replace the instruction with just byte operations. We would
8245 // transform other cases to loads/stores, but we don't know if
8246 // alignment is sufficient.
8247 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00008248 }
8249
Chris Lattner35b9e482004-10-12 04:52:52 +00008250 // If we have a memmove and the source operation is a constant global,
8251 // then the source and dest pointers can't alias, so we can change this
8252 // into a call to memcpy.
Chris Lattnerf497b022008-01-13 23:50:23 +00008253 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00008254 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
8255 if (GVSrc->isConstant()) {
8256 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner6d0339d2008-01-13 22:23:22 +00008257 Intrinsic::ID MemCpyID;
8258 if (CI.getOperand(3)->getType() == Type::Int32Ty)
8259 MemCpyID = Intrinsic::memcpy_i32;
Chris Lattner21959392006-03-03 01:34:17 +00008260 else
Chris Lattner6d0339d2008-01-13 22:23:22 +00008261 MemCpyID = Intrinsic::memcpy_i64;
8262 CI.setOperand(0, Intrinsic::getDeclaration(M, MemCpyID));
Chris Lattner35b9e482004-10-12 04:52:52 +00008263 Changed = true;
8264 }
Chris Lattner95a959d2006-03-06 20:18:44 +00008265 }
Chris Lattner35b9e482004-10-12 04:52:52 +00008266
Chris Lattner95a959d2006-03-06 20:18:44 +00008267 // If we can determine a pointer alignment that is bigger than currently
8268 // set, update the alignment.
8269 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
Chris Lattnerf497b022008-01-13 23:50:23 +00008270 if (Instruction *I = SimplifyMemTransfer(MI))
8271 return I;
Chris Lattner95a959d2006-03-06 20:18:44 +00008272 } else if (isa<MemSetInst>(MI)) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00008273 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest(), TD);
Reid Spencerb83eb642006-10-20 07:07:24 +00008274 if (MI->getAlignment()->getZExtValue() < Alignment) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00008275 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
Chris Lattner95a959d2006-03-06 20:18:44 +00008276 Changed = true;
8277 }
8278 }
8279
Chris Lattner8b0ea312006-01-13 20:11:04 +00008280 if (Changed) return II;
Chris Lattnera728ddc2006-01-13 21:28:09 +00008281 } else {
8282 switch (II->getIntrinsicID()) {
8283 default: break;
Chris Lattner82ed58f2006-04-02 05:30:25 +00008284 case Intrinsic::ppc_altivec_lvx:
8285 case Intrinsic::ppc_altivec_lvxl:
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00008286 case Intrinsic::x86_sse_loadu_ps:
8287 case Intrinsic::x86_sse2_loadu_pd:
8288 case Intrinsic::x86_sse2_loadu_dq:
8289 // Turn PPC lvx -> load if the pointer is known aligned.
8290 // Turn X86 loadups -> load if the pointer is known aligned.
Chris Lattnerf2369f22007-08-09 19:05:49 +00008291 if (GetOrEnforceKnownAlignment(II->getOperand(1), TD, 16) >= 16) {
Chris Lattner6d0339d2008-01-13 22:23:22 +00008292 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
8293 PointerType::getUnqual(II->getType()),
8294 CI);
Chris Lattner82ed58f2006-04-02 05:30:25 +00008295 return new LoadInst(Ptr);
8296 }
8297 break;
8298 case Intrinsic::ppc_altivec_stvx:
8299 case Intrinsic::ppc_altivec_stvxl:
8300 // Turn stvx -> store if the pointer is known aligned.
Chris Lattnerf2369f22007-08-09 19:05:49 +00008301 if (GetOrEnforceKnownAlignment(II->getOperand(2), TD, 16) >= 16) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00008302 const Type *OpPtrTy =
8303 PointerType::getUnqual(II->getOperand(1)->getType());
Chris Lattner6d0339d2008-01-13 22:23:22 +00008304 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
Chris Lattner82ed58f2006-04-02 05:30:25 +00008305 return new StoreInst(II->getOperand(1), Ptr);
8306 }
8307 break;
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00008308 case Intrinsic::x86_sse_storeu_ps:
8309 case Intrinsic::x86_sse2_storeu_pd:
8310 case Intrinsic::x86_sse2_storeu_dq:
8311 case Intrinsic::x86_sse2_storel_dq:
8312 // Turn X86 storeu -> store if the pointer is known aligned.
Chris Lattnerf2369f22007-08-09 19:05:49 +00008313 if (GetOrEnforceKnownAlignment(II->getOperand(1), TD, 16) >= 16) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00008314 const Type *OpPtrTy =
8315 PointerType::getUnqual(II->getOperand(2)->getType());
Chris Lattner6d0339d2008-01-13 22:23:22 +00008316 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00008317 return new StoreInst(II->getOperand(2), Ptr);
8318 }
8319 break;
Chris Lattner867b99f2006-10-05 06:55:50 +00008320
8321 case Intrinsic::x86_sse_cvttss2si: {
8322 // These intrinsics only demands the 0th element of its input vector. If
8323 // we can simplify the input based on that, do so now.
8324 uint64_t UndefElts;
8325 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
8326 UndefElts)) {
8327 II->setOperand(1, V);
8328 return II;
8329 }
8330 break;
8331 }
8332
Chris Lattnere2ed0572006-04-06 19:19:17 +00008333 case Intrinsic::ppc_altivec_vperm:
8334 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
Reid Spencer9d6565a2007-02-15 02:26:10 +00008335 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
Chris Lattnere2ed0572006-04-06 19:19:17 +00008336 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
8337
8338 // Check that all of the elements are integer constants or undefs.
8339 bool AllEltsOk = true;
8340 for (unsigned i = 0; i != 16; ++i) {
8341 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
8342 !isa<UndefValue>(Mask->getOperand(i))) {
8343 AllEltsOk = false;
8344 break;
8345 }
8346 }
8347
8348 if (AllEltsOk) {
8349 // Cast the input vectors to byte vectors.
Chris Lattner6d0339d2008-01-13 22:23:22 +00008350 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
8351 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
Chris Lattnere2ed0572006-04-06 19:19:17 +00008352 Value *Result = UndefValue::get(Op0->getType());
8353
8354 // Only extract each element once.
8355 Value *ExtractedElts[32];
8356 memset(ExtractedElts, 0, sizeof(ExtractedElts));
8357
8358 for (unsigned i = 0; i != 16; ++i) {
8359 if (isa<UndefValue>(Mask->getOperand(i)))
8360 continue;
Chris Lattnere34e9a22007-04-14 23:32:02 +00008361 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
Chris Lattnere2ed0572006-04-06 19:19:17 +00008362 Idx &= 31; // Match the hardware behavior.
8363
8364 if (ExtractedElts[Idx] == 0) {
8365 Instruction *Elt =
Chris Lattner867b99f2006-10-05 06:55:50 +00008366 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00008367 InsertNewInstBefore(Elt, CI);
8368 ExtractedElts[Idx] = Elt;
8369 }
8370
8371 // Insert this value into the result vector.
Chris Lattner867b99f2006-10-05 06:55:50 +00008372 Result = new InsertElementInst(Result, ExtractedElts[Idx], i,"tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00008373 InsertNewInstBefore(cast<Instruction>(Result), CI);
8374 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008375 return CastInst::create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00008376 }
8377 }
8378 break;
8379
Chris Lattnera728ddc2006-01-13 21:28:09 +00008380 case Intrinsic::stackrestore: {
8381 // If the save is right next to the restore, remove the restore. This can
8382 // happen when variable allocas are DCE'd.
8383 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
8384 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
8385 BasicBlock::iterator BI = SS;
8386 if (&*++BI == II)
8387 return EraseInstFromFunction(CI);
8388 }
8389 }
8390
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00008391 // Scan down this block to see if there is another stack restore in the
8392 // same block without an intervening call/alloca.
8393 BasicBlock::iterator BI = II;
Chris Lattnera728ddc2006-01-13 21:28:09 +00008394 TerminatorInst *TI = II->getParent()->getTerminator();
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00008395 bool CannotRemove = false;
8396 for (++BI; &*BI != TI; ++BI) {
8397 if (isa<AllocaInst>(BI)) {
8398 CannotRemove = true;
8399 break;
8400 }
8401 if (isa<CallInst>(BI)) {
8402 if (!isa<IntrinsicInst>(BI)) {
Chris Lattnera728ddc2006-01-13 21:28:09 +00008403 CannotRemove = true;
8404 break;
8405 }
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00008406 // If there is a stackrestore below this one, remove this one.
Chris Lattnera728ddc2006-01-13 21:28:09 +00008407 return EraseInstFromFunction(CI);
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00008408 }
Chris Lattnera728ddc2006-01-13 21:28:09 +00008409 }
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00008410
8411 // If the stack restore is in a return/unwind block and if there are no
8412 // allocas or calls between the restore and the return, nuke the restore.
8413 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
8414 return EraseInstFromFunction(CI);
Chris Lattnera728ddc2006-01-13 21:28:09 +00008415 break;
8416 }
8417 }
Chris Lattner35b9e482004-10-12 04:52:52 +00008418 }
8419
Chris Lattner8b0ea312006-01-13 20:11:04 +00008420 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +00008421}
8422
8423// InvokeInst simplification
8424//
8425Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +00008426 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +00008427}
8428
Chris Lattnera44d8a22003-10-07 22:32:43 +00008429// visitCallSite - Improvements for call and invoke instructions.
8430//
8431Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +00008432 bool Changed = false;
8433
8434 // If the callee is a constexpr cast of a function, attempt to move the cast
8435 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +00008436 if (transformConstExprCastCall(CS)) return 0;
8437
Chris Lattner6c266db2003-10-07 22:54:13 +00008438 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +00008439
Chris Lattner08b22ec2005-05-13 07:09:09 +00008440 if (Function *CalleeF = dyn_cast<Function>(Callee))
8441 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
8442 Instruction *OldCall = CS.getInstruction();
8443 // If the call and callee calling conventions don't match, this call must
8444 // be unreachable, as the call is undefined.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008445 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00008446 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
8447 OldCall);
Chris Lattner08b22ec2005-05-13 07:09:09 +00008448 if (!OldCall->use_empty())
8449 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
8450 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
8451 return EraseInstFromFunction(*OldCall);
8452 return 0;
8453 }
8454
Chris Lattner17be6352004-10-18 02:59:09 +00008455 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
8456 // This instruction is not reachable, just remove it. We insert a store to
8457 // undef so that we know that this code is not reachable, despite the fact
8458 // that we can't modify the CFG here.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008459 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00008460 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
Chris Lattner17be6352004-10-18 02:59:09 +00008461 CS.getInstruction());
8462
8463 if (!CS.getInstruction()->use_empty())
8464 CS.getInstruction()->
8465 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
8466
8467 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
8468 // Don't break the CFG, insert a dummy cond branch.
8469 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008470 ConstantInt::getTrue(), II);
Chris Lattnere87597f2004-10-16 18:11:37 +00008471 }
Chris Lattner17be6352004-10-18 02:59:09 +00008472 return EraseInstFromFunction(*CS.getInstruction());
8473 }
Chris Lattnere87597f2004-10-16 18:11:37 +00008474
Duncan Sandscdb6d922007-09-17 10:26:40 +00008475 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
8476 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
8477 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
8478 return transformCallThroughTrampoline(CS);
8479
Chris Lattner6c266db2003-10-07 22:54:13 +00008480 const PointerType *PTy = cast<PointerType>(Callee->getType());
8481 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
8482 if (FTy->isVarArg()) {
8483 // See if we can optimize any arguments passed through the varargs area of
8484 // the call.
8485 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
8486 E = CS.arg_end(); I != E; ++I)
8487 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
8488 // If this cast does not effect the value passed through the varargs
8489 // area, we can eliminate the use of the cast.
8490 Value *Op = CI->getOperand(0);
Reid Spencer3da59db2006-11-27 01:05:10 +00008491 if (CI->isLosslessCast()) {
Chris Lattner6c266db2003-10-07 22:54:13 +00008492 *I = Op;
8493 Changed = true;
8494 }
8495 }
8496 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008497
Duncan Sandsf0c33542007-12-19 21:13:37 +00008498 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sandsece2c042007-12-16 15:51:49 +00008499 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsf0c33542007-12-19 21:13:37 +00008500 CS.setDoesNotThrow();
Duncan Sandsece2c042007-12-16 15:51:49 +00008501 Changed = true;
8502 }
8503
Chris Lattner6c266db2003-10-07 22:54:13 +00008504 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +00008505}
8506
Chris Lattner9fe38862003-06-19 17:00:31 +00008507// transformConstExprCastCall - If the callee is a constexpr cast of a function,
8508// attempt to move the cast to the arguments of the call/invoke.
8509//
8510bool InstCombiner::transformConstExprCastCall(CallSite CS) {
8511 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
8512 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +00008513 if (CE->getOpcode() != Instruction::BitCast ||
8514 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +00008515 return false;
Reid Spencer8863f182004-07-18 00:38:32 +00008516 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +00008517 Instruction *Caller = CS.getInstruction();
Chris Lattner58d74912008-03-12 17:45:29 +00008518 const PAListPtr &CallerPAL = CS.getParamAttrs();
Chris Lattner9fe38862003-06-19 17:00:31 +00008519
8520 // Okay, this is a cast from a function to a different type. Unless doing so
8521 // would cause a type conversion of one of our arguments, change this call to
8522 // be a direct call with arguments casted to the appropriate types.
8523 //
8524 const FunctionType *FT = Callee->getFunctionType();
8525 const Type *OldRetTy = Caller->getType();
8526
Devang Patel75e6f022008-03-11 18:04:06 +00008527 if (isa<StructType>(FT->getReturnType()))
8528 return false; // TODO: Handle multiple return values.
8529
Chris Lattnerf78616b2004-01-14 06:06:08 +00008530 // Check to see if we are changing the return type...
8531 if (OldRetTy != FT->getReturnType()) {
Reid Spencer5cbf9852007-01-30 20:08:39 +00008532 if (Callee->isDeclaration() && !Caller->use_empty() &&
Chris Lattner46013f42007-01-06 19:53:32 +00008533 // Conversion is ok if changing from pointer to int of same size.
8534 !(isa<PointerType>(FT->getReturnType()) &&
8535 TD->getIntPtrType() == OldRetTy))
Chris Lattnerec479922007-01-06 02:09:32 +00008536 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +00008537
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008538 if (!Caller->use_empty() &&
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008539 // void -> non-void is handled specially
Duncan Sandse1e520f2008-01-13 08:02:44 +00008540 FT->getReturnType() != Type::VoidTy &&
8541 !CastInst::isCastable(FT->getReturnType(), OldRetTy))
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008542 return false; // Cannot transform this return value.
8543
Chris Lattner58d74912008-03-12 17:45:29 +00008544 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
8545 ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
Duncan Sands6c3470e2008-01-07 17:16:06 +00008546 if (RAttrs & ParamAttr::typeIncompatible(FT->getReturnType()))
8547 return false; // Attribute not compatible with transformed value.
8548 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008549
Chris Lattnerf78616b2004-01-14 06:06:08 +00008550 // If the callsite is an invoke instruction, and the return value is used by
8551 // a PHI node in a successor, we cannot change the return type of the call
8552 // because there is no place to put the cast instruction (without breaking
8553 // the critical edge). Bail out in this case.
8554 if (!Caller->use_empty())
8555 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
8556 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
8557 UI != E; ++UI)
8558 if (PHINode *PN = dyn_cast<PHINode>(*UI))
8559 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00008560 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +00008561 return false;
8562 }
Chris Lattner9fe38862003-06-19 17:00:31 +00008563
8564 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
8565 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +00008566
Chris Lattner9fe38862003-06-19 17:00:31 +00008567 CallSite::arg_iterator AI = CS.arg_begin();
8568 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
8569 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +00008570 const Type *ActTy = (*AI)->getType();
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008571
8572 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008573 return false; // Cannot transform this parameter value.
8574
Chris Lattner58d74912008-03-12 17:45:29 +00008575 if (CallerPAL.getParamAttrs(i + 1) & ParamAttr::typeIncompatible(ParamTy))
8576 return false; // Attribute not compatible with transformed value.
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008577
Reid Spencer3da59db2006-11-27 01:05:10 +00008578 ConstantInt *c = dyn_cast<ConstantInt>(*AI);
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008579 // Some conversions are safe even if we do not have a body.
8580 // Either we can cast directly, or we can upconvert the argument
Chris Lattnerec479922007-01-06 02:09:32 +00008581 bool isConvertible = ActTy == ParamTy ||
Chris Lattner46013f42007-01-06 19:53:32 +00008582 (isa<PointerType>(ParamTy) && isa<PointerType>(ActTy)) ||
Chris Lattner42a75512007-01-15 02:27:26 +00008583 (ParamTy->isInteger() && ActTy->isInteger() &&
Reid Spencerabaa8ca2007-01-08 16:32:00 +00008584 ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()) ||
8585 (c && ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()
Zhou Sheng0fc50952007-03-25 05:01:29 +00008586 && c->getValue().isStrictlyPositive());
Reid Spencer5cbf9852007-01-30 20:08:39 +00008587 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +00008588 }
8589
8590 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +00008591 Callee->isDeclaration())
Chris Lattner58d74912008-03-12 17:45:29 +00008592 return false; // Do not delete arguments unless we have a function body.
Chris Lattner9fe38862003-06-19 17:00:31 +00008593
Chris Lattner58d74912008-03-12 17:45:29 +00008594 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
8595 !CallerPAL.isEmpty())
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008596 // In this case we have more arguments than the new function type, but we
Duncan Sandse1e520f2008-01-13 08:02:44 +00008597 // won't be dropping them. Check that these extra arguments have attributes
8598 // that are compatible with being a vararg call argument.
Chris Lattner58d74912008-03-12 17:45:29 +00008599 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
8600 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sandse1e520f2008-01-13 08:02:44 +00008601 break;
Chris Lattner58d74912008-03-12 17:45:29 +00008602 ParameterAttributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Duncan Sandse1e520f2008-01-13 08:02:44 +00008603 if (PAttrs & ParamAttr::VarArgsIncompatible)
8604 return false;
8605 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008606
Chris Lattner9fe38862003-06-19 17:00:31 +00008607 // Okay, we decided that this is a safe thing to do: go ahead and start
8608 // inserting cast instructions as necessary...
8609 std::vector<Value*> Args;
8610 Args.reserve(NumActualArgs);
Chris Lattner58d74912008-03-12 17:45:29 +00008611 SmallVector<ParamAttrsWithIndex, 8> attrVec;
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008612 attrVec.reserve(NumCommonArgs);
8613
8614 // Get any return attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00008615 ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008616
8617 // If the return value is not being used, the type may not be compatible
8618 // with the existing attributes. Wipe out any problematic attributes.
Duncan Sands6c3470e2008-01-07 17:16:06 +00008619 RAttrs &= ~ParamAttr::typeIncompatible(FT->getReturnType());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008620
8621 // Add the new return attributes.
8622 if (RAttrs)
8623 attrVec.push_back(ParamAttrsWithIndex::get(0, RAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +00008624
8625 AI = CS.arg_begin();
8626 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
8627 const Type *ParamTy = FT->getParamType(i);
8628 if ((*AI)->getType() == ParamTy) {
8629 Args.push_back(*AI);
8630 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +00008631 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +00008632 false, ParamTy, false);
Reid Spencer8a903db2006-12-18 08:47:13 +00008633 CastInst *NewCast = CastInst::create(opcode, *AI, ParamTy, "tmp");
Reid Spencer3da59db2006-11-27 01:05:10 +00008634 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner9fe38862003-06-19 17:00:31 +00008635 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008636
8637 // Add any parameter attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00008638 if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008639 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +00008640 }
8641
8642 // If the function takes more arguments than the call was taking, add them
8643 // now...
8644 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
8645 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
8646
8647 // If we are removing arguments to the function, emit an obnoxious warning...
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00008648 if (FT->getNumParams() < NumActualArgs) {
Chris Lattner9fe38862003-06-19 17:00:31 +00008649 if (!FT->isVarArg()) {
Bill Wendlinge8156192006-12-07 01:30:32 +00008650 cerr << "WARNING: While resolving call to function '"
8651 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +00008652 } else {
8653 // Add all of the arguments in their promoted form to the arg list...
8654 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
8655 const Type *PTy = getPromotedType((*AI)->getType());
8656 if (PTy != (*AI)->getType()) {
8657 // Must promote to pass through va_arg area!
Reid Spencerc5b206b2006-12-31 05:48:39 +00008658 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
8659 PTy, false);
Reid Spencer8a903db2006-12-18 08:47:13 +00008660 Instruction *Cast = CastInst::create(opcode, *AI, PTy, "tmp");
Chris Lattner9fe38862003-06-19 17:00:31 +00008661 InsertNewInstBefore(Cast, *Caller);
8662 Args.push_back(Cast);
8663 } else {
8664 Args.push_back(*AI);
8665 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008666
Duncan Sandse1e520f2008-01-13 08:02:44 +00008667 // Add any parameter attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00008668 if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
Duncan Sandse1e520f2008-01-13 08:02:44 +00008669 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
8670 }
Chris Lattner9fe38862003-06-19 17:00:31 +00008671 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00008672 }
Chris Lattner9fe38862003-06-19 17:00:31 +00008673
8674 if (FT->getReturnType() == Type::VoidTy)
Chris Lattner6934a042007-02-11 01:23:03 +00008675 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +00008676
Chris Lattner58d74912008-03-12 17:45:29 +00008677 const PAListPtr &NewCallerPAL = PAListPtr::get(attrVec.begin(),attrVec.end());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008678
Chris Lattner9fe38862003-06-19 17:00:31 +00008679 Instruction *NC;
8680 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00008681 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
David Greenef1355a52007-08-27 19:04:21 +00008682 Args.begin(), Args.end(), Caller->getName(), Caller);
Reid Spencered3fa852007-07-30 19:53:57 +00008683 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008684 cast<InvokeInst>(NC)->setParamAttrs(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +00008685 } else {
Chris Lattner684b22d2007-08-02 16:53:43 +00008686 NC = new CallInst(Callee, Args.begin(), Args.end(),
8687 Caller->getName(), Caller);
Duncan Sandsdc024672007-11-27 13:23:08 +00008688 CallInst *CI = cast<CallInst>(Caller);
8689 if (CI->isTailCall())
Chris Lattnera9e92112005-05-06 06:48:21 +00008690 cast<CallInst>(NC)->setTailCall();
Duncan Sandsdc024672007-11-27 13:23:08 +00008691 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008692 cast<CallInst>(NC)->setParamAttrs(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +00008693 }
8694
Chris Lattner6934a042007-02-11 01:23:03 +00008695 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +00008696 Value *NV = NC;
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008697 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Chris Lattner9fe38862003-06-19 17:00:31 +00008698 if (NV->getType() != Type::VoidTy) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00008699 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008700 OldRetTy, false);
8701 NV = NC = CastInst::create(opcode, NC, OldRetTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +00008702
8703 // If this is an invoke instruction, we should insert it after the first
8704 // non-phi, instruction in the normal successor block.
8705 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
8706 BasicBlock::iterator I = II->getNormalDest()->begin();
8707 while (isa<PHINode>(I)) ++I;
8708 InsertNewInstBefore(NC, *I);
8709 } else {
8710 // Otherwise, it's a call, just insert cast right after the call instr
8711 InsertNewInstBefore(NC, *Caller);
8712 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00008713 AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00008714 } else {
Chris Lattnerc30bda72004-10-17 21:22:38 +00008715 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +00008716 }
8717 }
8718
8719 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
8720 Caller->replaceAllUsesWith(NV);
Chris Lattnerf22a5c62007-03-02 19:59:19 +00008721 Caller->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +00008722 RemoveFromWorkList(Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00008723 return true;
8724}
8725
Duncan Sandscdb6d922007-09-17 10:26:40 +00008726// transformCallThroughTrampoline - Turn a call to a function created by the
8727// init_trampoline intrinsic into a direct call to the underlying function.
8728//
8729Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
8730 Value *Callee = CS.getCalledValue();
8731 const PointerType *PTy = cast<PointerType>(Callee->getType());
8732 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Chris Lattner58d74912008-03-12 17:45:29 +00008733 const PAListPtr &Attrs = CS.getParamAttrs();
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008734
8735 // If the call already has the 'nest' attribute somewhere then give up -
8736 // otherwise 'nest' would occur twice after splicing in the chain.
Chris Lattner58d74912008-03-12 17:45:29 +00008737 if (Attrs.hasAttrSomewhere(ParamAttr::Nest))
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008738 return 0;
Duncan Sandscdb6d922007-09-17 10:26:40 +00008739
8740 IntrinsicInst *Tramp =
8741 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
8742
8743 Function *NestF =
8744 cast<Function>(IntrinsicInst::StripPointerCasts(Tramp->getOperand(2)));
8745 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
8746 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
8747
Chris Lattner58d74912008-03-12 17:45:29 +00008748 const PAListPtr &NestAttrs = NestF->getParamAttrs();
8749 if (!NestAttrs.isEmpty()) {
Duncan Sandscdb6d922007-09-17 10:26:40 +00008750 unsigned NestIdx = 1;
8751 const Type *NestTy = 0;
Dale Johannesen0d51e7e2008-02-19 21:38:47 +00008752 ParameterAttributes NestAttr = ParamAttr::None;
Duncan Sandscdb6d922007-09-17 10:26:40 +00008753
8754 // Look for a parameter marked with the 'nest' attribute.
8755 for (FunctionType::param_iterator I = NestFTy->param_begin(),
8756 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Chris Lattner58d74912008-03-12 17:45:29 +00008757 if (NestAttrs.paramHasAttr(NestIdx, ParamAttr::Nest)) {
Duncan Sandscdb6d922007-09-17 10:26:40 +00008758 // Record the parameter type and any other attributes.
8759 NestTy = *I;
Chris Lattner58d74912008-03-12 17:45:29 +00008760 NestAttr = NestAttrs.getParamAttrs(NestIdx);
Duncan Sandscdb6d922007-09-17 10:26:40 +00008761 break;
8762 }
8763
8764 if (NestTy) {
8765 Instruction *Caller = CS.getInstruction();
8766 std::vector<Value*> NewArgs;
8767 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
8768
Chris Lattner58d74912008-03-12 17:45:29 +00008769 SmallVector<ParamAttrsWithIndex, 8> NewAttrs;
8770 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008771
Duncan Sandscdb6d922007-09-17 10:26:40 +00008772 // Insert the nest argument into the call argument list, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008773 // mean appending it. Likewise for attributes.
8774
8775 // Add any function result attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00008776 if (ParameterAttributes Attr = Attrs.getParamAttrs(0))
8777 NewAttrs.push_back(ParamAttrsWithIndex::get(0, Attr));
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008778
Duncan Sandscdb6d922007-09-17 10:26:40 +00008779 {
8780 unsigned Idx = 1;
8781 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
8782 do {
8783 if (Idx == NestIdx) {
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008784 // Add the chain argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +00008785 Value *NestVal = Tramp->getOperand(3);
8786 if (NestVal->getType() != NestTy)
8787 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
8788 NewArgs.push_back(NestVal);
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008789 NewAttrs.push_back(ParamAttrsWithIndex::get(NestIdx, NestAttr));
Duncan Sandscdb6d922007-09-17 10:26:40 +00008790 }
8791
8792 if (I == E)
8793 break;
8794
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008795 // Add the original argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +00008796 NewArgs.push_back(*I);
Chris Lattner58d74912008-03-12 17:45:29 +00008797 if (ParameterAttributes Attr = Attrs.getParamAttrs(Idx))
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008798 NewAttrs.push_back
8799 (ParamAttrsWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sandscdb6d922007-09-17 10:26:40 +00008800
8801 ++Idx, ++I;
8802 } while (1);
8803 }
8804
8805 // The trampoline may have been bitcast to a bogus type (FTy).
8806 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008807 // with the chain parameter inserted.
Duncan Sandscdb6d922007-09-17 10:26:40 +00008808
Duncan Sandscdb6d922007-09-17 10:26:40 +00008809 std::vector<const Type*> NewTypes;
Duncan Sandscdb6d922007-09-17 10:26:40 +00008810 NewTypes.reserve(FTy->getNumParams()+1);
8811
Duncan Sandscdb6d922007-09-17 10:26:40 +00008812 // Insert the chain's type into the list of parameter types, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008813 // mean appending it.
Duncan Sandscdb6d922007-09-17 10:26:40 +00008814 {
8815 unsigned Idx = 1;
8816 FunctionType::param_iterator I = FTy->param_begin(),
8817 E = FTy->param_end();
8818
8819 do {
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008820 if (Idx == NestIdx)
8821 // Add the chain's type.
Duncan Sandscdb6d922007-09-17 10:26:40 +00008822 NewTypes.push_back(NestTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +00008823
8824 if (I == E)
8825 break;
8826
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008827 // Add the original type.
Duncan Sandscdb6d922007-09-17 10:26:40 +00008828 NewTypes.push_back(*I);
Duncan Sandscdb6d922007-09-17 10:26:40 +00008829
8830 ++Idx, ++I;
8831 } while (1);
8832 }
8833
8834 // Replace the trampoline call with a direct call. Let the generic
8835 // code sort out any function type mismatches.
8836 FunctionType *NewFTy =
Duncan Sandsdc024672007-11-27 13:23:08 +00008837 FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
Christopher Lamb43ad6b32007-12-17 01:12:55 +00008838 Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
8839 NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
Chris Lattner58d74912008-03-12 17:45:29 +00008840 const PAListPtr &NewPAL = PAListPtr::get(NewAttrs.begin(),NewAttrs.end());
Duncan Sandscdb6d922007-09-17 10:26:40 +00008841
8842 Instruction *NewCaller;
8843 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
8844 NewCaller = new InvokeInst(NewCallee,
8845 II->getNormalDest(), II->getUnwindDest(),
8846 NewArgs.begin(), NewArgs.end(),
8847 Caller->getName(), Caller);
8848 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Duncan Sandsdc024672007-11-27 13:23:08 +00008849 cast<InvokeInst>(NewCaller)->setParamAttrs(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +00008850 } else {
8851 NewCaller = new CallInst(NewCallee, NewArgs.begin(), NewArgs.end(),
8852 Caller->getName(), Caller);
8853 if (cast<CallInst>(Caller)->isTailCall())
8854 cast<CallInst>(NewCaller)->setTailCall();
8855 cast<CallInst>(NewCaller)->
8856 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Duncan Sandsdc024672007-11-27 13:23:08 +00008857 cast<CallInst>(NewCaller)->setParamAttrs(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +00008858 }
8859 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
8860 Caller->replaceAllUsesWith(NewCaller);
8861 Caller->eraseFromParent();
8862 RemoveFromWorkList(Caller);
8863 return 0;
8864 }
8865 }
8866
8867 // Replace the trampoline call with a direct call. Since there is no 'nest'
8868 // parameter, there is no need to adjust the argument list. Let the generic
8869 // code sort out any function type mismatches.
8870 Constant *NewCallee =
8871 NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
8872 CS.setCalledFunction(NewCallee);
8873 return CS.getInstruction();
8874}
8875
Chris Lattner7da52b22006-11-01 04:51:18 +00008876/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
8877/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
8878/// and a single binop.
8879Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
8880 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Reid Spencer832254e2007-02-02 02:16:23 +00008881 assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
8882 isa<CmpInst>(FirstInst));
Chris Lattner7da52b22006-11-01 04:51:18 +00008883 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00008884 Value *LHSVal = FirstInst->getOperand(0);
8885 Value *RHSVal = FirstInst->getOperand(1);
8886
8887 const Type *LHSType = LHSVal->getType();
8888 const Type *RHSType = RHSVal->getType();
Chris Lattner7da52b22006-11-01 04:51:18 +00008889
8890 // Scan to see if all operands are the same opcode, all have one use, and all
8891 // kill their operands (i.e. the operands have one use).
Chris Lattnera90a24c2006-11-01 04:55:47 +00008892 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
Chris Lattner7da52b22006-11-01 04:51:18 +00008893 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnera90a24c2006-11-01 04:55:47 +00008894 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00008895 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattner9c080502006-11-01 07:43:41 +00008896 // types or GEP's with different index types.
8897 I->getOperand(0)->getType() != LHSType ||
8898 I->getOperand(1)->getType() != RHSType)
Chris Lattner7da52b22006-11-01 04:51:18 +00008899 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +00008900
8901 // If they are CmpInst instructions, check their predicates
8902 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
8903 if (cast<CmpInst>(I)->getPredicate() !=
8904 cast<CmpInst>(FirstInst)->getPredicate())
8905 return 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00008906
8907 // Keep track of which operand needs a phi node.
8908 if (I->getOperand(0) != LHSVal) LHSVal = 0;
8909 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattner7da52b22006-11-01 04:51:18 +00008910 }
8911
Chris Lattner53738a42006-11-08 19:42:28 +00008912 // Otherwise, this is safe to transform, determine if it is profitable.
8913
8914 // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
8915 // Indexes are often folded into load/store instructions, so we don't want to
8916 // hide them behind a phi.
8917 if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
8918 return 0;
8919
Chris Lattner7da52b22006-11-01 04:51:18 +00008920 Value *InLHS = FirstInst->getOperand(0);
Chris Lattner7da52b22006-11-01 04:51:18 +00008921 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner53738a42006-11-08 19:42:28 +00008922 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00008923 if (LHSVal == 0) {
8924 NewLHS = new PHINode(LHSType, FirstInst->getOperand(0)->getName()+".pn");
8925 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
8926 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +00008927 InsertNewInstBefore(NewLHS, PN);
8928 LHSVal = NewLHS;
8929 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00008930
8931 if (RHSVal == 0) {
8932 NewRHS = new PHINode(RHSType, FirstInst->getOperand(1)->getName()+".pn");
8933 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
8934 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +00008935 InsertNewInstBefore(NewRHS, PN);
8936 RHSVal = NewRHS;
8937 }
8938
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00008939 // Add all operands to the new PHIs.
8940 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
8941 if (NewLHS) {
8942 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
8943 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
8944 }
8945 if (NewRHS) {
8946 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
8947 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
8948 }
8949 }
8950
Chris Lattner7da52b22006-11-01 04:51:18 +00008951 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattner9c080502006-11-01 07:43:41 +00008952 return BinaryOperator::create(BinOp->getOpcode(), LHSVal, RHSVal);
Reid Spencere4d87aa2006-12-23 06:05:41 +00008953 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
8954 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
8955 RHSVal);
Chris Lattner9c080502006-11-01 07:43:41 +00008956 else {
8957 assert(isa<GetElementPtrInst>(FirstInst));
8958 return new GetElementPtrInst(LHSVal, RHSVal);
8959 }
Chris Lattner7da52b22006-11-01 04:51:18 +00008960}
8961
Chris Lattner76c73142006-11-01 07:13:54 +00008962/// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
8963/// of the block that defines it. This means that it must be obvious the value
8964/// of the load is not changed from the point of the load to the end of the
8965/// block it is in.
Chris Lattnerfd905ca2007-02-01 22:30:07 +00008966///
8967/// Finally, it is safe, but not profitable, to sink a load targetting a
8968/// non-address-taken alloca. Doing so will cause us to not promote the alloca
8969/// to a register.
Chris Lattner76c73142006-11-01 07:13:54 +00008970static bool isSafeToSinkLoad(LoadInst *L) {
8971 BasicBlock::iterator BBI = L, E = L->getParent()->end();
8972
8973 for (++BBI; BBI != E; ++BBI)
8974 if (BBI->mayWriteToMemory())
8975 return false;
Chris Lattnerfd905ca2007-02-01 22:30:07 +00008976
8977 // Check for non-address taken alloca. If not address-taken already, it isn't
8978 // profitable to do this xform.
8979 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
8980 bool isAddressTaken = false;
8981 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
8982 UI != E; ++UI) {
8983 if (isa<LoadInst>(UI)) continue;
8984 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
8985 // If storing TO the alloca, then the address isn't taken.
8986 if (SI->getOperand(1) == AI) continue;
8987 }
8988 isAddressTaken = true;
8989 break;
8990 }
8991
8992 if (!isAddressTaken)
8993 return false;
8994 }
8995
Chris Lattner76c73142006-11-01 07:13:54 +00008996 return true;
8997}
8998
Chris Lattner9fe38862003-06-19 17:00:31 +00008999
Chris Lattnerbac32862004-11-14 19:13:23 +00009000// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
9001// operator and they all are only used by the PHI, PHI together their
9002// inputs, and do the operation once, to the result of the PHI.
9003Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
9004 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
9005
9006 // Scan the instruction, looking for input operations that can be folded away.
9007 // If all input operands to the phi are the same instruction (e.g. a cast from
9008 // the same type or "+42") we can pull the operation through the PHI, reducing
9009 // code size and simplifying code.
9010 Constant *ConstantOp = 0;
9011 const Type *CastSrcTy = 0;
Chris Lattner76c73142006-11-01 07:13:54 +00009012 bool isVolatile = false;
Chris Lattnerbac32862004-11-14 19:13:23 +00009013 if (isa<CastInst>(FirstInst)) {
9014 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer832254e2007-02-02 02:16:23 +00009015 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00009016 // Can fold binop, compare or shift here if the RHS is a constant,
9017 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattnerbac32862004-11-14 19:13:23 +00009018 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattner7da52b22006-11-01 04:51:18 +00009019 if (ConstantOp == 0)
9020 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner76c73142006-11-01 07:13:54 +00009021 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
9022 isVolatile = LI->isVolatile();
9023 // We can't sink the load if the loaded value could be modified between the
9024 // load and the PHI.
9025 if (LI->getParent() != PN.getIncomingBlock(0) ||
9026 !isSafeToSinkLoad(LI))
9027 return 0;
Chris Lattner9c080502006-11-01 07:43:41 +00009028 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner53738a42006-11-08 19:42:28 +00009029 if (FirstInst->getNumOperands() == 2)
Chris Lattner9c080502006-11-01 07:43:41 +00009030 return FoldPHIArgBinOpIntoPHI(PN);
9031 // Can't handle general GEPs yet.
9032 return 0;
Chris Lattnerbac32862004-11-14 19:13:23 +00009033 } else {
9034 return 0; // Cannot fold this operation.
9035 }
9036
9037 // Check to see if all arguments are the same operation.
9038 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9039 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
9040 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencere4d87aa2006-12-23 06:05:41 +00009041 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattnerbac32862004-11-14 19:13:23 +00009042 return 0;
9043 if (CastSrcTy) {
9044 if (I->getOperand(0)->getType() != CastSrcTy)
9045 return 0; // Cast operation must match.
Chris Lattner76c73142006-11-01 07:13:54 +00009046 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00009047 // We can't sink the load if the loaded value could be modified between
9048 // the load and the PHI.
Chris Lattner76c73142006-11-01 07:13:54 +00009049 if (LI->isVolatile() != isVolatile ||
9050 LI->getParent() != PN.getIncomingBlock(i) ||
9051 !isSafeToSinkLoad(LI))
9052 return 0;
Chris Lattnerbac32862004-11-14 19:13:23 +00009053 } else if (I->getOperand(1) != ConstantOp) {
9054 return 0;
9055 }
9056 }
9057
9058 // Okay, they are all the same operation. Create a new PHI node of the
9059 // correct type, and PHI together all of the LHS's of the instructions.
9060 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
9061 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +00009062 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +00009063
9064 Value *InVal = FirstInst->getOperand(0);
9065 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00009066
9067 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +00009068 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9069 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9070 if (NewInVal != InVal)
9071 InVal = 0;
9072 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
9073 }
9074
9075 Value *PhiVal;
9076 if (InVal) {
9077 // The new PHI unions all of the same values together. This is really
9078 // common, so we handle it intelligently here for compile-time speed.
9079 PhiVal = InVal;
9080 delete NewPN;
9081 } else {
9082 InsertNewInstBefore(NewPN, PN);
9083 PhiVal = NewPN;
9084 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009085
Chris Lattnerbac32862004-11-14 19:13:23 +00009086 // Insert and return the new operation.
Reid Spencer3da59db2006-11-27 01:05:10 +00009087 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
9088 return CastInst::create(FirstCI->getOpcode(), PhiVal, PN.getType());
Reid Spencer3ed469c2006-11-02 20:25:50 +00009089 else if (isa<LoadInst>(FirstInst))
Chris Lattner76c73142006-11-01 07:13:54 +00009090 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattnerbac32862004-11-14 19:13:23 +00009091 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattnerb5893442004-11-14 19:29:34 +00009092 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Reid Spencere4d87aa2006-12-23 06:05:41 +00009093 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
9094 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(),
9095 PhiVal, ConstantOp);
Chris Lattnerbac32862004-11-14 19:13:23 +00009096 else
Reid Spencer832254e2007-02-02 02:16:23 +00009097 assert(0 && "Unknown operation");
Jeff Cohenca5183d2007-03-05 00:00:42 +00009098 return 0;
Chris Lattnerbac32862004-11-14 19:13:23 +00009099}
Chris Lattnera1be5662002-05-02 17:06:02 +00009100
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009101/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
9102/// that is dead.
Chris Lattner0e5444b2007-03-26 20:40:50 +00009103static bool DeadPHICycle(PHINode *PN,
9104 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009105 if (PN->use_empty()) return true;
9106 if (!PN->hasOneUse()) return false;
9107
9108 // Remember this node, and if we find the cycle, return.
Chris Lattner0e5444b2007-03-26 20:40:50 +00009109 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009110 return true;
Chris Lattner92103de2007-08-28 04:23:55 +00009111
9112 // Don't scan crazily complex things.
9113 if (PotentiallyDeadPHIs.size() == 16)
9114 return false;
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009115
9116 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
9117 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +00009118
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009119 return false;
9120}
9121
Chris Lattnercf5008a2007-11-06 21:52:06 +00009122/// PHIsEqualValue - Return true if this phi node is always equal to
9123/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
9124/// z = some value; x = phi (y, z); y = phi (x, z)
9125static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
9126 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
9127 // See if we already saw this PHI node.
9128 if (!ValueEqualPHIs.insert(PN))
9129 return true;
9130
9131 // Don't scan crazily complex things.
9132 if (ValueEqualPHIs.size() == 16)
9133 return false;
9134
9135 // Scan the operands to see if they are either phi nodes or are equal to
9136 // the value.
9137 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
9138 Value *Op = PN->getIncomingValue(i);
9139 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
9140 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
9141 return false;
9142 } else if (Op != NonPhiInVal)
9143 return false;
9144 }
9145
9146 return true;
9147}
9148
9149
Chris Lattner473945d2002-05-06 18:06:38 +00009150// PHINode simplification
9151//
Chris Lattner7e708292002-06-25 16:13:24 +00009152Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +00009153 // If LCSSA is around, don't mess with Phi nodes
Chris Lattnerf964f322007-03-04 04:27:24 +00009154 if (MustPreserveLCSSA) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +00009155
Owen Anderson7e057142006-07-10 22:03:18 +00009156 if (Value *V = PN.hasConstantValue())
9157 return ReplaceInstUsesWith(PN, V);
9158
Owen Anderson7e057142006-07-10 22:03:18 +00009159 // If all PHI operands are the same operation, pull them through the PHI,
9160 // reducing code size.
9161 if (isa<Instruction>(PN.getIncomingValue(0)) &&
9162 PN.getIncomingValue(0)->hasOneUse())
9163 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
9164 return Result;
9165
9166 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
9167 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
9168 // PHI)... break the cycle.
Chris Lattnerff9f13a2007-01-15 07:30:06 +00009169 if (PN.hasOneUse()) {
9170 Instruction *PHIUser = cast<Instruction>(PN.use_back());
9171 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattner0e5444b2007-03-26 20:40:50 +00009172 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Anderson7e057142006-07-10 22:03:18 +00009173 PotentiallyDeadPHIs.insert(&PN);
9174 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
9175 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9176 }
Chris Lattnerff9f13a2007-01-15 07:30:06 +00009177
9178 // If this phi has a single use, and if that use just computes a value for
9179 // the next iteration of a loop, delete the phi. This occurs with unused
9180 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
9181 // common case here is good because the only other things that catch this
9182 // are induction variable analysis (sometimes) and ADCE, which is only run
9183 // late.
9184 if (PHIUser->hasOneUse() &&
9185 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
9186 PHIUser->use_back() == &PN) {
9187 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9188 }
9189 }
Owen Anderson7e057142006-07-10 22:03:18 +00009190
Chris Lattnercf5008a2007-11-06 21:52:06 +00009191 // We sometimes end up with phi cycles that non-obviously end up being the
9192 // same value, for example:
9193 // z = some value; x = phi (y, z); y = phi (x, z)
9194 // where the phi nodes don't necessarily need to be in the same block. Do a
9195 // quick check to see if the PHI node only contains a single non-phi value, if
9196 // so, scan to see if the phi cycle is actually equal to that value.
9197 {
9198 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
9199 // Scan for the first non-phi operand.
9200 while (InValNo != NumOperandVals &&
9201 isa<PHINode>(PN.getIncomingValue(InValNo)))
9202 ++InValNo;
9203
9204 if (InValNo != NumOperandVals) {
9205 Value *NonPhiInVal = PN.getOperand(InValNo);
9206
9207 // Scan the rest of the operands to see if there are any conflicts, if so
9208 // there is no need to recursively scan other phis.
9209 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
9210 Value *OpVal = PN.getIncomingValue(InValNo);
9211 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
9212 break;
9213 }
9214
9215 // If we scanned over all operands, then we have one unique value plus
9216 // phi values. Scan PHI nodes to see if they all merge in each other or
9217 // the value.
9218 if (InValNo == NumOperandVals) {
9219 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
9220 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
9221 return ReplaceInstUsesWith(PN, NonPhiInVal);
9222 }
9223 }
9224 }
Chris Lattner60921c92003-12-19 05:58:40 +00009225 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +00009226}
9227
Reid Spencer17212df2006-12-12 09:18:51 +00009228static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
9229 Instruction *InsertPoint,
9230 InstCombiner *IC) {
Reid Spencerabaa8ca2007-01-08 16:32:00 +00009231 unsigned PtrSize = DTy->getPrimitiveSizeInBits();
9232 unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +00009233 // We must cast correctly to the pointer type. Ensure that we
9234 // sign extend the integer value if it is smaller as this is
9235 // used for address computation.
9236 Instruction::CastOps opcode =
9237 (VTySize < PtrSize ? Instruction::SExt :
9238 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
9239 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
Chris Lattner28977af2004-04-05 01:30:19 +00009240}
9241
Chris Lattnera1be5662002-05-02 17:06:02 +00009242
Chris Lattner7e708292002-06-25 16:13:24 +00009243Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +00009244 Value *PtrOp = GEP.getOperand(0);
Chris Lattner9bc14642007-04-28 00:57:34 +00009245 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
Chris Lattner7e708292002-06-25 16:13:24 +00009246 // If so, eliminate the noop.
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009247 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +00009248 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009249
Chris Lattnere87597f2004-10-16 18:11:37 +00009250 if (isa<UndefValue>(GEP.getOperand(0)))
9251 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
9252
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009253 bool HasZeroPointerIndex = false;
9254 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
9255 HasZeroPointerIndex = C->isNullValue();
9256
9257 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +00009258 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +00009259
Chris Lattner28977af2004-04-05 01:30:19 +00009260 // Eliminate unneeded casts for indices.
9261 bool MadeChange = false;
Chris Lattnerdb9654e2007-03-25 20:43:09 +00009262
Chris Lattnercb69a4e2004-04-07 18:38:20 +00009263 gep_type_iterator GTI = gep_type_begin(GEP);
Chris Lattnerdb9654e2007-03-25 20:43:09 +00009264 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattnercb69a4e2004-04-07 18:38:20 +00009265 if (isa<SequentialType>(*GTI)) {
9266 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
Chris Lattner76b7a062007-01-15 07:02:54 +00009267 if (CI->getOpcode() == Instruction::ZExt ||
9268 CI->getOpcode() == Instruction::SExt) {
9269 const Type *SrcTy = CI->getOperand(0)->getType();
9270 // We can eliminate a cast from i32 to i64 iff the target
9271 // is a 32-bit pointer target.
9272 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
9273 MadeChange = true;
9274 GEP.setOperand(i, CI->getOperand(0));
Chris Lattner28977af2004-04-05 01:30:19 +00009275 }
9276 }
9277 }
Chris Lattnercb69a4e2004-04-07 18:38:20 +00009278 // If we are using a wider index than needed for this platform, shrink it
9279 // to what we need. If the incoming value needs a cast instruction,
9280 // insert it. This explicit cast can make subsequent optimizations more
9281 // obvious.
9282 Value *Op = GEP.getOperand(i);
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009283 if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
Chris Lattner4f1134e2004-04-17 18:16:10 +00009284 if (Constant *C = dyn_cast<Constant>(Op)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00009285 GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
Chris Lattner4f1134e2004-04-17 18:16:10 +00009286 MadeChange = true;
9287 } else {
Reid Spencer17212df2006-12-12 09:18:51 +00009288 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
9289 GEP);
Chris Lattnercb69a4e2004-04-07 18:38:20 +00009290 GEP.setOperand(i, Op);
9291 MadeChange = true;
9292 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009293 }
Chris Lattner28977af2004-04-05 01:30:19 +00009294 }
Chris Lattnerdb9654e2007-03-25 20:43:09 +00009295 }
Chris Lattner28977af2004-04-05 01:30:19 +00009296 if (MadeChange) return &GEP;
9297
Chris Lattnerdb9654e2007-03-25 20:43:09 +00009298 // If this GEP instruction doesn't move the pointer, and if the input operand
9299 // is a bitcast of another pointer, just replace the GEP with a bitcast of the
9300 // real input to the dest type.
Chris Lattner6a94de22007-10-12 05:30:59 +00009301 if (GEP.hasAllZeroIndices()) {
9302 if (BitCastInst *BCI = dyn_cast<BitCastInst>(GEP.getOperand(0))) {
9303 // If the bitcast is of an allocation, and the allocation will be
9304 // converted to match the type of the cast, don't touch this.
9305 if (isa<AllocationInst>(BCI->getOperand(0))) {
9306 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
Chris Lattnera79dd432007-10-12 18:05:47 +00009307 if (Instruction *I = visitBitCast(*BCI)) {
9308 if (I != BCI) {
9309 I->takeName(BCI);
9310 BCI->getParent()->getInstList().insert(BCI, I);
9311 ReplaceInstUsesWith(*BCI, I);
9312 }
Chris Lattner6a94de22007-10-12 05:30:59 +00009313 return &GEP;
Chris Lattnera79dd432007-10-12 18:05:47 +00009314 }
Chris Lattner6a94de22007-10-12 05:30:59 +00009315 }
9316 return new BitCastInst(BCI->getOperand(0), GEP.getType());
9317 }
9318 }
9319
Chris Lattner90ac28c2002-08-02 19:29:35 +00009320 // Combine Indices - If the source pointer to this getelementptr instruction
9321 // is a getelementptr instruction, combine the indices of the two
9322 // getelementptr instructions into a single instruction.
9323 //
Chris Lattner72588fc2007-02-15 22:48:32 +00009324 SmallVector<Value*, 8> SrcGEPOperands;
Chris Lattner574da9b2005-01-13 20:14:25 +00009325 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner72588fc2007-02-15 22:48:32 +00009326 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
Chris Lattnerebd985c2004-03-25 22:59:29 +00009327
9328 if (!SrcGEPOperands.empty()) {
Chris Lattner620ce142004-05-07 22:09:22 +00009329 // Note that if our source is a gep chain itself that we wait for that
9330 // chain to be resolved before we perform this transformation. This
9331 // avoids us creating a TON of code in some cases.
9332 //
9333 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
9334 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
9335 return 0; // Wait until our source is folded to completion.
9336
Chris Lattner72588fc2007-02-15 22:48:32 +00009337 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +00009338
9339 // Find out whether the last index in the source GEP is a sequential idx.
9340 bool EndsWithSequential = false;
9341 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
9342 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +00009343 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +00009344
Chris Lattner90ac28c2002-08-02 19:29:35 +00009345 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +00009346 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +00009347 // Replace: gep (gep %P, long B), long A, ...
9348 // With: T = long A+B; gep %P, T, ...
9349 //
Chris Lattner620ce142004-05-07 22:09:22 +00009350 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner28977af2004-04-05 01:30:19 +00009351 if (SO1 == Constant::getNullValue(SO1->getType())) {
9352 Sum = GO1;
9353 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
9354 Sum = SO1;
9355 } else {
9356 // If they aren't the same type, convert both to an integer of the
9357 // target's pointer size.
9358 if (SO1->getType() != GO1->getType()) {
9359 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +00009360 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +00009361 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +00009362 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +00009363 } else {
Duncan Sands514ab342007-11-01 20:53:16 +00009364 unsigned PS = TD->getPointerSizeInBits();
9365 if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +00009366 // Convert GO1 to SO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +00009367 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +00009368
Duncan Sands514ab342007-11-01 20:53:16 +00009369 } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +00009370 // Convert SO1 to GO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +00009371 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +00009372 } else {
9373 const Type *PT = TD->getIntPtrType();
Reid Spencer17212df2006-12-12 09:18:51 +00009374 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
9375 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +00009376 }
9377 }
9378 }
Chris Lattner620ce142004-05-07 22:09:22 +00009379 if (isa<Constant>(SO1) && isa<Constant>(GO1))
9380 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
9381 else {
Chris Lattner48595f12004-06-10 02:07:29 +00009382 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
9383 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner620ce142004-05-07 22:09:22 +00009384 }
Chris Lattner28977af2004-04-05 01:30:19 +00009385 }
Chris Lattner620ce142004-05-07 22:09:22 +00009386
9387 // Recycle the GEP we already have if possible.
9388 if (SrcGEPOperands.size() == 2) {
9389 GEP.setOperand(0, SrcGEPOperands[0]);
9390 GEP.setOperand(1, Sum);
9391 return &GEP;
9392 } else {
9393 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9394 SrcGEPOperands.end()-1);
9395 Indices.push_back(Sum);
9396 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
9397 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009398 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +00009399 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanfd939082005-04-21 23:48:37 +00009400 SrcGEPOperands.size() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +00009401 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerebd985c2004-03-25 22:59:29 +00009402 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9403 SrcGEPOperands.end());
Chris Lattner90ac28c2002-08-02 19:29:35 +00009404 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
9405 }
9406
9407 if (!Indices.empty())
David Greeneb8f74792007-09-04 15:46:09 +00009408 return new GetElementPtrInst(SrcGEPOperands[0], Indices.begin(),
9409 Indices.end(), GEP.getName());
Chris Lattner9b761232002-08-17 22:21:59 +00009410
Chris Lattner620ce142004-05-07 22:09:22 +00009411 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattner9b761232002-08-17 22:21:59 +00009412 // GEP of global variable. If all of the indices for this GEP are
9413 // constants, we can promote this to a constexpr instead of an instruction.
9414
9415 // Scan for nonconstants...
Chris Lattner55eb1c42007-01-31 04:40:53 +00009416 SmallVector<Constant*, 8> Indices;
Chris Lattner9b761232002-08-17 22:21:59 +00009417 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
9418 for (; I != E && isa<Constant>(*I); ++I)
9419 Indices.push_back(cast<Constant>(*I));
9420
9421 if (I == E) { // If they are all constants...
Chris Lattner55eb1c42007-01-31 04:40:53 +00009422 Constant *CE = ConstantExpr::getGetElementPtr(GV,
9423 &Indices[0],Indices.size());
Chris Lattner9b761232002-08-17 22:21:59 +00009424
9425 // Replace all uses of the GEP with the new constexpr...
9426 return ReplaceInstUsesWith(GEP, CE);
9427 }
Reid Spencer3da59db2006-11-27 01:05:10 +00009428 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
Chris Lattnereed48272005-09-13 00:40:14 +00009429 if (!isa<PointerType>(X->getType())) {
9430 // Not interesting. Source pointer must be a cast from pointer.
9431 } else if (HasZeroPointerIndex) {
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009432 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
9433 // into : GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +00009434 //
9435 // This occurs when the program declares an array extern like "int X[];"
9436 //
9437 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
9438 const PointerType *XTy = cast<PointerType>(X->getType());
9439 if (const ArrayType *XATy =
9440 dyn_cast<ArrayType>(XTy->getElementType()))
9441 if (const ArrayType *CATy =
9442 dyn_cast<ArrayType>(CPTy->getElementType()))
9443 if (CATy->getElementType() == XATy->getElementType()) {
9444 // At this point, we know that the cast source type is a pointer
9445 // to an array of the same type as the destination pointer
9446 // array. Because the array type is never stepped over (there
9447 // is a leading zero) we can fold the cast into this GEP.
9448 GEP.setOperand(0, X);
9449 return &GEP;
9450 }
9451 } else if (GEP.getNumOperands() == 2) {
9452 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009453 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
9454 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnereed48272005-09-13 00:40:14 +00009455 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
9456 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
9457 if (isa<ArrayType>(SrcElTy) &&
Duncan Sands514ab342007-11-01 20:53:16 +00009458 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
9459 TD->getABITypeSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +00009460 Value *Idx[2];
9461 Idx[0] = Constant::getNullValue(Type::Int32Ty);
9462 Idx[1] = GEP.getOperand(1);
Chris Lattnereed48272005-09-13 00:40:14 +00009463 Value *V = InsertNewInstBefore(
David Greeneb8f74792007-09-04 15:46:09 +00009464 new GetElementPtrInst(X, Idx, Idx + 2, GEP.getName()), GEP);
Reid Spencer3da59db2006-11-27 01:05:10 +00009465 // V and GEP are both pointer types --> BitCast
9466 return new BitCastInst(V, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009467 }
Chris Lattner7835cdd2005-09-13 18:36:04 +00009468
9469 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009470 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +00009471 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009472 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +00009473
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009474 if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
Chris Lattner7835cdd2005-09-13 18:36:04 +00009475 uint64_t ArrayEltSize =
Duncan Sands514ab342007-11-01 20:53:16 +00009476 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +00009477
9478 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
9479 // allow either a mul, shift, or constant here.
9480 Value *NewIdx = 0;
9481 ConstantInt *Scale = 0;
9482 if (ArrayEltSize == 1) {
9483 NewIdx = GEP.getOperand(1);
9484 Scale = ConstantInt::get(NewIdx->getType(), 1);
9485 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattner6e2f8432005-09-14 17:32:56 +00009486 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +00009487 Scale = CI;
9488 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
9489 if (Inst->getOpcode() == Instruction::Shl &&
9490 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00009491 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
9492 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
9493 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +00009494 NewIdx = Inst->getOperand(0);
9495 } else if (Inst->getOpcode() == Instruction::Mul &&
9496 isa<ConstantInt>(Inst->getOperand(1))) {
9497 Scale = cast<ConstantInt>(Inst->getOperand(1));
9498 NewIdx = Inst->getOperand(0);
9499 }
9500 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009501
Chris Lattner7835cdd2005-09-13 18:36:04 +00009502 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009503 // out, perform the transformation. Note, we don't know whether Scale is
9504 // signed or not. We'll use unsigned version of division/modulo
9505 // operation after making sure Scale doesn't have the sign bit set.
9506 if (Scale && Scale->getSExtValue() >= 0LL &&
9507 Scale->getZExtValue() % ArrayEltSize == 0) {
9508 Scale = ConstantInt::get(Scale->getType(),
9509 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +00009510 if (Scale->getZExtValue() != 1) {
Reid Spencer17212df2006-12-12 09:18:51 +00009511 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009512 false /*ZExt*/);
Chris Lattner7835cdd2005-09-13 18:36:04 +00009513 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
9514 NewIdx = InsertNewInstBefore(Sc, GEP);
9515 }
9516
9517 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +00009518 Value *Idx[2];
9519 Idx[0] = Constant::getNullValue(Type::Int32Ty);
9520 Idx[1] = NewIdx;
Reid Spencer3da59db2006-11-27 01:05:10 +00009521 Instruction *NewGEP =
David Greeneb8f74792007-09-04 15:46:09 +00009522 new GetElementPtrInst(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +00009523 NewGEP = InsertNewInstBefore(NewGEP, GEP);
9524 // The NewGEP must be pointer typed, so must the old one -> BitCast
9525 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +00009526 }
9527 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009528 }
Chris Lattner8a2a3112001-12-14 16:52:21 +00009529 }
9530
Chris Lattner8a2a3112001-12-14 16:52:21 +00009531 return 0;
9532}
9533
Chris Lattner0864acf2002-11-04 16:18:53 +00009534Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
9535 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009536 if (AI.isArrayAllocation()) { // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +00009537 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
9538 const Type *NewTy =
9539 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattner0006bd72002-11-09 00:49:43 +00009540 AllocationInst *New = 0;
Chris Lattner0864acf2002-11-04 16:18:53 +00009541
9542 // Create and insert the replacement instruction...
9543 if (isa<MallocInst>(AI))
Nate Begeman14b05292005-11-05 09:21:28 +00009544 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +00009545 else {
9546 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman14b05292005-11-05 09:21:28 +00009547 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +00009548 }
Chris Lattner7c881df2004-03-19 06:08:10 +00009549
9550 InsertNewInstBefore(New, AI);
Misha Brukmanfd939082005-04-21 23:48:37 +00009551
Chris Lattner0864acf2002-11-04 16:18:53 +00009552 // Scan to the end of the allocation instructions, to skip over a block of
9553 // allocas if possible...
9554 //
9555 BasicBlock::iterator It = New;
9556 while (isa<AllocationInst>(*It)) ++It;
9557
9558 // Now that I is pointing to the first non-allocation-inst in the block,
9559 // insert our getelementptr instruction...
9560 //
Reid Spencerc5b206b2006-12-31 05:48:39 +00009561 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
David Greeneb8f74792007-09-04 15:46:09 +00009562 Value *Idx[2];
9563 Idx[0] = NullIdx;
9564 Idx[1] = NullIdx;
9565 Value *V = new GetElementPtrInst(New, Idx, Idx + 2,
Chris Lattner693787a2005-05-04 19:10:26 +00009566 New->getName()+".sub", It);
Chris Lattner0864acf2002-11-04 16:18:53 +00009567
9568 // Now make everything use the getelementptr instead of the original
9569 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +00009570 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +00009571 } else if (isa<UndefValue>(AI.getArraySize())) {
9572 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +00009573 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009574 }
Chris Lattner7c881df2004-03-19 06:08:10 +00009575
9576 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
9577 // Note that we only do this for alloca's, because malloc should allocate and
9578 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanfd939082005-04-21 23:48:37 +00009579 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Duncan Sands514ab342007-11-01 20:53:16 +00009580 TD->getABITypeSize(AI.getAllocatedType()) == 0)
Chris Lattner7c881df2004-03-19 06:08:10 +00009581 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
9582
Chris Lattner0864acf2002-11-04 16:18:53 +00009583 return 0;
9584}
9585
Chris Lattner67b1e1b2003-12-07 01:24:23 +00009586Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
9587 Value *Op = FI.getOperand(0);
9588
Chris Lattner17be6352004-10-18 02:59:09 +00009589 // free undef -> unreachable.
9590 if (isa<UndefValue>(Op)) {
9591 // Insert a new store to null because we cannot modify the CFG here.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009592 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009593 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
Chris Lattner17be6352004-10-18 02:59:09 +00009594 return EraseInstFromFunction(FI);
9595 }
Chris Lattner6fe55412007-04-14 00:20:02 +00009596
Chris Lattner6160e852004-02-28 04:57:37 +00009597 // If we have 'free null' delete the instruction. This can happen in stl code
9598 // when lots of inlining happens.
Chris Lattner17be6352004-10-18 02:59:09 +00009599 if (isa<ConstantPointerNull>(Op))
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009600 return EraseInstFromFunction(FI);
Chris Lattner6fe55412007-04-14 00:20:02 +00009601
9602 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
9603 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
9604 FI.setOperand(0, CI->getOperand(0));
9605 return &FI;
9606 }
9607
9608 // Change free (gep X, 0,0,0,0) into free(X)
9609 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
9610 if (GEPI->hasAllZeroIndices()) {
9611 AddToWorkList(GEPI);
9612 FI.setOperand(0, GEPI->getOperand(0));
9613 return &FI;
9614 }
9615 }
9616
9617 // Change free(malloc) into nothing, if the malloc has a single use.
9618 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
9619 if (MI->hasOneUse()) {
9620 EraseInstFromFunction(FI);
9621 return EraseInstFromFunction(*MI);
9622 }
Chris Lattner6160e852004-02-28 04:57:37 +00009623
Chris Lattner67b1e1b2003-12-07 01:24:23 +00009624 return 0;
9625}
9626
9627
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009628/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patel99db6ad2007-10-18 19:52:32 +00009629static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling587c01d2008-02-26 10:53:30 +00009630 const TargetData *TD) {
Chris Lattnerb89e0712004-07-13 01:49:43 +00009631 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +00009632 Value *CastOp = CI->getOperand(0);
Chris Lattnerb89e0712004-07-13 01:49:43 +00009633
Devang Patel99db6ad2007-10-18 19:52:32 +00009634 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
9635 // Instead of loading constant c string, use corresponding integer value
9636 // directly if string length is small enough.
9637 const std::string &Str = CE->getOperand(0)->getStringValue();
9638 if (!Str.empty()) {
9639 unsigned len = Str.length();
9640 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
9641 unsigned numBits = Ty->getPrimitiveSizeInBits();
9642 // Replace LI with immediate integer store.
9643 if ((numBits >> 3) == len + 1) {
Bill Wendling587c01d2008-02-26 10:53:30 +00009644 APInt StrVal(numBits, 0);
9645 APInt SingleChar(numBits, 0);
9646 if (TD->isLittleEndian()) {
9647 for (signed i = len-1; i >= 0; i--) {
9648 SingleChar = (uint64_t) Str[i];
9649 StrVal = (StrVal << 8) | SingleChar;
9650 }
9651 } else {
9652 for (unsigned i = 0; i < len; i++) {
9653 SingleChar = (uint64_t) Str[i];
9654 StrVal = (StrVal << 8) | SingleChar;
9655 }
9656 // Append NULL at the end.
9657 SingleChar = 0;
9658 StrVal = (StrVal << 8) | SingleChar;
9659 }
9660 Value *NL = ConstantInt::get(StrVal);
9661 return IC.ReplaceInstUsesWith(LI, NL);
Devang Patel99db6ad2007-10-18 19:52:32 +00009662 }
9663 }
9664 }
9665
Chris Lattnerb89e0712004-07-13 01:49:43 +00009666 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +00009667 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattnerb89e0712004-07-13 01:49:43 +00009668 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +00009669
Reid Spencer42230162007-01-22 05:51:25 +00009670 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +00009671 isa<VectorType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +00009672 // If the source is an array, the code below will not succeed. Check to
9673 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
9674 // constants.
9675 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
9676 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
9677 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +00009678 Value *Idxs[2];
9679 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
9680 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerf9527852005-01-31 04:50:46 +00009681 SrcTy = cast<PointerType>(CastOp->getType());
9682 SrcPTy = SrcTy->getElementType();
9683 }
9684
Reid Spencer42230162007-01-22 05:51:25 +00009685 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +00009686 isa<VectorType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +00009687 // Do not allow turning this into a load of an integer, which is then
9688 // casted to a pointer, this pessimizes pointer analysis a lot.
9689 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Reid Spencer42230162007-01-22 05:51:25 +00009690 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
9691 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +00009692
Chris Lattnerf9527852005-01-31 04:50:46 +00009693 // Okay, we are casting from one integer or pointer type to another of
9694 // the same size. Instead of casting the pointer before the load, cast
9695 // the result of the loaded value.
9696 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
9697 CI->getName(),
9698 LI.isVolatile()),LI);
9699 // Now cast the result of the load.
Reid Spencerd977d862006-12-12 23:36:14 +00009700 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerf9527852005-01-31 04:50:46 +00009701 }
Chris Lattnerb89e0712004-07-13 01:49:43 +00009702 }
9703 }
9704 return 0;
9705}
9706
Chris Lattnerc10aced2004-09-19 18:43:46 +00009707/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattner8a375202004-09-19 19:18:10 +00009708/// from this value cannot trap. If it is not obviously safe to load from the
9709/// specified pointer, we do a quick local scan of the basic block containing
9710/// ScanFrom, to determine if the address is already accessed.
9711static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
Duncan Sands892c7e42007-09-19 10:10:31 +00009712 // If it is an alloca it is always safe to load from.
9713 if (isa<AllocaInst>(V)) return true;
9714
Duncan Sands46318cd2007-09-19 10:25:38 +00009715 // If it is a global variable it is mostly safe to load from.
Duncan Sands892c7e42007-09-19 10:10:31 +00009716 if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
Duncan Sands46318cd2007-09-19 10:25:38 +00009717 // Don't try to evaluate aliases. External weak GV can be null.
Duncan Sands892c7e42007-09-19 10:10:31 +00009718 return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
Chris Lattner8a375202004-09-19 19:18:10 +00009719
9720 // Otherwise, be a little bit agressive by scanning the local block where we
9721 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00009722 // from/to. If so, the previous load or store would have already trapped,
9723 // so there is no harm doing an extra load (also, CSE will later eliminate
9724 // the load entirely).
Chris Lattner8a375202004-09-19 19:18:10 +00009725 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
9726
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00009727 while (BBI != E) {
Chris Lattner8a375202004-09-19 19:18:10 +00009728 --BBI;
9729
9730 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
9731 if (LI->getOperand(0) == V) return true;
9732 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
9733 if (SI->getOperand(1) == V) return true;
Misha Brukmanfd939082005-04-21 23:48:37 +00009734
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00009735 }
Chris Lattner8a375202004-09-19 19:18:10 +00009736 return false;
Chris Lattnerc10aced2004-09-19 18:43:46 +00009737}
9738
Chris Lattner8d2e8882007-08-11 18:48:48 +00009739/// GetUnderlyingObject - Trace through a series of getelementptrs and bitcasts
9740/// until we find the underlying object a pointer is referring to or something
9741/// we don't understand. Note that the returned pointer may be offset from the
9742/// input, because we ignore GEP indices.
9743static Value *GetUnderlyingObject(Value *Ptr) {
9744 while (1) {
9745 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
9746 if (CE->getOpcode() == Instruction::BitCast ||
9747 CE->getOpcode() == Instruction::GetElementPtr)
9748 Ptr = CE->getOperand(0);
9749 else
9750 return Ptr;
9751 } else if (BitCastInst *BCI = dyn_cast<BitCastInst>(Ptr)) {
9752 Ptr = BCI->getOperand(0);
9753 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
9754 Ptr = GEP->getOperand(0);
9755 } else {
9756 return Ptr;
9757 }
9758 }
9759}
9760
Chris Lattner833b8a42003-06-26 05:06:25 +00009761Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
9762 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +00009763
Dan Gohman9941f742007-07-20 16:34:21 +00009764 // Attempt to improve the alignment.
Chris Lattnerf2369f22007-08-09 19:05:49 +00009765 unsigned KnownAlign = GetOrEnforceKnownAlignment(Op, TD);
Dan Gohman9941f742007-07-20 16:34:21 +00009766 if (KnownAlign > LI.getAlignment())
9767 LI.setAlignment(KnownAlign);
9768
Chris Lattner37366c12005-05-01 04:24:53 +00009769 // load (cast X) --> cast (load X) iff safe
Reid Spencer3ed469c2006-11-02 20:25:50 +00009770 if (isa<CastInst>(Op))
Devang Patel99db6ad2007-10-18 19:52:32 +00009771 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattner37366c12005-05-01 04:24:53 +00009772 return Res;
9773
9774 // None of the following transforms are legal for volatile loads.
9775 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +00009776
Chris Lattner62f254d2005-09-12 22:00:15 +00009777 if (&LI.getParent()->front() != &LI) {
9778 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattner9c1f0fd2005-09-12 22:21:03 +00009779 // If the instruction immediately before this is a store to the same
9780 // address, do a simple form of store->load forwarding.
Chris Lattner62f254d2005-09-12 22:00:15 +00009781 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
9782 if (SI->getOperand(1) == LI.getOperand(0))
9783 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattner9c1f0fd2005-09-12 22:21:03 +00009784 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
9785 if (LIB->getOperand(0) == LI.getOperand(0))
9786 return ReplaceInstUsesWith(LI, LIB);
Chris Lattner62f254d2005-09-12 22:00:15 +00009787 }
Chris Lattner37366c12005-05-01 04:24:53 +00009788
Christopher Lambb15147e2007-12-29 07:56:53 +00009789 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
9790 const Value *GEPI0 = GEPI->getOperand(0);
9791 // TODO: Consider a target hook for valid address spaces for this xform.
9792 if (isa<ConstantPointerNull>(GEPI0) &&
9793 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
Chris Lattner37366c12005-05-01 04:24:53 +00009794 // Insert a new store to null instruction before the load to indicate
9795 // that this code is not reachable. We do this instead of inserting
9796 // an unreachable instruction directly because we cannot modify the
9797 // CFG.
9798 new StoreInst(UndefValue::get(LI.getType()),
9799 Constant::getNullValue(Op->getType()), &LI);
9800 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
9801 }
Christopher Lambb15147e2007-12-29 07:56:53 +00009802 }
Chris Lattner37366c12005-05-01 04:24:53 +00009803
Chris Lattnere87597f2004-10-16 18:11:37 +00009804 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner37366c12005-05-01 04:24:53 +00009805 // load null/undef -> undef
Christopher Lambb15147e2007-12-29 07:56:53 +00009806 // TODO: Consider a target hook for valid address spaces for this xform.
9807 if (isa<UndefValue>(C) || (C->isNullValue() &&
9808 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
Chris Lattner17be6352004-10-18 02:59:09 +00009809 // Insert a new store to null instruction before the load to indicate that
9810 // this code is not reachable. We do this instead of inserting an
9811 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattner37366c12005-05-01 04:24:53 +00009812 new StoreInst(UndefValue::get(LI.getType()),
9813 Constant::getNullValue(Op->getType()), &LI);
Chris Lattnere87597f2004-10-16 18:11:37 +00009814 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner17be6352004-10-18 02:59:09 +00009815 }
Chris Lattner833b8a42003-06-26 05:06:25 +00009816
Chris Lattnere87597f2004-10-16 18:11:37 +00009817 // Instcombine load (constant global) into the value loaded.
9818 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Reid Spencer5cbf9852007-01-30 20:08:39 +00009819 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattnere87597f2004-10-16 18:11:37 +00009820 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +00009821
Chris Lattnere87597f2004-10-16 18:11:37 +00009822 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009823 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
Chris Lattnere87597f2004-10-16 18:11:37 +00009824 if (CE->getOpcode() == Instruction::GetElementPtr) {
9825 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Reid Spencer5cbf9852007-01-30 20:08:39 +00009826 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattner363f2a22005-09-26 05:28:06 +00009827 if (Constant *V =
9828 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattnere87597f2004-10-16 18:11:37 +00009829 return ReplaceInstUsesWith(LI, V);
Chris Lattner37366c12005-05-01 04:24:53 +00009830 if (CE->getOperand(0)->isNullValue()) {
9831 // Insert a new store to null instruction before the load to indicate
9832 // that this code is not reachable. We do this instead of inserting
9833 // an unreachable instruction directly because we cannot modify the
9834 // CFG.
9835 new StoreInst(UndefValue::get(LI.getType()),
9836 Constant::getNullValue(Op->getType()), &LI);
9837 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
9838 }
9839
Reid Spencer3da59db2006-11-27 01:05:10 +00009840 } else if (CE->isCast()) {
Devang Patel99db6ad2007-10-18 19:52:32 +00009841 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattnere87597f2004-10-16 18:11:37 +00009842 return Res;
9843 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009844 }
Chris Lattnere87597f2004-10-16 18:11:37 +00009845 }
Chris Lattner8d2e8882007-08-11 18:48:48 +00009846
9847 // If this load comes from anywhere in a constant global, and if the global
9848 // is all undef or zero, we know what it loads.
9849 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(Op))) {
9850 if (GV->isConstant() && GV->hasInitializer()) {
9851 if (GV->getInitializer()->isNullValue())
9852 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
9853 else if (isa<UndefValue>(GV->getInitializer()))
9854 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
9855 }
9856 }
Chris Lattnerf499eac2004-04-08 20:39:49 +00009857
Chris Lattner37366c12005-05-01 04:24:53 +00009858 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +00009859 // Change select and PHI nodes to select values instead of addresses: this
9860 // helps alias analysis out a lot, allows many others simplifications, and
9861 // exposes redundancy in the code.
9862 //
9863 // Note that we cannot do the transformation unless we know that the
9864 // introduced loads cannot trap! Something like this is valid as long as
9865 // the condition is always false: load (select bool %C, int* null, int* %G),
9866 // but it would not be valid if we transformed it to load from null
9867 // unconditionally.
9868 //
9869 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
9870 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +00009871 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
9872 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerc10aced2004-09-19 18:43:46 +00009873 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner79f0c8e2004-09-20 10:15:10 +00009874 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +00009875 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner79f0c8e2004-09-20 10:15:10 +00009876 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +00009877 return new SelectInst(SI->getCondition(), V1, V2);
9878 }
9879
Chris Lattner684fe212004-09-23 15:46:00 +00009880 // load (select (cond, null, P)) -> load P
9881 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
9882 if (C->isNullValue()) {
9883 LI.setOperand(0, SI->getOperand(2));
9884 return &LI;
9885 }
9886
9887 // load (select (cond, P, null)) -> load P
9888 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
9889 if (C->isNullValue()) {
9890 LI.setOperand(0, SI->getOperand(1));
9891 return &LI;
9892 }
Chris Lattnerc10aced2004-09-19 18:43:46 +00009893 }
9894 }
Chris Lattner833b8a42003-06-26 05:06:25 +00009895 return 0;
9896}
9897
Reid Spencer55af2b52007-01-19 21:20:31 +00009898/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009899/// when possible.
9900static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
9901 User *CI = cast<User>(SI.getOperand(1));
9902 Value *CastOp = CI->getOperand(0);
9903
9904 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
9905 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
9906 const Type *SrcPTy = SrcTy->getElementType();
9907
Reid Spencer42230162007-01-22 05:51:25 +00009908 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009909 // If the source is an array, the code below will not succeed. Check to
9910 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
9911 // constants.
9912 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
9913 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
9914 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +00009915 Value* Idxs[2];
9916 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
9917 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009918 SrcTy = cast<PointerType>(CastOp->getType());
9919 SrcPTy = SrcTy->getElementType();
9920 }
9921
Reid Spencer67f827c2007-01-20 23:35:48 +00009922 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
9923 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
9924 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009925
9926 // Okay, we are casting from one integer or pointer type to another of
Reid Spencer75153962007-01-18 18:54:33 +00009927 // the same size. Instead of casting the pointer before
9928 // the store, cast the value to be stored.
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009929 Value *NewCast;
Reid Spencerd977d862006-12-12 23:36:14 +00009930 Value *SIOp0 = SI.getOperand(0);
Reid Spencer75153962007-01-18 18:54:33 +00009931 Instruction::CastOps opcode = Instruction::BitCast;
9932 const Type* CastSrcTy = SIOp0->getType();
9933 const Type* CastDstTy = SrcPTy;
9934 if (isa<PointerType>(CastDstTy)) {
9935 if (CastSrcTy->isInteger())
Reid Spencerd977d862006-12-12 23:36:14 +00009936 opcode = Instruction::IntToPtr;
Reid Spencer67f827c2007-01-20 23:35:48 +00009937 } else if (isa<IntegerType>(CastDstTy)) {
Reid Spencerc55b2432006-12-13 18:21:21 +00009938 if (isa<PointerType>(SIOp0->getType()))
Reid Spencerd977d862006-12-12 23:36:14 +00009939 opcode = Instruction::PtrToInt;
9940 }
9941 if (Constant *C = dyn_cast<Constant>(SIOp0))
Reid Spencer75153962007-01-18 18:54:33 +00009942 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009943 else
Reid Spencer3da59db2006-11-27 01:05:10 +00009944 NewCast = IC.InsertNewInstBefore(
Reid Spencer75153962007-01-18 18:54:33 +00009945 CastInst::create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
9946 SI);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009947 return new StoreInst(NewCast, CastOp);
9948 }
9949 }
9950 }
9951 return 0;
9952}
9953
Chris Lattner2f503e62005-01-31 05:36:43 +00009954Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
9955 Value *Val = SI.getOperand(0);
9956 Value *Ptr = SI.getOperand(1);
9957
9958 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner9ca96412006-02-08 03:25:32 +00009959 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +00009960 ++NumCombined;
9961 return 0;
9962 }
Chris Lattner836692d2007-01-15 06:51:56 +00009963
9964 // If the RHS is an alloca with a single use, zapify the store, making the
9965 // alloca dead.
9966 if (Ptr->hasOneUse()) {
9967 if (isa<AllocaInst>(Ptr)) {
9968 EraseInstFromFunction(SI);
9969 ++NumCombined;
9970 return 0;
9971 }
9972
9973 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
9974 if (isa<AllocaInst>(GEP->getOperand(0)) &&
9975 GEP->getOperand(0)->hasOneUse()) {
9976 EraseInstFromFunction(SI);
9977 ++NumCombined;
9978 return 0;
9979 }
9980 }
Chris Lattner2f503e62005-01-31 05:36:43 +00009981
Dan Gohman9941f742007-07-20 16:34:21 +00009982 // Attempt to improve the alignment.
Chris Lattnerf2369f22007-08-09 19:05:49 +00009983 unsigned KnownAlign = GetOrEnforceKnownAlignment(Ptr, TD);
Dan Gohman9941f742007-07-20 16:34:21 +00009984 if (KnownAlign > SI.getAlignment())
9985 SI.setAlignment(KnownAlign);
9986
Chris Lattner9ca96412006-02-08 03:25:32 +00009987 // Do really simple DSE, to catch cases where there are several consequtive
9988 // stores to the same location, separated by a few arithmetic operations. This
9989 // situation often occurs with bitfield accesses.
9990 BasicBlock::iterator BBI = &SI;
9991 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
9992 --ScanInsts) {
9993 --BBI;
9994
9995 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
9996 // Prev store isn't volatile, and stores to the same location?
9997 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
9998 ++NumDeadStore;
9999 ++BBI;
10000 EraseInstFromFunction(*PrevSI);
10001 continue;
10002 }
10003 break;
10004 }
10005
Chris Lattnerb4db97f2006-05-26 19:19:20 +000010006 // If this is a load, we have to stop. However, if the loaded value is from
10007 // the pointer we're loading and is producing the pointer we're storing,
10008 // then *this* store is dead (X = load P; store X -> P).
10009 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Chris Lattnera54c7eb2007-09-07 05:33:03 +000010010 if (LI == Val && LI->getOperand(0) == Ptr && !SI.isVolatile()) {
Chris Lattnerb4db97f2006-05-26 19:19:20 +000010011 EraseInstFromFunction(SI);
10012 ++NumCombined;
10013 return 0;
10014 }
10015 // Otherwise, this is a load from some other location. Stores before it
10016 // may not be dead.
10017 break;
10018 }
10019
Chris Lattner9ca96412006-02-08 03:25:32 +000010020 // Don't skip over loads or things that can modify memory.
Chris Lattnerb4db97f2006-05-26 19:19:20 +000010021 if (BBI->mayWriteToMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +000010022 break;
10023 }
10024
10025
10026 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +000010027
10028 // store X, null -> turns into 'unreachable' in SimplifyCFG
10029 if (isa<ConstantPointerNull>(Ptr)) {
10030 if (!isa<UndefValue>(Val)) {
10031 SI.setOperand(0, UndefValue::get(Val->getType()));
10032 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattnerdbab3862007-03-02 21:28:56 +000010033 AddToWorkList(U); // Dropped a use.
Chris Lattner2f503e62005-01-31 05:36:43 +000010034 ++NumCombined;
10035 }
10036 return 0; // Do not modify these!
10037 }
10038
10039 // store undef, Ptr -> noop
10040 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +000010041 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000010042 ++NumCombined;
10043 return 0;
10044 }
10045
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010046 // If the pointer destination is a cast, see if we can fold the cast into the
10047 // source instead.
Reid Spencer3ed469c2006-11-02 20:25:50 +000010048 if (isa<CastInst>(Ptr))
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010049 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10050 return Res;
10051 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer3da59db2006-11-27 01:05:10 +000010052 if (CE->isCast())
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010053 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10054 return Res;
10055
Chris Lattner408902b2005-09-12 23:23:25 +000010056
10057 // If this store is the last instruction in the basic block, and if the block
10058 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner9ca96412006-02-08 03:25:32 +000010059 BBI = &SI; ++BBI;
Chris Lattner408902b2005-09-12 23:23:25 +000010060 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
Chris Lattner3284d1f2007-04-15 00:07:55 +000010061 if (BI->isUnconditional())
10062 if (SimplifyStoreAtEndOfBlock(SI))
10063 return 0; // xform done!
Chris Lattner408902b2005-09-12 23:23:25 +000010064
Chris Lattner2f503e62005-01-31 05:36:43 +000010065 return 0;
10066}
10067
Chris Lattner3284d1f2007-04-15 00:07:55 +000010068/// SimplifyStoreAtEndOfBlock - Turn things like:
10069/// if () { *P = v1; } else { *P = v2 }
10070/// into a phi node with a store in the successor.
10071///
Chris Lattner31755a02007-04-15 01:02:18 +000010072/// Simplify things like:
10073/// *P = v1; if () { *P = v2; }
10074/// into a phi node with a store in the successor.
10075///
Chris Lattner3284d1f2007-04-15 00:07:55 +000010076bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
10077 BasicBlock *StoreBB = SI.getParent();
10078
10079 // Check to see if the successor block has exactly two incoming edges. If
10080 // so, see if the other predecessor contains a store to the same location.
10081 // if so, insert a PHI node (if needed) and move the stores down.
Chris Lattner31755a02007-04-15 01:02:18 +000010082 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Chris Lattner3284d1f2007-04-15 00:07:55 +000010083
10084 // Determine whether Dest has exactly two predecessors and, if so, compute
10085 // the other predecessor.
Chris Lattner31755a02007-04-15 01:02:18 +000010086 pred_iterator PI = pred_begin(DestBB);
10087 BasicBlock *OtherBB = 0;
Chris Lattner3284d1f2007-04-15 00:07:55 +000010088 if (*PI != StoreBB)
Chris Lattner31755a02007-04-15 01:02:18 +000010089 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000010090 ++PI;
Chris Lattner31755a02007-04-15 01:02:18 +000010091 if (PI == pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000010092 return false;
10093
10094 if (*PI != StoreBB) {
Chris Lattner31755a02007-04-15 01:02:18 +000010095 if (OtherBB)
Chris Lattner3284d1f2007-04-15 00:07:55 +000010096 return false;
Chris Lattner31755a02007-04-15 01:02:18 +000010097 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000010098 }
Chris Lattner31755a02007-04-15 01:02:18 +000010099 if (++PI != pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000010100 return false;
10101
10102
Chris Lattner31755a02007-04-15 01:02:18 +000010103 // Verify that the other block ends in a branch and is not otherwise empty.
10104 BasicBlock::iterator BBI = OtherBB->getTerminator();
Chris Lattner3284d1f2007-04-15 00:07:55 +000010105 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
Chris Lattner31755a02007-04-15 01:02:18 +000010106 if (!OtherBr || BBI == OtherBB->begin())
Chris Lattner3284d1f2007-04-15 00:07:55 +000010107 return false;
10108
Chris Lattner31755a02007-04-15 01:02:18 +000010109 // If the other block ends in an unconditional branch, check for the 'if then
10110 // else' case. there is an instruction before the branch.
10111 StoreInst *OtherStore = 0;
10112 if (OtherBr->isUnconditional()) {
10113 // If this isn't a store, or isn't a store to the same location, bail out.
10114 --BBI;
10115 OtherStore = dyn_cast<StoreInst>(BBI);
10116 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
10117 return false;
10118 } else {
Chris Lattnerd717c182007-05-05 22:32:24 +000010119 // Otherwise, the other block ended with a conditional branch. If one of the
Chris Lattner31755a02007-04-15 01:02:18 +000010120 // destinations is StoreBB, then we have the if/then case.
10121 if (OtherBr->getSuccessor(0) != StoreBB &&
10122 OtherBr->getSuccessor(1) != StoreBB)
10123 return false;
10124
10125 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
Chris Lattnerd717c182007-05-05 22:32:24 +000010126 // if/then triangle. See if there is a store to the same ptr as SI that
10127 // lives in OtherBB.
Chris Lattner31755a02007-04-15 01:02:18 +000010128 for (;; --BBI) {
10129 // Check to see if we find the matching store.
10130 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
10131 if (OtherStore->getOperand(1) != SI.getOperand(1))
10132 return false;
10133 break;
10134 }
Chris Lattnerd717c182007-05-05 22:32:24 +000010135 // If we find something that may be using the stored value, or if we run
10136 // out of instructions, we can't do the xform.
Chris Lattner31755a02007-04-15 01:02:18 +000010137 if (isa<LoadInst>(BBI) || BBI->mayWriteToMemory() ||
10138 BBI == OtherBB->begin())
10139 return false;
10140 }
10141
10142 // In order to eliminate the store in OtherBr, we have to
10143 // make sure nothing reads the stored value in StoreBB.
10144 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
10145 // FIXME: This should really be AA driven.
10146 if (isa<LoadInst>(I) || I->mayWriteToMemory())
10147 return false;
10148 }
10149 }
Chris Lattner3284d1f2007-04-15 00:07:55 +000010150
Chris Lattner31755a02007-04-15 01:02:18 +000010151 // Insert a PHI node now if we need it.
Chris Lattner3284d1f2007-04-15 00:07:55 +000010152 Value *MergedVal = OtherStore->getOperand(0);
10153 if (MergedVal != SI.getOperand(0)) {
10154 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
10155 PN->reserveOperandSpace(2);
10156 PN->addIncoming(SI.getOperand(0), SI.getParent());
Chris Lattner31755a02007-04-15 01:02:18 +000010157 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
10158 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Chris Lattner3284d1f2007-04-15 00:07:55 +000010159 }
10160
10161 // Advance to a place where it is safe to insert the new store and
10162 // insert it.
Chris Lattner31755a02007-04-15 01:02:18 +000010163 BBI = DestBB->begin();
Chris Lattner3284d1f2007-04-15 00:07:55 +000010164 while (isa<PHINode>(BBI)) ++BBI;
10165 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
10166 OtherStore->isVolatile()), *BBI);
10167
10168 // Nuke the old stores.
10169 EraseInstFromFunction(SI);
10170 EraseInstFromFunction(*OtherStore);
10171 ++NumCombined;
10172 return true;
10173}
10174
Chris Lattner2f503e62005-01-31 05:36:43 +000010175
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000010176Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
10177 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +000010178 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000010179 BasicBlock *TrueDest;
10180 BasicBlock *FalseDest;
10181 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
10182 !isa<Constant>(X)) {
10183 // Swap Destinations and condition...
10184 BI.setCondition(X);
10185 BI.setSuccessor(0, FalseDest);
10186 BI.setSuccessor(1, TrueDest);
10187 return &BI;
10188 }
10189
Reid Spencere4d87aa2006-12-23 06:05:41 +000010190 // Cannonicalize fcmp_one -> fcmp_oeq
10191 FCmpInst::Predicate FPred; Value *Y;
10192 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
10193 TrueDest, FalseDest)))
10194 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
10195 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
10196 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000010197 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
Chris Lattner6934a042007-02-11 01:23:03 +000010198 Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
10199 NewSCC->takeName(I);
Reid Spencere4d87aa2006-12-23 06:05:41 +000010200 // Swap Destinations and condition...
10201 BI.setCondition(NewSCC);
10202 BI.setSuccessor(0, FalseDest);
10203 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000010204 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000010205 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000010206 AddToWorkList(NewSCC);
Reid Spencere4d87aa2006-12-23 06:05:41 +000010207 return &BI;
10208 }
10209
10210 // Cannonicalize icmp_ne -> icmp_eq
10211 ICmpInst::Predicate IPred;
10212 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
10213 TrueDest, FalseDest)))
10214 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
10215 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
10216 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
10217 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000010218 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
Chris Lattner6934a042007-02-11 01:23:03 +000010219 Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
10220 NewSCC->takeName(I);
Chris Lattner40f5d702003-06-04 05:10:11 +000010221 // Swap Destinations and condition...
Chris Lattneracd1f0f2004-07-30 07:50:03 +000010222 BI.setCondition(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000010223 BI.setSuccessor(0, FalseDest);
10224 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000010225 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000010226 I->eraseFromParent();;
Chris Lattnerdbab3862007-03-02 21:28:56 +000010227 AddToWorkList(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000010228 return &BI;
10229 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010230
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000010231 return 0;
10232}
Chris Lattner0864acf2002-11-04 16:18:53 +000010233
Chris Lattner46238a62004-07-03 00:26:11 +000010234Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
10235 Value *Cond = SI.getCondition();
10236 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
10237 if (I->getOpcode() == Instruction::Add)
10238 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
10239 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
10240 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattnere87597f2004-10-16 18:11:37 +000010241 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +000010242 AddRHS));
10243 SI.setOperand(0, I->getOperand(0));
Chris Lattnerdbab3862007-03-02 21:28:56 +000010244 AddToWorkList(I);
Chris Lattner46238a62004-07-03 00:26:11 +000010245 return &SI;
10246 }
10247 }
10248 return 0;
10249}
10250
Chris Lattner220b0cf2006-03-05 00:22:33 +000010251/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
10252/// is to leave as a vector operation.
10253static bool CheapToScalarize(Value *V, bool isConstant) {
10254 if (isa<ConstantAggregateZero>(V))
10255 return true;
Reid Spencer9d6565a2007-02-15 02:26:10 +000010256 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000010257 if (isConstant) return true;
10258 // If all elts are the same, we can extract.
10259 Constant *Op0 = C->getOperand(0);
10260 for (unsigned i = 1; i < C->getNumOperands(); ++i)
10261 if (C->getOperand(i) != Op0)
10262 return false;
10263 return true;
10264 }
10265 Instruction *I = dyn_cast<Instruction>(V);
10266 if (!I) return false;
10267
10268 // Insert element gets simplified to the inserted element or is deleted if
10269 // this is constant idx extract element and its a constant idx insertelt.
10270 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
10271 isa<ConstantInt>(I->getOperand(2)))
10272 return true;
10273 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
10274 return true;
10275 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
10276 if (BO->hasOneUse() &&
10277 (CheapToScalarize(BO->getOperand(0), isConstant) ||
10278 CheapToScalarize(BO->getOperand(1), isConstant)))
10279 return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +000010280 if (CmpInst *CI = dyn_cast<CmpInst>(I))
10281 if (CI->hasOneUse() &&
10282 (CheapToScalarize(CI->getOperand(0), isConstant) ||
10283 CheapToScalarize(CI->getOperand(1), isConstant)))
10284 return true;
Chris Lattner220b0cf2006-03-05 00:22:33 +000010285
10286 return false;
10287}
10288
Chris Lattnerd2b7cec2007-02-14 05:52:17 +000010289/// Read and decode a shufflevector mask.
10290///
10291/// It turns undef elements into values that are larger than the number of
10292/// elements in the input.
Chris Lattner863bcff2006-05-25 23:48:38 +000010293static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
10294 unsigned NElts = SVI->getType()->getNumElements();
10295 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
10296 return std::vector<unsigned>(NElts, 0);
10297 if (isa<UndefValue>(SVI->getOperand(2)))
10298 return std::vector<unsigned>(NElts, 2*NElts);
10299
10300 std::vector<unsigned> Result;
Reid Spencer9d6565a2007-02-15 02:26:10 +000010301 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Chris Lattner863bcff2006-05-25 23:48:38 +000010302 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
10303 if (isa<UndefValue>(CP->getOperand(i)))
10304 Result.push_back(NElts*2); // undef -> 8
10305 else
Reid Spencerb83eb642006-10-20 07:07:24 +000010306 Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
Chris Lattner863bcff2006-05-25 23:48:38 +000010307 return Result;
10308}
10309
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010310/// FindScalarElement - Given a vector and an element number, see if the scalar
10311/// value is already around as a register, for example if it were inserted then
10312/// extracted from the vector.
10313static Value *FindScalarElement(Value *V, unsigned EltNo) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000010314 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
10315 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +000010316 unsigned Width = PTy->getNumElements();
10317 if (EltNo >= Width) // Out of range access.
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010318 return UndefValue::get(PTy->getElementType());
10319
10320 if (isa<UndefValue>(V))
10321 return UndefValue::get(PTy->getElementType());
10322 else if (isa<ConstantAggregateZero>(V))
10323 return Constant::getNullValue(PTy->getElementType());
Reid Spencer9d6565a2007-02-15 02:26:10 +000010324 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010325 return CP->getOperand(EltNo);
10326 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
10327 // If this is an insert to a variable element, we don't know what it is.
Reid Spencerb83eb642006-10-20 07:07:24 +000010328 if (!isa<ConstantInt>(III->getOperand(2)))
10329 return 0;
10330 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010331
10332 // If this is an insert to the element we are looking for, return the
10333 // inserted value.
Reid Spencerb83eb642006-10-20 07:07:24 +000010334 if (EltNo == IIElt)
10335 return III->getOperand(1);
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010336
10337 // Otherwise, the insertelement doesn't modify the value, recurse on its
10338 // vector input.
10339 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner389a6f52006-04-10 23:06:36 +000010340 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Chris Lattner863bcff2006-05-25 23:48:38 +000010341 unsigned InEl = getShuffleMask(SVI)[EltNo];
10342 if (InEl < Width)
10343 return FindScalarElement(SVI->getOperand(0), InEl);
10344 else if (InEl < Width*2)
10345 return FindScalarElement(SVI->getOperand(1), InEl - Width);
10346 else
10347 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010348 }
10349
10350 // Otherwise, we don't know.
10351 return 0;
10352}
10353
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010354Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010355
Dan Gohman07a96762007-07-16 14:29:03 +000010356 // If vector val is undef, replace extract with scalar undef.
Chris Lattner1f13c882006-03-31 18:25:14 +000010357 if (isa<UndefValue>(EI.getOperand(0)))
10358 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10359
Dan Gohman07a96762007-07-16 14:29:03 +000010360 // If vector val is constant 0, replace extract with scalar 0.
Chris Lattner1f13c882006-03-31 18:25:14 +000010361 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
10362 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
10363
Reid Spencer9d6565a2007-02-15 02:26:10 +000010364 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Dan Gohman07a96762007-07-16 14:29:03 +000010365 // If vector val is constant with uniform operands, replace EI
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010366 // with that operand
Chris Lattner220b0cf2006-03-05 00:22:33 +000010367 Constant *op0 = C->getOperand(0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010368 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +000010369 if (C->getOperand(i) != op0) {
10370 op0 = 0;
10371 break;
10372 }
10373 if (op0)
10374 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010375 }
Chris Lattner220b0cf2006-03-05 00:22:33 +000010376
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010377 // If extracting a specified index from the vector, see if we can recursively
10378 // find a previously computed scalar that was inserted into the vector.
Reid Spencerb83eb642006-10-20 07:07:24 +000010379 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner85464092007-04-09 01:37:55 +000010380 unsigned IndexVal = IdxC->getZExtValue();
10381 unsigned VectorWidth =
10382 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
10383
10384 // If this is extracting an invalid index, turn this into undef, to avoid
10385 // crashing the code below.
10386 if (IndexVal >= VectorWidth)
10387 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10388
Chris Lattner867b99f2006-10-05 06:55:50 +000010389 // This instruction only demands the single element from the input vector.
10390 // If the input vector has a single use, simplify it based on this use
10391 // property.
Chris Lattner85464092007-04-09 01:37:55 +000010392 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Chris Lattner867b99f2006-10-05 06:55:50 +000010393 uint64_t UndefElts;
10394 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Reid Spencerb83eb642006-10-20 07:07:24 +000010395 1 << IndexVal,
Chris Lattner867b99f2006-10-05 06:55:50 +000010396 UndefElts)) {
10397 EI.setOperand(0, V);
10398 return &EI;
10399 }
10400 }
10401
Reid Spencerb83eb642006-10-20 07:07:24 +000010402 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010403 return ReplaceInstUsesWith(EI, Elt);
Chris Lattnerb7300fa2007-04-14 23:02:14 +000010404
10405 // If the this extractelement is directly using a bitcast from a vector of
10406 // the same number of elements, see if we can find the source element from
10407 // it. In this case, we will end up needing to bitcast the scalars.
10408 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
10409 if (const VectorType *VT =
10410 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
10411 if (VT->getNumElements() == VectorWidth)
10412 if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
10413 return new BitCastInst(Elt, EI.getType());
10414 }
Chris Lattner389a6f52006-04-10 23:06:36 +000010415 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010416
Chris Lattner73fa49d2006-05-25 22:53:38 +000010417 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010418 if (I->hasOneUse()) {
10419 // Push extractelement into predecessor operation if legal and
10420 // profitable to do so
10421 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000010422 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
10423 if (CheapToScalarize(BO, isConstantElt)) {
10424 ExtractElementInst *newEI0 =
10425 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
10426 EI.getName()+".lhs");
10427 ExtractElementInst *newEI1 =
10428 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
10429 EI.getName()+".rhs");
10430 InsertNewInstBefore(newEI0, EI);
10431 InsertNewInstBefore(newEI1, EI);
10432 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
10433 }
Reid Spencer3ed469c2006-11-02 20:25:50 +000010434 } else if (isa<LoadInst>(I)) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +000010435 unsigned AS =
10436 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +000010437 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
10438 PointerType::get(EI.getType(), AS),EI);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010439 GetElementPtrInst *GEP =
Reid Spencerde331242006-11-29 01:11:01 +000010440 new GetElementPtrInst(Ptr, EI.getOperand(1), I->getName() + ".gep");
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010441 InsertNewInstBefore(GEP, EI);
10442 return new LoadInst(GEP);
Chris Lattner73fa49d2006-05-25 22:53:38 +000010443 }
10444 }
10445 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
10446 // Extracting the inserted element?
10447 if (IE->getOperand(2) == EI.getOperand(1))
10448 return ReplaceInstUsesWith(EI, IE->getOperand(1));
10449 // If the inserted and extracted elements are constants, they must not
10450 // be the same value, extract from the pre-inserted value instead.
10451 if (isa<Constant>(IE->getOperand(2)) &&
10452 isa<Constant>(EI.getOperand(1))) {
10453 AddUsesToWorkList(EI);
10454 EI.setOperand(0, IE->getOperand(0));
10455 return &EI;
10456 }
10457 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
10458 // If this is extracting an element from a shufflevector, figure out where
10459 // it came from and extract from the appropriate input element instead.
Reid Spencerb83eb642006-10-20 07:07:24 +000010460 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
10461 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner863bcff2006-05-25 23:48:38 +000010462 Value *Src;
10463 if (SrcIdx < SVI->getType()->getNumElements())
10464 Src = SVI->getOperand(0);
10465 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
10466 SrcIdx -= SVI->getType()->getNumElements();
10467 Src = SVI->getOperand(1);
10468 } else {
10469 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +000010470 }
Chris Lattner867b99f2006-10-05 06:55:50 +000010471 return new ExtractElementInst(Src, SrcIdx);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010472 }
10473 }
Chris Lattner73fa49d2006-05-25 22:53:38 +000010474 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010475 return 0;
10476}
10477
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010478/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
10479/// elements from either LHS or RHS, return the shuffle mask and true.
10480/// Otherwise, return false.
10481static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
10482 std::vector<Constant*> &Mask) {
10483 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
10484 "Invalid CollectSingleShuffleElements");
Reid Spencer9d6565a2007-02-15 02:26:10 +000010485 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010486
10487 if (isa<UndefValue>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010488 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010489 return true;
10490 } else if (V == LHS) {
10491 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000010492 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010493 return true;
10494 } else if (V == RHS) {
10495 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000010496 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010497 return true;
10498 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
10499 // If this is an insert of an extract from some other vector, include it.
10500 Value *VecOp = IEI->getOperand(0);
10501 Value *ScalarOp = IEI->getOperand(1);
10502 Value *IdxOp = IEI->getOperand(2);
10503
Chris Lattnerd929f062006-04-27 21:14:21 +000010504 if (!isa<ConstantInt>(IdxOp))
10505 return false;
Reid Spencerb83eb642006-10-20 07:07:24 +000010506 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerd929f062006-04-27 21:14:21 +000010507
10508 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
10509 // Okay, we can handle this if the vector we are insertinting into is
10510 // transitively ok.
10511 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
10512 // If so, update the mask to reflect the inserted undef.
Reid Spencerc5b206b2006-12-31 05:48:39 +000010513 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
Chris Lattnerd929f062006-04-27 21:14:21 +000010514 return true;
10515 }
10516 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
10517 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010518 EI->getOperand(0)->getType() == V->getType()) {
10519 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000010520 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010521
10522 // This must be extracting from either LHS or RHS.
10523 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
10524 // Okay, we can handle this if the vector we are insertinting into is
10525 // transitively ok.
10526 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
10527 // If so, update the mask to reflect the inserted value.
10528 if (EI->getOperand(0) == LHS) {
10529 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000010530 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010531 } else {
10532 assert(EI->getOperand(0) == RHS);
10533 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000010534 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010535
10536 }
10537 return true;
10538 }
10539 }
10540 }
10541 }
10542 }
10543 // TODO: Handle shufflevector here!
10544
10545 return false;
10546}
10547
10548/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
10549/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
10550/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +000010551static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010552 Value *&RHS) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000010553 assert(isa<VectorType>(V->getType()) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010554 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +000010555 "Invalid shuffle!");
Reid Spencer9d6565a2007-02-15 02:26:10 +000010556 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattnerefb47352006-04-15 01:39:45 +000010557
10558 if (isa<UndefValue>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010559 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000010560 return V;
10561 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010562 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
Chris Lattnerefb47352006-04-15 01:39:45 +000010563 return V;
10564 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
10565 // If this is an insert of an extract from some other vector, include it.
10566 Value *VecOp = IEI->getOperand(0);
10567 Value *ScalarOp = IEI->getOperand(1);
10568 Value *IdxOp = IEI->getOperand(2);
10569
10570 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
10571 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
10572 EI->getOperand(0)->getType() == V->getType()) {
10573 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000010574 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
10575 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000010576
10577 // Either the extracted from or inserted into vector must be RHSVec,
10578 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010579 if (EI->getOperand(0) == RHS || RHS == 0) {
10580 RHS = EI->getOperand(0);
10581 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +000010582 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000010583 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000010584 return V;
10585 }
10586
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010587 if (VecOp == RHS) {
10588 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +000010589 // Everything but the extracted element is replaced with the RHS.
10590 for (unsigned i = 0; i != NumElts; ++i) {
10591 if (i != InsertedIdx)
Reid Spencerc5b206b2006-12-31 05:48:39 +000010592 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
Chris Lattnerefb47352006-04-15 01:39:45 +000010593 }
10594 return V;
10595 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010596
10597 // If this insertelement is a chain that comes from exactly these two
10598 // vectors, return the vector and the effective shuffle.
10599 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
10600 return EI->getOperand(0);
10601
Chris Lattnerefb47352006-04-15 01:39:45 +000010602 }
10603 }
10604 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010605 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +000010606
10607 // Otherwise, can't do anything fancy. Return an identity vector.
10608 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000010609 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattnerefb47352006-04-15 01:39:45 +000010610 return V;
10611}
10612
10613Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
10614 Value *VecOp = IE.getOperand(0);
10615 Value *ScalarOp = IE.getOperand(1);
10616 Value *IdxOp = IE.getOperand(2);
10617
Chris Lattner599ded12007-04-09 01:11:16 +000010618 // Inserting an undef or into an undefined place, remove this.
10619 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
10620 ReplaceInstUsesWith(IE, VecOp);
10621
Chris Lattnerefb47352006-04-15 01:39:45 +000010622 // If the inserted element was extracted from some other vector, and if the
10623 // indexes are constant, try to turn this into a shufflevector operation.
10624 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
10625 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
10626 EI->getOperand(0)->getType() == IE.getType()) {
10627 unsigned NumVectorElts = IE.getType()->getNumElements();
Chris Lattnere34e9a22007-04-14 23:32:02 +000010628 unsigned ExtractedIdx =
10629 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Reid Spencerb83eb642006-10-20 07:07:24 +000010630 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000010631
10632 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
10633 return ReplaceInstUsesWith(IE, VecOp);
10634
10635 if (InsertedIdx >= NumVectorElts) // Out of range insert.
10636 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
10637
10638 // If we are extracting a value from a vector, then inserting it right
10639 // back into the same place, just use the input vector.
10640 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
10641 return ReplaceInstUsesWith(IE, VecOp);
10642
10643 // We could theoretically do this for ANY input. However, doing so could
10644 // turn chains of insertelement instructions into a chain of shufflevector
10645 // instructions, and right now we do not merge shufflevectors. As such,
10646 // only do this in a situation where it is clear that there is benefit.
10647 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
10648 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
10649 // the values of VecOp, except then one read from EIOp0.
10650 // Build a new shuffle mask.
10651 std::vector<Constant*> Mask;
10652 if (isa<UndefValue>(VecOp))
Reid Spencerc5b206b2006-12-31 05:48:39 +000010653 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000010654 else {
10655 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Reid Spencerc5b206b2006-12-31 05:48:39 +000010656 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
Chris Lattnerefb47352006-04-15 01:39:45 +000010657 NumVectorElts));
10658 }
Reid Spencerc5b206b2006-12-31 05:48:39 +000010659 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000010660 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Reid Spencer9d6565a2007-02-15 02:26:10 +000010661 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000010662 }
10663
10664 // If this insertelement isn't used by some other insertelement, turn it
10665 // (and any insertelements it points to), into one big shuffle.
10666 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
10667 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010668 Value *RHS = 0;
10669 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
10670 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
10671 // We now have a shuffle of LHS, RHS, Mask.
Reid Spencer9d6565a2007-02-15 02:26:10 +000010672 return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000010673 }
10674 }
10675 }
10676
10677 return 0;
10678}
10679
10680
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010681Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
10682 Value *LHS = SVI.getOperand(0);
10683 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +000010684 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010685
10686 bool MadeChange = false;
10687
Chris Lattner867b99f2006-10-05 06:55:50 +000010688 // Undefined shuffle mask -> undefined value.
Chris Lattner863bcff2006-05-25 23:48:38 +000010689 if (isa<UndefValue>(SVI.getOperand(2)))
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010690 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
10691
Chris Lattnere4929dd2007-01-05 07:36:08 +000010692 // If we have shuffle(x, undef, mask) and any elements of mask refer to
Chris Lattnerefb47352006-04-15 01:39:45 +000010693 // the undef, change them to undefs.
Chris Lattnere4929dd2007-01-05 07:36:08 +000010694 if (isa<UndefValue>(SVI.getOperand(1))) {
10695 // Scan to see if there are any references to the RHS. If so, replace them
10696 // with undef element refs and set MadeChange to true.
10697 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
10698 if (Mask[i] >= e && Mask[i] != 2*e) {
10699 Mask[i] = 2*e;
10700 MadeChange = true;
10701 }
10702 }
10703
10704 if (MadeChange) {
10705 // Remap any references to RHS to use LHS.
10706 std::vector<Constant*> Elts;
10707 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
10708 if (Mask[i] == 2*e)
10709 Elts.push_back(UndefValue::get(Type::Int32Ty));
10710 else
10711 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
10712 }
Reid Spencer9d6565a2007-02-15 02:26:10 +000010713 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattnere4929dd2007-01-05 07:36:08 +000010714 }
10715 }
Chris Lattnerefb47352006-04-15 01:39:45 +000010716
Chris Lattner863bcff2006-05-25 23:48:38 +000010717 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
10718 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
10719 if (LHS == RHS || isa<UndefValue>(LHS)) {
10720 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010721 // shuffle(undef,undef,mask) -> undef.
10722 return ReplaceInstUsesWith(SVI, LHS);
10723 }
10724
Chris Lattner863bcff2006-05-25 23:48:38 +000010725 // Remap any references to RHS to use LHS.
10726 std::vector<Constant*> Elts;
10727 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000010728 if (Mask[i] >= 2*e)
Reid Spencerc5b206b2006-12-31 05:48:39 +000010729 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000010730 else {
10731 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
10732 (Mask[i] < e && isa<UndefValue>(LHS)))
10733 Mask[i] = 2*e; // Turn into undef.
10734 else
10735 Mask[i] &= (e-1); // Force to LHS.
Reid Spencerc5b206b2006-12-31 05:48:39 +000010736 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000010737 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010738 }
Chris Lattner863bcff2006-05-25 23:48:38 +000010739 SVI.setOperand(0, SVI.getOperand(1));
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010740 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Reid Spencer9d6565a2007-02-15 02:26:10 +000010741 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000010742 LHS = SVI.getOperand(0);
10743 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010744 MadeChange = true;
10745 }
10746
Chris Lattner7b2e27922006-05-26 00:29:06 +000010747 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +000010748 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +000010749
Chris Lattner863bcff2006-05-25 23:48:38 +000010750 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
10751 if (Mask[i] >= e*2) continue; // Ignore undef values.
10752 // Is this an identity shuffle of the LHS value?
10753 isLHSID &= (Mask[i] == i);
10754
10755 // Is this an identity shuffle of the RHS value?
10756 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +000010757 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010758
Chris Lattner863bcff2006-05-25 23:48:38 +000010759 // Eliminate identity shuffles.
10760 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
10761 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010762
Chris Lattner7b2e27922006-05-26 00:29:06 +000010763 // If the LHS is a shufflevector itself, see if we can combine it with this
10764 // one without producing an unusual shuffle. Here we are really conservative:
10765 // we are absolutely afraid of producing a shuffle mask not in the input
10766 // program, because the code gen may not be smart enough to turn a merged
10767 // shuffle into two specific shuffles: it may produce worse code. As such,
10768 // we only merge two shuffles if the result is one of the two input shuffle
10769 // masks. In this case, merging the shuffles just removes one instruction,
10770 // which we know is safe. This is good for things like turning:
10771 // (splat(splat)) -> splat.
10772 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
10773 if (isa<UndefValue>(RHS)) {
10774 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
10775
10776 std::vector<unsigned> NewMask;
10777 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
10778 if (Mask[i] >= 2*e)
10779 NewMask.push_back(2*e);
10780 else
10781 NewMask.push_back(LHSMask[Mask[i]]);
10782
10783 // If the result mask is equal to the src shuffle or this shuffle mask, do
10784 // the replacement.
10785 if (NewMask == LHSMask || NewMask == Mask) {
10786 std::vector<Constant*> Elts;
10787 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
10788 if (NewMask[i] >= e*2) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010789 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000010790 } else {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010791 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000010792 }
10793 }
10794 return new ShuffleVectorInst(LHSSVI->getOperand(0),
10795 LHSSVI->getOperand(1),
Reid Spencer9d6565a2007-02-15 02:26:10 +000010796 ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000010797 }
10798 }
10799 }
Chris Lattnerc5eff442007-01-30 22:32:46 +000010800
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010801 return MadeChange ? &SVI : 0;
10802}
10803
10804
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010805
Chris Lattnerea1c4542004-12-08 23:43:58 +000010806
10807/// TryToSinkInstruction - Try to move the specified instruction from its
10808/// current block into the beginning of DestBlock, which can only happen if it's
10809/// safe to move the instruction past all of the instructions between it and the
10810/// end of its block.
10811static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
10812 assert(I->hasOneUse() && "Invariants didn't hold!");
10813
Chris Lattner108e9022005-10-27 17:13:11 +000010814 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
10815 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
Misha Brukmanfd939082005-04-21 23:48:37 +000010816
Chris Lattnerea1c4542004-12-08 23:43:58 +000010817 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +000010818 if (isa<AllocaInst>(I) && I->getParent() ==
10819 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +000010820 return false;
10821
Chris Lattner96a52a62004-12-09 07:14:34 +000010822 // We can only sink load instructions if there is nothing between the load and
10823 // the end of block that could change the value.
10824 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattner96a52a62004-12-09 07:14:34 +000010825 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
10826 Scan != E; ++Scan)
10827 if (Scan->mayWriteToMemory())
10828 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +000010829 }
Chris Lattnerea1c4542004-12-08 23:43:58 +000010830
10831 BasicBlock::iterator InsertPos = DestBlock->begin();
10832 while (isa<PHINode>(InsertPos)) ++InsertPos;
10833
Chris Lattner4bc5f802005-08-08 19:11:57 +000010834 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +000010835 ++NumSunkInst;
10836 return true;
10837}
10838
Chris Lattnerf4f5a772006-05-10 19:00:36 +000010839
10840/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
10841/// all reachable code to the worklist.
10842///
10843/// This has a couple of tricks to make the code faster and more powerful. In
10844/// particular, we constant fold and DCE instructions as we go, to avoid adding
10845/// them to the worklist (this significantly speeds up instcombine on code where
10846/// many instructions are dead or constant). Additionally, if we find a branch
10847/// whose condition is a known constant, we only visit the reachable successors.
10848///
10849static void AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +000010850 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +000010851 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +000010852 const TargetData *TD) {
Chris Lattner2c7718a2007-03-23 19:17:18 +000010853 std::vector<BasicBlock*> Worklist;
10854 Worklist.push_back(BB);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000010855
Chris Lattner2c7718a2007-03-23 19:17:18 +000010856 while (!Worklist.empty()) {
10857 BB = Worklist.back();
10858 Worklist.pop_back();
10859
10860 // We have now visited this block! If we've already been here, ignore it.
10861 if (!Visited.insert(BB)) continue;
10862
10863 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
10864 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000010865
Chris Lattner2c7718a2007-03-23 19:17:18 +000010866 // DCE instruction if trivially dead.
10867 if (isInstructionTriviallyDead(Inst)) {
10868 ++NumDeadInst;
10869 DOUT << "IC: DCE: " << *Inst;
10870 Inst->eraseFromParent();
10871 continue;
10872 }
10873
10874 // ConstantProp instruction if trivially constant.
10875 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
10876 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
10877 Inst->replaceAllUsesWith(C);
10878 ++NumConstProp;
10879 Inst->eraseFromParent();
10880 continue;
10881 }
Chris Lattner3ccc6bc2007-07-20 22:06:41 +000010882
Chris Lattner2c7718a2007-03-23 19:17:18 +000010883 IC.AddToWorkList(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000010884 }
Chris Lattner2c7718a2007-03-23 19:17:18 +000010885
10886 // Recursively visit successors. If this is a branch or switch on a
10887 // constant, only visit the reachable successor.
Nick Lewycky91436992008-03-09 08:50:23 +000010888 if (BB->getUnwindDest())
10889 Worklist.push_back(BB->getUnwindDest());
Chris Lattner2c7718a2007-03-23 19:17:18 +000010890 TerminatorInst *TI = BB->getTerminator();
10891 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
10892 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
10893 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky91436992008-03-09 08:50:23 +000010894 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
10895 if (ReachableBB != BB->getUnwindDest())
10896 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000010897 continue;
10898 }
10899 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
10900 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
10901 // See if this is an explicit destination.
10902 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
10903 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky91436992008-03-09 08:50:23 +000010904 BasicBlock *ReachableBB = SI->getSuccessor(i);
10905 if (ReachableBB != BB->getUnwindDest())
10906 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000010907 continue;
10908 }
10909
10910 // Otherwise it is the default destination.
10911 Worklist.push_back(SI->getSuccessor(0));
10912 continue;
10913 }
10914 }
10915
10916 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
10917 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +000010918 }
Chris Lattnerf4f5a772006-05-10 19:00:36 +000010919}
10920
Chris Lattnerec9c3582007-03-03 02:04:50 +000010921bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000010922 bool Changed = false;
Chris Lattnerbc61e662003-11-02 05:57:39 +000010923 TD = &getAnalysis<TargetData>();
Chris Lattnerec9c3582007-03-03 02:04:50 +000010924
10925 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
10926 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +000010927
Chris Lattnerb3d59702005-07-07 20:40:38 +000010928 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +000010929 // Do a depth-first traversal of the function, populate the worklist with
10930 // the reachable instructions. Ignore blocks that are not reachable. Keep
10931 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +000010932 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerdbab3862007-03-02 21:28:56 +000010933 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +000010934
Chris Lattnerb3d59702005-07-07 20:40:38 +000010935 // Do a quick scan over the function. If we find any blocks that are
10936 // unreachable, remove any instructions inside of them. This prevents
10937 // the instcombine code from having to deal with some bad special cases.
10938 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
10939 if (!Visited.count(BB)) {
10940 Instruction *Term = BB->getTerminator();
10941 while (Term != BB->begin()) { // Remove instrs bottom-up
10942 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +000010943
Bill Wendlingb7427032006-11-26 09:46:52 +000010944 DOUT << "IC: DCE: " << *I;
Chris Lattnerb3d59702005-07-07 20:40:38 +000010945 ++NumDeadInst;
10946
10947 if (!I->use_empty())
10948 I->replaceAllUsesWith(UndefValue::get(I->getType()));
10949 I->eraseFromParent();
10950 }
10951 }
10952 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000010953
Chris Lattnerdbab3862007-03-02 21:28:56 +000010954 while (!Worklist.empty()) {
10955 Instruction *I = RemoveOneFromWorkList();
10956 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +000010957
Chris Lattner8c8c66a2006-05-11 17:11:52 +000010958 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +000010959 if (isInstructionTriviallyDead(I)) {
Chris Lattner8c8c66a2006-05-11 17:11:52 +000010960 // Add operands to the worklist.
Chris Lattner4bb7c022003-10-06 17:11:01 +000010961 if (I->getNumOperands() < 4)
Chris Lattner7bcc0e72004-02-28 05:22:00 +000010962 AddUsesToWorkList(*I);
Chris Lattner62b14df2002-09-02 04:59:56 +000010963 ++NumDeadInst;
Chris Lattner4bb7c022003-10-06 17:11:01 +000010964
Bill Wendlingb7427032006-11-26 09:46:52 +000010965 DOUT << "IC: DCE: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000010966
10967 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000010968 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000010969 continue;
10970 }
Chris Lattner62b14df2002-09-02 04:59:56 +000010971
Chris Lattner8c8c66a2006-05-11 17:11:52 +000010972 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattner0a19ffa2007-01-30 23:16:15 +000010973 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Bill Wendlingb7427032006-11-26 09:46:52 +000010974 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000010975
Chris Lattner8c8c66a2006-05-11 17:11:52 +000010976 // Add operands to the worklist.
Chris Lattner7bcc0e72004-02-28 05:22:00 +000010977 AddUsesToWorkList(*I);
Chris Lattnerc736d562002-12-05 22:41:53 +000010978 ReplaceInstUsesWith(*I, C);
10979
Chris Lattner62b14df2002-09-02 04:59:56 +000010980 ++NumConstProp;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000010981 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000010982 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000010983 continue;
Chris Lattner62b14df2002-09-02 04:59:56 +000010984 }
Chris Lattner4bb7c022003-10-06 17:11:01 +000010985
Chris Lattnerea1c4542004-12-08 23:43:58 +000010986 // See if we can trivially sink this instruction to a successor basic block.
10987 if (I->hasOneUse()) {
10988 BasicBlock *BB = I->getParent();
10989 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
10990 if (UserParent != BB) {
10991 bool UserIsSuccessor = false;
10992 // See if the user is one of our successors.
10993 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
10994 if (*SI == UserParent) {
10995 UserIsSuccessor = true;
10996 break;
10997 }
10998
10999 // If the user is one of our immediate successors, and if that successor
11000 // only has us as a predecessors (we'd have to split the critical edge
11001 // otherwise), we can keep going.
11002 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
11003 next(pred_begin(UserParent)) == pred_end(UserParent))
11004 // Okay, the CFG is simple enough, try to sink this instruction.
11005 Changed |= TryToSinkInstruction(I, UserParent);
11006 }
11007 }
11008
Chris Lattner8a2a3112001-12-14 16:52:21 +000011009 // Now that we have an instruction, try combining it to simplify it...
Reid Spencera9b81012007-03-26 17:44:01 +000011010#ifndef NDEBUG
11011 std::string OrigI;
11012#endif
11013 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
Chris Lattner90ac28c2002-08-02 19:29:35 +000011014 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +000011015 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011016 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000011017 if (Result != I) {
Bill Wendlingb7427032006-11-26 09:46:52 +000011018 DOUT << "IC: Old = " << *I
11019 << " New = " << *Result;
Chris Lattner0cea42a2004-03-13 23:54:27 +000011020
Chris Lattnerf523d062004-06-09 05:08:07 +000011021 // Everything uses the new instruction now.
11022 I->replaceAllUsesWith(Result);
11023
11024 // Push the new instruction and any users onto the worklist.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011025 AddToWorkList(Result);
Chris Lattnerf523d062004-06-09 05:08:07 +000011026 AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011027
Chris Lattner6934a042007-02-11 01:23:03 +000011028 // Move the name to the new instruction first.
11029 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011030
11031 // Insert the new instruction into the basic block...
11032 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +000011033 BasicBlock::iterator InsertPos = I;
11034
11035 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
11036 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
11037 ++InsertPos;
11038
11039 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011040
Chris Lattner00d51312004-05-01 23:27:23 +000011041 // Make sure that we reprocess all operands now that we reduced their
11042 // use counts.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011043 AddUsesToWorkList(*I);
Chris Lattner216d4d82004-05-01 23:19:52 +000011044
Chris Lattnerf523d062004-06-09 05:08:07 +000011045 // Instructions can end up on the worklist more than once. Make sure
11046 // we do not process an instruction that has been deleted.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011047 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011048
11049 // Erase the old instruction.
11050 InstParent->getInstList().erase(I);
Chris Lattner7e708292002-06-25 16:13:24 +000011051 } else {
Evan Chengc7baf682007-03-27 16:44:48 +000011052#ifndef NDEBUG
Reid Spencera9b81012007-03-26 17:44:01 +000011053 DOUT << "IC: Mod = " << OrigI
11054 << " New = " << *I;
Evan Chengc7baf682007-03-27 16:44:48 +000011055#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +000011056
Chris Lattner90ac28c2002-08-02 19:29:35 +000011057 // If the instruction was modified, it's possible that it is now dead.
11058 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +000011059 if (isInstructionTriviallyDead(I)) {
11060 // Make sure we process all operands now that we are reducing their
11061 // use counts.
Chris Lattnerec9c3582007-03-03 02:04:50 +000011062 AddUsesToWorkList(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000011063
Chris Lattner00d51312004-05-01 23:27:23 +000011064 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011065 // occurrences of this instruction.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011066 RemoveFromWorkList(I);
Chris Lattner2f503e62005-01-31 05:36:43 +000011067 I->eraseFromParent();
Chris Lattnerf523d062004-06-09 05:08:07 +000011068 } else {
Chris Lattnerec9c3582007-03-03 02:04:50 +000011069 AddToWorkList(I);
11070 AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +000011071 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000011072 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011073 Changed = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +000011074 }
11075 }
11076
Chris Lattnerec9c3582007-03-03 02:04:50 +000011077 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattnera9ff5eb2007-08-05 08:47:58 +000011078
11079 // Do an explicit clear, this shrinks the map if needed.
11080 WorklistMap.clear();
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011081 return Changed;
Chris Lattnerbd0ef772002-02-26 21:46:54 +000011082}
11083
Chris Lattnerec9c3582007-03-03 02:04:50 +000011084
11085bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +000011086 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
11087
Chris Lattnerec9c3582007-03-03 02:04:50 +000011088 bool EverMadeChange = false;
11089
11090 // Iterate while there is work to do.
11091 unsigned Iteration = 0;
11092 while (DoOneIteration(F, Iteration++))
11093 EverMadeChange = true;
11094 return EverMadeChange;
11095}
11096
Brian Gaeke96d4bf72004-07-27 17:43:21 +000011097FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011098 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +000011099}
Brian Gaeked0fde302003-11-11 22:41:34 +000011100