blob: 65548aff0452fa07d0522d7fce6bbe97a72095aa [file] [log] [blame]
Chris Lattner233f7dc2002-08-12 21:17:25 +00001//===- InstructionCombining.cpp - Combine multiple instructions -----------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner8a2a3112001-12-14 16:52:21 +00009//
10// InstructionCombining - Combine instructions to form fewer, simple
Chris Lattner62b14df2002-09-02 04:59:56 +000011// instructions. This pass does not modify the CFG This pass is where algebraic
12// simplification happens.
Chris Lattner8a2a3112001-12-14 16:52:21 +000013//
14// This pass combines things like:
Chris Lattner32ed46b2004-05-04 15:19:33 +000015// %Y = add int %X, 1
16// %Z = add int %Y, 1
Chris Lattner8a2a3112001-12-14 16:52:21 +000017// into:
Chris Lattner32ed46b2004-05-04 15:19:33 +000018// %Z = add int %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.
Chris Lattner2cd91962003-07-23 21:41:57 +000027// 3. SetCC instructions are converted from <,>,<=,>= to ==,!= if possible
28// 4. All SetCC 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 Lattnerbc61e662003-11-02 05:57:39 +000042#include "llvm/Target/TargetData.h"
43#include "llvm/Transforms/Utils/BasicBlockUtils.h"
44#include "llvm/Transforms/Utils/Local.h"
Chris Lattner28977af2004-04-05 01:30:19 +000045#include "llvm/Support/CallSite.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000046#include "llvm/Support/Debug.h"
Chris Lattner28977af2004-04-05 01:30:19 +000047#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattnerdd841ae2002-04-18 17:39:14 +000048#include "llvm/Support/InstVisitor.h"
Chris Lattnerbcd7db52005-08-02 19:16:58 +000049#include "llvm/Support/MathExtras.h"
Chris Lattneracd1f0f2004-07-30 07:50:03 +000050#include "llvm/Support/PatternMatch.h"
Chris Lattnerb3d59702005-07-07 20:40:38 +000051#include "llvm/ADT/DepthFirstIterator.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000052#include "llvm/ADT/Statistic.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000053#include "llvm/ADT/STLExtras.h"
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000054#include <algorithm>
Chris Lattnerdac58ad2006-01-22 23:32:06 +000055#include <iostream>
Chris Lattner67b1e1b2003-12-07 01:24:23 +000056using namespace llvm;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000057using namespace llvm::PatternMatch;
Brian Gaeked0fde302003-11-11 22:41:34 +000058
Chris Lattnerdd841ae2002-04-18 17:39:14 +000059namespace {
Chris Lattnera92f6962002-10-01 22:38:41 +000060 Statistic<> NumCombined ("instcombine", "Number of insts combined");
61 Statistic<> NumConstProp("instcombine", "Number of constant folds");
62 Statistic<> NumDeadInst ("instcombine", "Number of dead inst eliminated");
Chris Lattner9ca96412006-02-08 03:25:32 +000063 Statistic<> NumDeadStore("instcombine", "Number of dead stores eliminated");
Chris Lattnerea1c4542004-12-08 23:43:58 +000064 Statistic<> NumSunkInst ("instcombine", "Number of instructions sunk");
Chris Lattnera92f6962002-10-01 22:38:41 +000065
Chris Lattnerf57b8452002-04-27 06:56:12 +000066 class InstCombiner : public FunctionPass,
Chris Lattnerdd841ae2002-04-18 17:39:14 +000067 public InstVisitor<InstCombiner, Instruction*> {
68 // Worklist of all of the instructions that need to be simplified.
69 std::vector<Instruction*> WorkList;
Chris Lattnerbc61e662003-11-02 05:57:39 +000070 TargetData *TD;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000071
Chris Lattner7bcc0e72004-02-28 05:22:00 +000072 /// AddUsersToWorkList - When an instruction is simplified, add all users of
73 /// the instruction to the work lists because they might get more simplified
74 /// now.
75 ///
Chris Lattner6dce1a72006-02-07 06:56:34 +000076 void AddUsersToWorkList(Value &I) {
Chris Lattner7e708292002-06-25 16:13:24 +000077 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattnerdd841ae2002-04-18 17:39:14 +000078 UI != UE; ++UI)
79 WorkList.push_back(cast<Instruction>(*UI));
80 }
81
Chris Lattner7bcc0e72004-02-28 05:22:00 +000082 /// AddUsesToWorkList - When an instruction is simplified, add operands to
83 /// the work lists because they might get more simplified now.
84 ///
85 void AddUsesToWorkList(Instruction &I) {
86 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
87 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
88 WorkList.push_back(Op);
89 }
90
Chris Lattner62b14df2002-09-02 04:59:56 +000091 // removeFromWorkList - remove all instances of I from the worklist.
92 void removeFromWorkList(Instruction *I);
Chris Lattnerdd841ae2002-04-18 17:39:14 +000093 public:
Chris Lattner7e708292002-06-25 16:13:24 +000094 virtual bool runOnFunction(Function &F);
Chris Lattnerdd841ae2002-04-18 17:39:14 +000095
Chris Lattner97e52e42002-04-28 21:27:06 +000096 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerbc61e662003-11-02 05:57:39 +000097 AU.addRequired<TargetData>();
Chris Lattnercb2610e2002-10-21 20:00:28 +000098 AU.setPreservesCFG();
Chris Lattner97e52e42002-04-28 21:27:06 +000099 }
100
Chris Lattner28977af2004-04-05 01:30:19 +0000101 TargetData &getTargetData() const { return *TD; }
102
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000103 // Visitation implementation - Implement instruction combining for different
104 // instruction types. The semantics are as follows:
105 // Return Value:
106 // null - No change was made
Chris Lattner233f7dc2002-08-12 21:17:25 +0000107 // I - Change was made, I is still valid, I may be dead though
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000108 // otherwise - Change was made, replace I with returned instruction
Misha Brukmanfd939082005-04-21 23:48:37 +0000109 //
Chris Lattner7e708292002-06-25 16:13:24 +0000110 Instruction *visitAdd(BinaryOperator &I);
111 Instruction *visitSub(BinaryOperator &I);
112 Instruction *visitMul(BinaryOperator &I);
113 Instruction *visitDiv(BinaryOperator &I);
114 Instruction *visitRem(BinaryOperator &I);
115 Instruction *visitAnd(BinaryOperator &I);
116 Instruction *visitOr (BinaryOperator &I);
117 Instruction *visitXor(BinaryOperator &I);
Chris Lattner484d3cf2005-04-24 06:59:08 +0000118 Instruction *visitSetCondInst(SetCondInst &I);
119 Instruction *visitSetCondInstWithCastAndCast(SetCondInst &SCI);
120
Chris Lattner574da9b2005-01-13 20:14:25 +0000121 Instruction *FoldGEPSetCC(User *GEPLHS, Value *RHS,
122 Instruction::BinaryOps Cond, Instruction &I);
Chris Lattnerea340052003-03-10 19:16:08 +0000123 Instruction *visitShiftInst(ShiftInst &I);
Chris Lattner4d5542c2006-01-06 07:12:35 +0000124 Instruction *FoldShiftByConstant(Value *Op0, ConstantUInt *Op1,
125 ShiftInst &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000126 Instruction *visitCastInst(CastInst &CI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +0000127 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
128 Instruction *FI);
Chris Lattner3d69f462004-03-12 05:52:32 +0000129 Instruction *visitSelectInst(SelectInst &CI);
Chris Lattner9fe38862003-06-19 17:00:31 +0000130 Instruction *visitCallInst(CallInst &CI);
131 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner7e708292002-06-25 16:13:24 +0000132 Instruction *visitPHINode(PHINode &PN);
133 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner0864acf2002-11-04 16:18:53 +0000134 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner67b1e1b2003-12-07 01:24:23 +0000135 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner833b8a42003-06-26 05:06:25 +0000136 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner2f503e62005-01-31 05:36:43 +0000137 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattnerc4d10eb2003-06-04 04:46:00 +0000138 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner46238a62004-07-03 00:26:11 +0000139 Instruction *visitSwitchInst(SwitchInst &SI);
Robert Bocchino1d7456d2006-01-13 22:48:06 +0000140 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000141
142 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner7e708292002-06-25 16:13:24 +0000143 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner8b170942002-08-09 23:47:40 +0000144
Chris Lattner9fe38862003-06-19 17:00:31 +0000145 private:
Chris Lattnera44d8a22003-10-07 22:32:43 +0000146 Instruction *visitCallSite(CallSite CS);
Chris Lattner9fe38862003-06-19 17:00:31 +0000147 bool transformConstExprCastCall(CallSite CS);
148
Chris Lattner28977af2004-04-05 01:30:19 +0000149 public:
Chris Lattner8b170942002-08-09 23:47:40 +0000150 // InsertNewInstBefore - insert an instruction New before instruction Old
151 // in the program. Add the new instruction to the worklist.
152 //
Chris Lattner955f3312004-09-28 21:48:02 +0000153 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattnere6f9a912002-08-23 18:32:43 +0000154 assert(New && New->getParent() == 0 &&
155 "New instruction already inserted into a basic block!");
Chris Lattner8b170942002-08-09 23:47:40 +0000156 BasicBlock *BB = Old.getParent();
157 BB->getInstList().insert(&Old, New); // Insert inst
158 WorkList.push_back(New); // Add to worklist
Chris Lattner4cb170c2004-02-23 06:38:22 +0000159 return New;
Chris Lattner8b170942002-08-09 23:47:40 +0000160 }
161
Chris Lattner0c967662004-09-24 15:21:34 +0000162 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
163 /// This also adds the cast to the worklist. Finally, this returns the
164 /// cast.
165 Value *InsertCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
166 if (V->getType() == Ty) return V;
Misha Brukmanfd939082005-04-21 23:48:37 +0000167
Chris Lattner0c967662004-09-24 15:21:34 +0000168 Instruction *C = new CastInst(V, Ty, V->getName(), &Pos);
169 WorkList.push_back(C);
170 return C;
171 }
172
Chris Lattner8b170942002-08-09 23:47:40 +0000173 // ReplaceInstUsesWith - This method is to be used when an instruction is
174 // found to be dead, replacable with another preexisting expression. Here
175 // we add all uses of I to the worklist, replace all uses of I with the new
176 // value, then return I, so that the inst combiner will know that I was
177 // modified.
178 //
179 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000180 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner15a76c02004-04-05 02:10:19 +0000181 if (&I != V) {
182 I.replaceAllUsesWith(V);
183 return &I;
184 } else {
185 // If we are replacing the instruction with itself, this must be in a
186 // segment of unreachable code, so just clobber the instruction.
Chris Lattner17be6352004-10-18 02:59:09 +0000187 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +0000188 return &I;
189 }
Chris Lattner8b170942002-08-09 23:47:40 +0000190 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000191
Chris Lattner6dce1a72006-02-07 06:56:34 +0000192 // UpdateValueUsesWith - This method is to be used when an value is
193 // found to be replacable with another preexisting expression or was
194 // updated. Here we add all uses of I to the worklist, replace all uses of
195 // I with the new value (unless the instruction was just updated), then
196 // return true, so that the inst combiner will know that I was modified.
197 //
198 bool UpdateValueUsesWith(Value *Old, Value *New) {
199 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
200 if (Old != New)
201 Old->replaceAllUsesWith(New);
202 if (Instruction *I = dyn_cast<Instruction>(Old))
203 WorkList.push_back(I);
Chris Lattnerf8c36f52006-02-12 08:02:11 +0000204 if (Instruction *I = dyn_cast<Instruction>(New))
205 WorkList.push_back(I);
Chris Lattner6dce1a72006-02-07 06:56:34 +0000206 return true;
207 }
208
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000209 // EraseInstFromFunction - When dealing with an instruction that has side
210 // effects or produces a void value, we can't rely on DCE to delete the
211 // instruction. Instead, visit methods should return the value returned by
212 // this function.
213 Instruction *EraseInstFromFunction(Instruction &I) {
214 assert(I.use_empty() && "Cannot erase instruction that is used!");
215 AddUsesToWorkList(I);
216 removeFromWorkList(&I);
Chris Lattner954f66a2004-11-18 21:41:39 +0000217 I.eraseFromParent();
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000218 return 0; // Don't do anything with FI
219 }
220
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000221 private:
Chris Lattner24c8e382003-07-24 17:35:25 +0000222 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
223 /// InsertBefore instruction. This is specialized a bit to avoid inserting
224 /// casts that are known to not do anything...
225 ///
226 Value *InsertOperandCastBefore(Value *V, const Type *DestTy,
227 Instruction *InsertBefore);
228
Chris Lattnerc8802d22003-03-11 00:12:48 +0000229 // SimplifyCommutative - This performs a few simplifications for commutative
Chris Lattner4e998b22004-09-29 05:07:12 +0000230 // operators.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000231 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000232
Chris Lattner255d8912006-02-11 09:31:47 +0000233 bool SimplifyDemandedBits(Value *V, uint64_t Mask,
234 uint64_t &KnownZero, uint64_t &KnownOne,
235 unsigned Depth = 0);
Chris Lattner4e998b22004-09-29 05:07:12 +0000236
237 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
238 // PHI node as operand #0, see if we can fold the instruction into the PHI
239 // (which is only possible if all operands to the PHI are constants).
240 Instruction *FoldOpIntoPhi(Instruction &I);
241
Chris Lattnerbac32862004-11-14 19:13:23 +0000242 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
243 // operator and they all are only used by the PHI, PHI together their
244 // inputs, and do the operation once, to the result of the PHI.
245 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
246
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000247 Instruction *OptAndOp(Instruction *Op, ConstantIntegral *OpRHS,
248 ConstantIntegral *AndRHS, BinaryOperator &TheAnd);
Chris Lattnerc8e77562005-09-18 04:24:45 +0000249
250 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantIntegral *Mask,
251 bool isSub, Instruction &I);
Chris Lattnera96879a2004-09-29 17:40:11 +0000252 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
253 bool Inside, Instruction &IB);
Chris Lattnerb3f83972005-10-24 06:03:58 +0000254 Instruction *PromoteCastOfAllocation(CastInst &CI, AllocationInst &AI);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000255 };
Chris Lattnerf6293092002-07-23 18:06:35 +0000256
Chris Lattnera6275cc2002-07-26 21:12:46 +0000257 RegisterOpt<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000258}
259
Chris Lattner4f98c562003-03-10 21:43:22 +0000260// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattnere87597f2004-10-16 18:11:37 +0000261// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattner4f98c562003-03-10 21:43:22 +0000262static unsigned getComplexity(Value *V) {
263 if (isa<Instruction>(V)) {
264 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattnere87597f2004-10-16 18:11:37 +0000265 return 3;
266 return 4;
Chris Lattner4f98c562003-03-10 21:43:22 +0000267 }
Chris Lattnere87597f2004-10-16 18:11:37 +0000268 if (isa<Argument>(V)) return 3;
269 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattner4f98c562003-03-10 21:43:22 +0000270}
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000271
Chris Lattnerc8802d22003-03-11 00:12:48 +0000272// isOnlyUse - Return true if this instruction will be deleted if we stop using
273// it.
274static bool isOnlyUse(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000275 return V->hasOneUse() || isa<Constant>(V);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000276}
277
Chris Lattner4cb170c2004-02-23 06:38:22 +0000278// getPromotedType - Return the specified type promoted as it would be to pass
279// though a va_arg area...
280static const Type *getPromotedType(const Type *Ty) {
Chris Lattner5dd04022004-06-17 18:16:02 +0000281 switch (Ty->getTypeID()) {
Chris Lattner4cb170c2004-02-23 06:38:22 +0000282 case Type::SByteTyID:
283 case Type::ShortTyID: return Type::IntTy;
284 case Type::UByteTyID:
285 case Type::UShortTyID: return Type::UIntTy;
286 case Type::FloatTyID: return Type::DoubleTy;
287 default: return Ty;
288 }
289}
290
Chris Lattnereed48272005-09-13 00:40:14 +0000291/// isCast - If the specified operand is a CastInst or a constant expr cast,
292/// return the operand value, otherwise return null.
293static Value *isCast(Value *V) {
294 if (CastInst *I = dyn_cast<CastInst>(V))
295 return I->getOperand(0);
296 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
297 if (CE->getOpcode() == Instruction::Cast)
298 return CE->getOperand(0);
299 return 0;
300}
301
Chris Lattner4f98c562003-03-10 21:43:22 +0000302// SimplifyCommutative - This performs a few simplifications for commutative
303// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000304//
Chris Lattner4f98c562003-03-10 21:43:22 +0000305// 1. Order operands such that they are listed from right (least complex) to
306// left (most complex). This puts constants before unary operators before
307// binary operators.
308//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000309// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
310// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000311//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000312bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000313 bool Changed = false;
314 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
315 Changed = !I.swapOperands();
Misha Brukmanfd939082005-04-21 23:48:37 +0000316
Chris Lattner4f98c562003-03-10 21:43:22 +0000317 if (!I.isAssociative()) return Changed;
318 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000319 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
320 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
321 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner2a9c8472003-05-27 16:40:51 +0000322 Constant *Folded = ConstantExpr::get(I.getOpcode(),
323 cast<Constant>(I.getOperand(1)),
324 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000325 I.setOperand(0, Op->getOperand(0));
326 I.setOperand(1, Folded);
327 return true;
328 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
329 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
330 isOnlyUse(Op) && isOnlyUse(Op1)) {
331 Constant *C1 = cast<Constant>(Op->getOperand(1));
332 Constant *C2 = cast<Constant>(Op1->getOperand(1));
333
334 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner2a9c8472003-05-27 16:40:51 +0000335 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000336 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
337 Op1->getOperand(0),
338 Op1->getName(), &I);
339 WorkList.push_back(New);
340 I.setOperand(0, New);
341 I.setOperand(1, Folded);
342 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000343 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000344 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000345 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000346}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000347
Chris Lattner8d969642003-03-10 23:06:50 +0000348// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
349// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000350//
Chris Lattner8d969642003-03-10 23:06:50 +0000351static inline Value *dyn_castNegVal(Value *V) {
352 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000353 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000354
Chris Lattner0ce85802004-12-14 20:08:06 +0000355 // Constants can be considered to be negated values if they can be folded.
356 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
357 return ConstantExpr::getNeg(C);
Chris Lattner8d969642003-03-10 23:06:50 +0000358 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000359}
360
Chris Lattner8d969642003-03-10 23:06:50 +0000361static inline Value *dyn_castNotVal(Value *V) {
362 if (BinaryOperator::isNot(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000363 return BinaryOperator::getNotArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000364
365 // Constants can be considered to be not'ed values...
Chris Lattner3f2ec392003-04-30 22:34:06 +0000366 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
Chris Lattner448c3232004-06-10 02:12:35 +0000367 return ConstantExpr::getNot(C);
Chris Lattner8d969642003-03-10 23:06:50 +0000368 return 0;
369}
370
Chris Lattnerc8802d22003-03-11 00:12:48 +0000371// dyn_castFoldableMul - If this value is a multiply that can be folded into
372// other computations (because it has a constant operand), return the
Chris Lattner50af16a2004-11-13 19:50:12 +0000373// non-constant operand of the multiply, and set CST to point to the multiplier.
374// Otherwise, return null.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000375//
Chris Lattner50af16a2004-11-13 19:50:12 +0000376static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000377 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner50af16a2004-11-13 19:50:12 +0000378 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000379 if (I->getOpcode() == Instruction::Mul)
Chris Lattner50e60c72004-11-15 05:54:07 +0000380 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000381 return I->getOperand(0);
Chris Lattner50af16a2004-11-13 19:50:12 +0000382 if (I->getOpcode() == Instruction::Shl)
Chris Lattner50e60c72004-11-15 05:54:07 +0000383 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000384 // The multiplier is really 1 << CST.
385 Constant *One = ConstantInt::get(V->getType(), 1);
386 CST = cast<ConstantInt>(ConstantExpr::getShl(One, CST));
387 return I->getOperand(0);
388 }
389 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000390 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000391}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000392
Chris Lattner574da9b2005-01-13 20:14:25 +0000393/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
394/// expression, return it.
395static User *dyn_castGetElementPtr(Value *V) {
396 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
397 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
398 if (CE->getOpcode() == Instruction::GetElementPtr)
399 return cast<User>(V);
400 return false;
401}
402
Chris Lattner955f3312004-09-28 21:48:02 +0000403// AddOne, SubOne - Add or subtract a constant one from an integer constant...
Chris Lattnera96879a2004-09-29 17:40:11 +0000404static ConstantInt *AddOne(ConstantInt *C) {
405 return cast<ConstantInt>(ConstantExpr::getAdd(C,
406 ConstantInt::get(C->getType(), 1)));
Chris Lattner955f3312004-09-28 21:48:02 +0000407}
Chris Lattnera96879a2004-09-29 17:40:11 +0000408static ConstantInt *SubOne(ConstantInt *C) {
409 return cast<ConstantInt>(ConstantExpr::getSub(C,
410 ConstantInt::get(C->getType(), 1)));
Chris Lattner955f3312004-09-28 21:48:02 +0000411}
412
Chris Lattner255d8912006-02-11 09:31:47 +0000413/// GetConstantInType - Return a ConstantInt with the specified type and value.
414///
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000415static ConstantIntegral *GetConstantInType(const Type *Ty, uint64_t Val) {
Chris Lattner255d8912006-02-11 09:31:47 +0000416 if (Ty->isUnsigned())
417 return ConstantUInt::get(Ty, Val);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000418 else if (Ty->getTypeID() == Type::BoolTyID)
419 return ConstantBool::get(Val);
Chris Lattner255d8912006-02-11 09:31:47 +0000420 int64_t SVal = Val;
421 SVal <<= 64-Ty->getPrimitiveSizeInBits();
422 SVal >>= 64-Ty->getPrimitiveSizeInBits();
423 return ConstantSInt::get(Ty, SVal);
424}
425
426
Chris Lattner68d5ff22006-02-09 07:38:58 +0000427/// ComputeMaskedBits - Determine which of the bits specified in Mask are
428/// known to be either zero or one and return them in the KnownZero/KnownOne
429/// bitsets. This code only analyzes bits in Mask, in order to short-circuit
430/// processing.
431static void ComputeMaskedBits(Value *V, uint64_t Mask, uint64_t &KnownZero,
432 uint64_t &KnownOne, unsigned Depth = 0) {
Chris Lattner5931c542005-09-24 23:43:33 +0000433 // Note, we cannot consider 'undef' to be "IsZero" here. The problem is that
434 // we cannot optimize based on the assumption that it is zero without changing
Chris Lattner3bedbd92006-02-07 07:27:52 +0000435 // it to be an explicit zero. If we don't change it to zero, other code could
Chris Lattner5931c542005-09-24 23:43:33 +0000436 // optimized based on the contradictory assumption that it is non-zero.
437 // Because instcombine aggressively folds operations with undef args anyway,
438 // this won't lose us code quality.
Chris Lattner68d5ff22006-02-09 07:38:58 +0000439 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V)) {
440 // We know all of the bits for a constant!
Chris Lattner255d8912006-02-11 09:31:47 +0000441 KnownOne = CI->getZExtValue() & Mask;
Chris Lattner68d5ff22006-02-09 07:38:58 +0000442 KnownZero = ~KnownOne & Mask;
443 return;
444 }
445
446 KnownZero = KnownOne = 0; // Don't know anything.
Chris Lattner74c51a02006-02-07 08:05:22 +0000447 if (Depth == 6 || Mask == 0)
Chris Lattner68d5ff22006-02-09 07:38:58 +0000448 return; // Limit search depth.
449
450 uint64_t KnownZero2, KnownOne2;
Chris Lattner255d8912006-02-11 09:31:47 +0000451 Instruction *I = dyn_cast<Instruction>(V);
452 if (!I) return;
453
454 switch (I->getOpcode()) {
455 case Instruction::And:
456 // If either the LHS or the RHS are Zero, the result is zero.
457 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
458 Mask &= ~KnownZero;
459 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
460 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
461 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
462
463 // Output known-1 bits are only known if set in both the LHS & RHS.
464 KnownOne &= KnownOne2;
465 // Output known-0 are known to be clear if zero in either the LHS | RHS.
466 KnownZero |= KnownZero2;
467 return;
468 case Instruction::Or:
469 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
470 Mask &= ~KnownOne;
471 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
472 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
473 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
474
475 // Output known-0 bits are only known if clear in both the LHS & RHS.
476 KnownZero &= KnownZero2;
477 // Output known-1 are known to be set if set in either the LHS | RHS.
478 KnownOne |= KnownOne2;
479 return;
480 case Instruction::Xor: {
481 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
482 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
483 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
484 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
485
486 // Output known-0 bits are known if clear or set in both the LHS & RHS.
487 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
488 // Output known-1 are known to be set if set in only one of the LHS, RHS.
489 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
490 KnownZero = KnownZeroOut;
491 return;
492 }
493 case Instruction::Select:
494 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
495 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
496 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
497 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
498
499 // Only known if known in both the LHS and RHS.
500 KnownOne &= KnownOne2;
501 KnownZero &= KnownZero2;
502 return;
503 case Instruction::Cast: {
504 const Type *SrcTy = I->getOperand(0)->getType();
505 if (!SrcTy->isIntegral()) return;
506
507 // If this is an integer truncate or noop, just look in the input.
508 if (SrcTy->getPrimitiveSizeInBits() >=
509 I->getType()->getPrimitiveSizeInBits()) {
510 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
Chris Lattner68d5ff22006-02-09 07:38:58 +0000511 return;
512 }
Chris Lattner68d5ff22006-02-09 07:38:58 +0000513
Chris Lattner255d8912006-02-11 09:31:47 +0000514 // Sign or Zero extension. Compute the bits in the result that are not
515 // present in the input.
516 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
517 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
Chris Lattner60de63d2005-10-09 06:36:35 +0000518
Chris Lattner255d8912006-02-11 09:31:47 +0000519 // Handle zero extension.
520 if (!SrcTy->isSigned()) {
521 Mask &= SrcTy->getIntegralTypeMask();
522 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
523 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
524 // The top bits are known to be zero.
525 KnownZero |= NewBits;
526 } else {
527 // Sign extension.
528 Mask &= SrcTy->getIntegralTypeMask();
529 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
530 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner74c51a02006-02-07 08:05:22 +0000531
Chris Lattner255d8912006-02-11 09:31:47 +0000532 // If the sign bit of the input is known set or clear, then we know the
533 // top bits of the result.
534 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
535 if (KnownZero & InSignBit) { // Input sign bit known zero
Chris Lattner68d5ff22006-02-09 07:38:58 +0000536 KnownZero |= NewBits;
Chris Lattner255d8912006-02-11 09:31:47 +0000537 KnownOne &= ~NewBits;
538 } else if (KnownOne & InSignBit) { // Input sign bit known set
539 KnownOne |= NewBits;
540 KnownZero &= ~NewBits;
541 } else { // Input sign bit unknown
542 KnownZero &= ~NewBits;
543 KnownOne &= ~NewBits;
544 }
545 }
546 return;
547 }
548 case Instruction::Shl:
549 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
550 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
551 Mask >>= SA->getValue();
552 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
553 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
554 KnownZero <<= SA->getValue();
555 KnownOne <<= SA->getValue();
556 KnownZero |= (1ULL << SA->getValue())-1; // low bits known zero.
557 return;
558 }
559 break;
560 case Instruction::Shr:
561 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
562 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
563 // Compute the new bits that are at the top now.
564 uint64_t HighBits = (1ULL << SA->getValue())-1;
565 HighBits <<= I->getType()->getPrimitiveSizeInBits()-SA->getValue();
566
567 if (I->getType()->isUnsigned()) { // Unsigned shift right.
568 Mask <<= SA->getValue();
569 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
570 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
571 KnownZero >>= SA->getValue();
572 KnownOne >>= SA->getValue();
573 KnownZero |= HighBits; // high bits known zero.
Chris Lattner68d5ff22006-02-09 07:38:58 +0000574 } else {
Chris Lattner255d8912006-02-11 09:31:47 +0000575 Mask <<= SA->getValue();
576 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
577 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
578 KnownZero >>= SA->getValue();
579 KnownOne >>= SA->getValue();
580
581 // Handle the sign bits.
582 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
583 SignBit >>= SA->getValue(); // Adjust to where it is now in the mask.
584
585 if (KnownZero & SignBit) { // New bits are known zero.
586 KnownZero |= HighBits;
587 } else if (KnownOne & SignBit) { // New bits are known one.
588 KnownOne |= HighBits;
Chris Lattner68d5ff22006-02-09 07:38:58 +0000589 }
590 }
591 return;
Chris Lattner60de63d2005-10-09 06:36:35 +0000592 }
Chris Lattner255d8912006-02-11 09:31:47 +0000593 break;
Chris Lattner5931c542005-09-24 23:43:33 +0000594 }
Chris Lattner74c51a02006-02-07 08:05:22 +0000595}
596
597/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
598/// this predicate to simplify operations downstream. Mask is known to be zero
599/// for bits that V cannot have.
600static bool MaskedValueIsZero(Value *V, uint64_t Mask, unsigned Depth = 0) {
Chris Lattner68d5ff22006-02-09 07:38:58 +0000601 uint64_t KnownZero, KnownOne;
602 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
603 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
604 return (KnownZero & Mask) == Mask;
Chris Lattner5931c542005-09-24 23:43:33 +0000605}
606
Chris Lattner255d8912006-02-11 09:31:47 +0000607/// ShrinkDemandedConstant - Check to see if the specified operand of the
608/// specified instruction is a constant integer. If so, check to see if there
609/// are any bits set in the constant that are not demanded. If so, shrink the
610/// constant and return true.
611static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
612 uint64_t Demanded) {
613 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
614 if (!OpC) return false;
615
616 // If there are no bits set that aren't demanded, nothing to do.
617 if ((~Demanded & OpC->getZExtValue()) == 0)
618 return false;
619
620 // This is producing any bits that are not needed, shrink the RHS.
621 uint64_t Val = Demanded & OpC->getZExtValue();
622 I->setOperand(OpNo, GetConstantInType(OpC->getType(), Val));
623 return true;
624}
625
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000626// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
627// set of known zero and one bits, compute the maximum and minimum values that
628// could have the specified known zero and known one bits, returning them in
629// min/max.
630static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
631 uint64_t KnownZero,
632 uint64_t KnownOne,
633 int64_t &Min, int64_t &Max) {
634 uint64_t TypeBits = Ty->getIntegralTypeMask();
635 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
636
637 uint64_t SignBit = 1ULL << (Ty->getPrimitiveSizeInBits()-1);
638
639 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
640 // bit if it is unknown.
641 Min = KnownOne;
642 Max = KnownOne|UnknownBits;
643
644 if (SignBit & UnknownBits) { // Sign bit is unknown
645 Min |= SignBit;
646 Max &= ~SignBit;
647 }
648
649 // Sign extend the min/max values.
650 int ShAmt = 64-Ty->getPrimitiveSizeInBits();
651 Min = (Min << ShAmt) >> ShAmt;
652 Max = (Max << ShAmt) >> ShAmt;
653}
654
655// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
656// a set of known zero and one bits, compute the maximum and minimum values that
657// could have the specified known zero and known one bits, returning them in
658// min/max.
659static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
660 uint64_t KnownZero,
661 uint64_t KnownOne,
662 uint64_t &Min,
663 uint64_t &Max) {
664 uint64_t TypeBits = Ty->getIntegralTypeMask();
665 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
666
667 // The minimum value is when the unknown bits are all zeros.
668 Min = KnownOne;
669 // The maximum value is when the unknown bits are all ones.
670 Max = KnownOne|UnknownBits;
671}
Chris Lattner255d8912006-02-11 09:31:47 +0000672
673
674/// SimplifyDemandedBits - Look at V. At this point, we know that only the
675/// DemandedMask bits of the result of V are ever used downstream. If we can
676/// use this information to simplify V, do so and return true. Otherwise,
677/// analyze the expression and return a mask of KnownOne and KnownZero bits for
678/// the expression (used to simplify the caller). The KnownZero/One bits may
679/// only be accurate for those bits in the DemandedMask.
680bool InstCombiner::SimplifyDemandedBits(Value *V, uint64_t DemandedMask,
681 uint64_t &KnownZero, uint64_t &KnownOne,
Chris Lattner6dce1a72006-02-07 06:56:34 +0000682 unsigned Depth) {
Chris Lattner255d8912006-02-11 09:31:47 +0000683 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V)) {
684 // We know all of the bits for a constant!
685 KnownOne = CI->getZExtValue() & DemandedMask;
686 KnownZero = ~KnownOne & DemandedMask;
687 return false;
688 }
689
690 KnownZero = KnownOne = 0;
Chris Lattner6dce1a72006-02-07 06:56:34 +0000691 if (!V->hasOneUse()) { // Other users may use these bits.
Chris Lattner255d8912006-02-11 09:31:47 +0000692 if (Depth != 0) { // Not at the root.
693 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
694 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
Chris Lattner6dce1a72006-02-07 06:56:34 +0000695 return false;
Chris Lattner255d8912006-02-11 09:31:47 +0000696 }
Chris Lattner6dce1a72006-02-07 06:56:34 +0000697 // If this is the root being simplified, allow it to have multiple uses,
Chris Lattner255d8912006-02-11 09:31:47 +0000698 // just set the DemandedMask to all bits.
699 DemandedMask = V->getType()->getIntegralTypeMask();
700 } else if (DemandedMask == 0) { // Not demanding any bits from V.
Chris Lattner74c51a02006-02-07 08:05:22 +0000701 if (V != UndefValue::get(V->getType()))
702 return UpdateValueUsesWith(V, UndefValue::get(V->getType()));
703 return false;
Chris Lattner6dce1a72006-02-07 06:56:34 +0000704 } else if (Depth == 6) { // Limit search depth.
705 return false;
706 }
707
708 Instruction *I = dyn_cast<Instruction>(V);
709 if (!I) return false; // Only analyze instructions.
710
Chris Lattner255d8912006-02-11 09:31:47 +0000711 uint64_t KnownZero2, KnownOne2;
Chris Lattner6dce1a72006-02-07 06:56:34 +0000712 switch (I->getOpcode()) {
713 default: break;
714 case Instruction::And:
Chris Lattner255d8912006-02-11 09:31:47 +0000715 // If either the LHS or the RHS are Zero, the result is zero.
716 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
717 KnownZero, KnownOne, Depth+1))
718 return true;
719 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
720
721 // If something is known zero on the RHS, the bits aren't demanded on the
722 // LHS.
723 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownZero,
724 KnownZero2, KnownOne2, Depth+1))
725 return true;
726 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
727
728 // If all of the demanded bits are known one on one side, return the other.
729 // These bits cannot contribute to the result of the 'and'.
730 if ((DemandedMask & ~KnownZero2 & KnownOne) == (DemandedMask & ~KnownZero2))
731 return UpdateValueUsesWith(I, I->getOperand(0));
732 if ((DemandedMask & ~KnownZero & KnownOne2) == (DemandedMask & ~KnownZero))
733 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattnerf8c36f52006-02-12 08:02:11 +0000734
735 // If all of the demanded bits in the inputs are known zeros, return zero.
736 if ((DemandedMask & (KnownZero|KnownZero2)) == DemandedMask)
737 return UpdateValueUsesWith(I, Constant::getNullValue(I->getType()));
738
Chris Lattner255d8912006-02-11 09:31:47 +0000739 // If the RHS is a constant, see if we can simplify it.
Chris Lattnerf8c36f52006-02-12 08:02:11 +0000740 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~KnownZero2))
Chris Lattner255d8912006-02-11 09:31:47 +0000741 return UpdateValueUsesWith(I, I);
742
743 // Output known-1 bits are only known if set in both the LHS & RHS.
744 KnownOne &= KnownOne2;
745 // Output known-0 are known to be clear if zero in either the LHS | RHS.
746 KnownZero |= KnownZero2;
747 break;
748 case Instruction::Or:
749 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
750 KnownZero, KnownOne, Depth+1))
751 return true;
752 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
753 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownOne,
754 KnownZero2, KnownOne2, Depth+1))
755 return true;
756 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
757
758 // If all of the demanded bits are known zero on one side, return the other.
759 // These bits cannot contribute to the result of the 'or'.
Jeff Cohenbce48052006-02-18 03:20:33 +0000760 if ((DemandedMask & ~KnownOne2 & KnownZero) == (DemandedMask & ~KnownOne2))
Chris Lattner255d8912006-02-11 09:31:47 +0000761 return UpdateValueUsesWith(I, I->getOperand(0));
Jeff Cohenbce48052006-02-18 03:20:33 +0000762 if ((DemandedMask & ~KnownOne & KnownZero2) == (DemandedMask & ~KnownOne))
Chris Lattner255d8912006-02-11 09:31:47 +0000763 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattnerf8c36f52006-02-12 08:02:11 +0000764
765 // If all of the potentially set bits on one side are known to be set on
766 // the other side, just use the 'other' side.
767 if ((DemandedMask & (~KnownZero) & KnownOne2) ==
768 (DemandedMask & (~KnownZero)))
769 return UpdateValueUsesWith(I, I->getOperand(0));
Nate Begeman368e18d2006-02-16 21:11:51 +0000770 if ((DemandedMask & (~KnownZero2) & KnownOne) ==
771 (DemandedMask & (~KnownZero2)))
772 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner255d8912006-02-11 09:31:47 +0000773
774 // If the RHS is a constant, see if we can simplify it.
775 if (ShrinkDemandedConstant(I, 1, DemandedMask))
776 return UpdateValueUsesWith(I, I);
777
778 // Output known-0 bits are only known if clear in both the LHS & RHS.
779 KnownZero &= KnownZero2;
780 // Output known-1 are known to be set if set in either the LHS | RHS.
781 KnownOne |= KnownOne2;
782 break;
783 case Instruction::Xor: {
784 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
785 KnownZero, KnownOne, Depth+1))
786 return true;
787 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
788 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
789 KnownZero2, KnownOne2, Depth+1))
790 return true;
791 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
792
793 // If all of the demanded bits are known zero on one side, return the other.
794 // These bits cannot contribute to the result of the 'xor'.
795 if ((DemandedMask & KnownZero) == DemandedMask)
796 return UpdateValueUsesWith(I, I->getOperand(0));
797 if ((DemandedMask & KnownZero2) == DemandedMask)
798 return UpdateValueUsesWith(I, I->getOperand(1));
799
800 // Output known-0 bits are known if clear or set in both the LHS & RHS.
801 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
802 // Output known-1 are known to be set if set in only one of the LHS, RHS.
803 uint64_t KnownOneOut = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
804
805 // If all of the unknown bits are known to be zero on one side or the other
806 // (but not both) turn this into an *inclusive* or.
Chris Lattnerf8c36f52006-02-12 08:02:11 +0000807 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattner255d8912006-02-11 09:31:47 +0000808 if (uint64_t UnknownBits = DemandedMask & ~(KnownZeroOut|KnownOneOut)) {
809 if ((UnknownBits & (KnownZero|KnownZero2)) == UnknownBits) {
810 Instruction *Or =
811 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
812 I->getName());
813 InsertNewInstBefore(Or, *I);
814 return UpdateValueUsesWith(I, Or);
Chris Lattner6dce1a72006-02-07 06:56:34 +0000815 }
816 }
Chris Lattner255d8912006-02-11 09:31:47 +0000817
Chris Lattnerf8c36f52006-02-12 08:02:11 +0000818 // If all of the demanded bits on one side are known, and all of the set
819 // bits on that side are also known to be set on the other side, turn this
820 // into an AND, as we know the bits will be cleared.
821 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
822 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask) { // all known
823 if ((KnownOne & KnownOne2) == KnownOne) {
824 Constant *AndC = GetConstantInType(I->getType(),
825 ~KnownOne & DemandedMask);
826 Instruction *And =
827 BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
828 InsertNewInstBefore(And, *I);
829 return UpdateValueUsesWith(I, And);
830 }
831 }
832
Chris Lattner255d8912006-02-11 09:31:47 +0000833 // If the RHS is a constant, see if we can simplify it.
834 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
835 if (ShrinkDemandedConstant(I, 1, DemandedMask))
836 return UpdateValueUsesWith(I, I);
837
838 KnownZero = KnownZeroOut;
839 KnownOne = KnownOneOut;
840 break;
841 }
842 case Instruction::Select:
843 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
844 KnownZero, KnownOne, Depth+1))
845 return true;
846 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
847 KnownZero2, KnownOne2, Depth+1))
848 return true;
849 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
850 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
851
852 // If the operands are constants, see if we can simplify them.
853 if (ShrinkDemandedConstant(I, 1, DemandedMask))
854 return UpdateValueUsesWith(I, I);
855 if (ShrinkDemandedConstant(I, 2, DemandedMask))
856 return UpdateValueUsesWith(I, I);
857
858 // Only known if known in both the LHS and RHS.
859 KnownOne &= KnownOne2;
860 KnownZero &= KnownZero2;
861 break;
Chris Lattner6dce1a72006-02-07 06:56:34 +0000862 case Instruction::Cast: {
863 const Type *SrcTy = I->getOperand(0)->getType();
Chris Lattner255d8912006-02-11 09:31:47 +0000864 if (!SrcTy->isIntegral()) return false;
Chris Lattner6dce1a72006-02-07 06:56:34 +0000865
Chris Lattner255d8912006-02-11 09:31:47 +0000866 // If this is an integer truncate or noop, just look in the input.
867 if (SrcTy->getPrimitiveSizeInBits() >=
868 I->getType()->getPrimitiveSizeInBits()) {
869 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
870 KnownZero, KnownOne, Depth+1))
871 return true;
872 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
873 break;
874 }
875
876 // Sign or Zero extension. Compute the bits in the result that are not
877 // present in the input.
878 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
879 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
880
881 // Handle zero extension.
882 if (!SrcTy->isSigned()) {
883 DemandedMask &= SrcTy->getIntegralTypeMask();
884 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
885 KnownZero, KnownOne, Depth+1))
886 return true;
887 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
888 // The top bits are known to be zero.
889 KnownZero |= NewBits;
890 } else {
891 // Sign extension.
Chris Lattnerf345fe42006-02-13 22:41:07 +0000892 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
893 int64_t InputDemandedBits = DemandedMask & SrcTy->getIntegralTypeMask();
894
895 // If any of the sign extended bits are demanded, we know that the sign
896 // bit is demanded.
897 if (NewBits & DemandedMask)
898 InputDemandedBits |= InSignBit;
899
900 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
Chris Lattner255d8912006-02-11 09:31:47 +0000901 KnownZero, KnownOne, Depth+1))
902 return true;
903 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
904
905 // If the sign bit of the input is known set or clear, then we know the
906 // top bits of the result.
Chris Lattner6dce1a72006-02-07 06:56:34 +0000907
Chris Lattner255d8912006-02-11 09:31:47 +0000908 // If the input sign bit is known zero, or if the NewBits are not demanded
909 // convert this into a zero extension.
910 if ((KnownZero & InSignBit) || (NewBits & ~DemandedMask) == NewBits) {
Chris Lattner6dce1a72006-02-07 06:56:34 +0000911 // Convert to unsigned first.
Chris Lattnerd89d8882006-02-07 19:07:40 +0000912 Instruction *NewVal;
Chris Lattner6dce1a72006-02-07 06:56:34 +0000913 NewVal = new CastInst(I->getOperand(0), SrcTy->getUnsignedVersion(),
Chris Lattnerd89d8882006-02-07 19:07:40 +0000914 I->getOperand(0)->getName());
915 InsertNewInstBefore(NewVal, *I);
Chris Lattner255d8912006-02-11 09:31:47 +0000916 // Then cast that to the destination type.
Chris Lattnerd89d8882006-02-07 19:07:40 +0000917 NewVal = new CastInst(NewVal, I->getType(), I->getName());
918 InsertNewInstBefore(NewVal, *I);
Chris Lattner6dce1a72006-02-07 06:56:34 +0000919 return UpdateValueUsesWith(I, NewVal);
Chris Lattner255d8912006-02-11 09:31:47 +0000920 } else if (KnownOne & InSignBit) { // Input sign bit known set
921 KnownOne |= NewBits;
922 KnownZero &= ~NewBits;
923 } else { // Input sign bit unknown
924 KnownZero &= ~NewBits;
925 KnownOne &= ~NewBits;
Chris Lattner6dce1a72006-02-07 06:56:34 +0000926 }
Chris Lattner6dce1a72006-02-07 06:56:34 +0000927 }
Chris Lattner255d8912006-02-11 09:31:47 +0000928 break;
Chris Lattner6dce1a72006-02-07 06:56:34 +0000929 }
Chris Lattner6dce1a72006-02-07 06:56:34 +0000930 case Instruction::Shl:
Chris Lattner255d8912006-02-11 09:31:47 +0000931 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
932 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask >> SA->getValue(),
933 KnownZero, KnownOne, Depth+1))
934 return true;
935 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
936 KnownZero <<= SA->getValue();
937 KnownOne <<= SA->getValue();
938 KnownZero |= (1ULL << SA->getValue())-1; // low bits known zero.
939 }
Chris Lattner6dce1a72006-02-07 06:56:34 +0000940 break;
941 case Instruction::Shr:
Chris Lattner255d8912006-02-11 09:31:47 +0000942 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
943 unsigned ShAmt = SA->getValue();
944
945 // Compute the new bits that are at the top now.
946 uint64_t HighBits = (1ULL << ShAmt)-1;
947 HighBits <<= I->getType()->getPrimitiveSizeInBits() - ShAmt;
Chris Lattnerc15637b2006-02-13 06:09:08 +0000948 uint64_t TypeMask = I->getType()->getIntegralTypeMask();
Chris Lattner255d8912006-02-11 09:31:47 +0000949 if (I->getType()->isUnsigned()) { // Unsigned shift right.
Chris Lattnerc15637b2006-02-13 06:09:08 +0000950 if (SimplifyDemandedBits(I->getOperand(0),
951 (DemandedMask << ShAmt) & TypeMask,
Chris Lattner255d8912006-02-11 09:31:47 +0000952 KnownZero, KnownOne, Depth+1))
953 return true;
954 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattnerc15637b2006-02-13 06:09:08 +0000955 KnownZero &= TypeMask;
956 KnownOne &= TypeMask;
Chris Lattner255d8912006-02-11 09:31:47 +0000957 KnownZero >>= ShAmt;
958 KnownOne >>= ShAmt;
959 KnownZero |= HighBits; // high bits known zero.
960 } else { // Signed shift right.
Chris Lattnerc15637b2006-02-13 06:09:08 +0000961 if (SimplifyDemandedBits(I->getOperand(0),
962 (DemandedMask << ShAmt) & TypeMask,
Chris Lattner255d8912006-02-11 09:31:47 +0000963 KnownZero, KnownOne, Depth+1))
964 return true;
965 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattnerc15637b2006-02-13 06:09:08 +0000966 KnownZero &= TypeMask;
967 KnownOne &= TypeMask;
Chris Lattner255d8912006-02-11 09:31:47 +0000968 KnownZero >>= SA->getValue();
969 KnownOne >>= SA->getValue();
970
971 // Handle the sign bits.
972 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
973 SignBit >>= SA->getValue(); // Adjust to where it is now in the mask.
974
975 // If the input sign bit is known to be zero, or if none of the top bits
976 // are demanded, turn this into an unsigned shift right.
977 if ((KnownZero & SignBit) || (HighBits & ~DemandedMask) == HighBits) {
978 // Convert the input to unsigned.
979 Instruction *NewVal;
980 NewVal = new CastInst(I->getOperand(0),
981 I->getType()->getUnsignedVersion(),
982 I->getOperand(0)->getName());
983 InsertNewInstBefore(NewVal, *I);
984 // Perform the unsigned shift right.
985 NewVal = new ShiftInst(Instruction::Shr, NewVal, SA, I->getName());
986 InsertNewInstBefore(NewVal, *I);
987 // Then cast that to the destination type.
988 NewVal = new CastInst(NewVal, I->getType(), I->getName());
989 InsertNewInstBefore(NewVal, *I);
990 return UpdateValueUsesWith(I, NewVal);
991 } else if (KnownOne & SignBit) { // New bits are known one.
992 KnownOne |= HighBits;
993 }
Chris Lattner6dce1a72006-02-07 06:56:34 +0000994 }
Chris Lattner255d8912006-02-11 09:31:47 +0000995 }
Chris Lattner6dce1a72006-02-07 06:56:34 +0000996 break;
997 }
Chris Lattner255d8912006-02-11 09:31:47 +0000998
999 // If the client is only demanding bits that we know, return the known
1000 // constant.
1001 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask)
1002 return UpdateValueUsesWith(I, GetConstantInType(I->getType(), KnownOne));
Chris Lattner6dce1a72006-02-07 06:56:34 +00001003 return false;
1004}
1005
Chris Lattner955f3312004-09-28 21:48:02 +00001006// isTrueWhenEqual - Return true if the specified setcondinst instruction is
1007// true when both operands are equal...
1008//
1009static bool isTrueWhenEqual(Instruction &I) {
1010 return I.getOpcode() == Instruction::SetEQ ||
1011 I.getOpcode() == Instruction::SetGE ||
1012 I.getOpcode() == Instruction::SetLE;
1013}
Chris Lattner564a7272003-08-13 19:01:45 +00001014
1015/// AssociativeOpt - Perform an optimization on an associative operator. This
1016/// function is designed to check a chain of associative operators for a
1017/// potential to apply a certain optimization. Since the optimization may be
1018/// applicable if the expression was reassociated, this checks the chain, then
1019/// reassociates the expression as necessary to expose the optimization
1020/// opportunity. This makes use of a special Functor, which must define
1021/// 'shouldApply' and 'apply' methods.
1022///
1023template<typename Functor>
1024Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1025 unsigned Opcode = Root.getOpcode();
1026 Value *LHS = Root.getOperand(0);
1027
1028 // Quick check, see if the immediate LHS matches...
1029 if (F.shouldApply(LHS))
1030 return F.apply(Root);
1031
1032 // Otherwise, if the LHS is not of the same opcode as the root, return.
1033 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +00001034 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +00001035 // Should we apply this transform to the RHS?
1036 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1037
1038 // If not to the RHS, check to see if we should apply to the LHS...
1039 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1040 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1041 ShouldApply = true;
1042 }
1043
1044 // If the functor wants to apply the optimization to the RHS of LHSI,
1045 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1046 if (ShouldApply) {
1047 BasicBlock *BB = Root.getParent();
Misha Brukmanfd939082005-04-21 23:48:37 +00001048
Chris Lattner564a7272003-08-13 19:01:45 +00001049 // Now all of the instructions are in the current basic block, go ahead
1050 // and perform the reassociation.
1051 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1052
1053 // First move the selected RHS to the LHS of the root...
1054 Root.setOperand(0, LHSI->getOperand(1));
1055
1056 // Make what used to be the LHS of the root be the user of the root...
1057 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +00001058 if (&Root == TmpLHSI) {
Chris Lattner15a76c02004-04-05 02:10:19 +00001059 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1060 return 0;
1061 }
Chris Lattner65725312004-04-16 18:08:07 +00001062 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +00001063 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +00001064 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1065 BasicBlock::iterator ARI = &Root; ++ARI;
1066 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
1067 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +00001068
1069 // Now propagate the ExtraOperand down the chain of instructions until we
1070 // get to LHSI.
1071 while (TmpLHSI != LHSI) {
1072 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +00001073 // Move the instruction to immediately before the chain we are
1074 // constructing to avoid breaking dominance properties.
1075 NextLHSI->getParent()->getInstList().remove(NextLHSI);
1076 BB->getInstList().insert(ARI, NextLHSI);
1077 ARI = NextLHSI;
1078
Chris Lattner564a7272003-08-13 19:01:45 +00001079 Value *NextOp = NextLHSI->getOperand(1);
1080 NextLHSI->setOperand(1, ExtraOperand);
1081 TmpLHSI = NextLHSI;
1082 ExtraOperand = NextOp;
1083 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001084
Chris Lattner564a7272003-08-13 19:01:45 +00001085 // Now that the instructions are reassociated, have the functor perform
1086 // the transformation...
1087 return F.apply(Root);
1088 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001089
Chris Lattner564a7272003-08-13 19:01:45 +00001090 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1091 }
1092 return 0;
1093}
1094
1095
1096// AddRHS - Implements: X + X --> X << 1
1097struct AddRHS {
1098 Value *RHS;
1099 AddRHS(Value *rhs) : RHS(rhs) {}
1100 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1101 Instruction *apply(BinaryOperator &Add) const {
1102 return new ShiftInst(Instruction::Shl, Add.getOperand(0),
1103 ConstantInt::get(Type::UByteTy, 1));
1104 }
1105};
1106
1107// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1108// iff C1&C2 == 0
1109struct AddMaskingAnd {
1110 Constant *C2;
1111 AddMaskingAnd(Constant *c) : C2(c) {}
1112 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001113 ConstantInt *C1;
Misha Brukmanfd939082005-04-21 23:48:37 +00001114 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001115 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +00001116 }
1117 Instruction *apply(BinaryOperator &Add) const {
Chris Lattner48595f12004-06-10 02:07:29 +00001118 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +00001119 }
1120};
1121
Chris Lattner6e7ba452005-01-01 16:22:27 +00001122static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +00001123 InstCombiner *IC) {
Chris Lattner6e7ba452005-01-01 16:22:27 +00001124 if (isa<CastInst>(I)) {
1125 if (Constant *SOC = dyn_cast<Constant>(SO))
1126 return ConstantExpr::getCast(SOC, I.getType());
Misha Brukmanfd939082005-04-21 23:48:37 +00001127
Chris Lattner6e7ba452005-01-01 16:22:27 +00001128 return IC->InsertNewInstBefore(new CastInst(SO, I.getType(),
1129 SO->getName() + ".cast"), I);
1130 }
1131
Chris Lattner2eefe512004-04-09 19:05:30 +00001132 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +00001133 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1134 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +00001135
Chris Lattner2eefe512004-04-09 19:05:30 +00001136 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1137 if (ConstIsRHS)
Chris Lattner6e7ba452005-01-01 16:22:27 +00001138 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1139 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +00001140 }
1141
1142 Value *Op0 = SO, *Op1 = ConstOperand;
1143 if (!ConstIsRHS)
1144 std::swap(Op0, Op1);
1145 Instruction *New;
Chris Lattner6e7ba452005-01-01 16:22:27 +00001146 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1147 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1148 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
1149 New = new ShiftInst(SI->getOpcode(), Op0, Op1, SO->getName()+".sh");
Chris Lattner326c0f32004-04-10 19:15:56 +00001150 else {
Chris Lattner2eefe512004-04-09 19:05:30 +00001151 assert(0 && "Unknown binary instruction type!");
Chris Lattner326c0f32004-04-10 19:15:56 +00001152 abort();
1153 }
Chris Lattner6e7ba452005-01-01 16:22:27 +00001154 return IC->InsertNewInstBefore(New, I);
1155}
1156
1157// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1158// constant as the other operand, try to fold the binary operator into the
1159// select arguments. This also works for Cast instructions, which obviously do
1160// not have a second operand.
1161static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1162 InstCombiner *IC) {
1163 // Don't modify shared select instructions
1164 if (!SI->hasOneUse()) return 0;
1165 Value *TV = SI->getOperand(1);
1166 Value *FV = SI->getOperand(2);
1167
1168 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +00001169 // Bool selects with constant operands can be folded to logical ops.
1170 if (SI->getType() == Type::BoolTy) return 0;
1171
Chris Lattner6e7ba452005-01-01 16:22:27 +00001172 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1173 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1174
1175 return new SelectInst(SI->getCondition(), SelectTrueVal,
1176 SelectFalseVal);
1177 }
1178 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +00001179}
1180
Chris Lattner4e998b22004-09-29 05:07:12 +00001181
1182/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1183/// node as operand #0, see if we can fold the instruction into the PHI (which
1184/// is only possible if all operands to the PHI are constants).
1185Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1186 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00001187 unsigned NumPHIValues = PN->getNumIncomingValues();
1188 if (!PN->hasOneUse() || NumPHIValues == 0 ||
1189 !isa<Constant>(PN->getIncomingValue(0))) return 0;
Chris Lattner4e998b22004-09-29 05:07:12 +00001190
1191 // Check to see if all of the operands of the PHI are constants. If not, we
1192 // cannot do the transformation.
Chris Lattnerbac32862004-11-14 19:13:23 +00001193 for (unsigned i = 1; i != NumPHIValues; ++i)
Chris Lattner4e998b22004-09-29 05:07:12 +00001194 if (!isa<Constant>(PN->getIncomingValue(i)))
1195 return 0;
1196
1197 // Okay, we can do the transformation: create the new PHI node.
1198 PHINode *NewPN = new PHINode(I.getType(), I.getName());
1199 I.setName("");
Chris Lattner55517062005-01-29 00:39:08 +00001200 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner4e998b22004-09-29 05:07:12 +00001201 InsertNewInstBefore(NewPN, *PN);
1202
1203 // Next, add all of the operands to the PHI.
1204 if (I.getNumOperands() == 2) {
1205 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +00001206 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner4e998b22004-09-29 05:07:12 +00001207 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
1208 NewPN->addIncoming(ConstantExpr::get(I.getOpcode(), InV, C),
1209 PN->getIncomingBlock(i));
1210 }
1211 } else {
1212 assert(isa<CastInst>(I) && "Unary op should be a cast!");
1213 const Type *RetTy = I.getType();
Chris Lattnerbac32862004-11-14 19:13:23 +00001214 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner4e998b22004-09-29 05:07:12 +00001215 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
1216 NewPN->addIncoming(ConstantExpr::getCast(InV, RetTy),
1217 PN->getIncomingBlock(i));
1218 }
1219 }
1220 return ReplaceInstUsesWith(I, NewPN);
1221}
1222
Chris Lattner7e708292002-06-25 16:13:24 +00001223Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00001224 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00001225 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +00001226
Chris Lattner66331a42004-04-10 22:01:55 +00001227 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattnere87597f2004-10-16 18:11:37 +00001228 // X + undef -> undef
1229 if (isa<UndefValue>(RHS))
1230 return ReplaceInstUsesWith(I, RHS);
1231
Chris Lattner66331a42004-04-10 22:01:55 +00001232 // X + 0 --> X
Chris Lattner5e678e02005-10-17 17:56:38 +00001233 if (!I.getType()->isFloatingPoint()) { // NOTE: -0 + +0 = +0.
1234 if (RHSC->isNullValue())
1235 return ReplaceInstUsesWith(I, LHS);
Chris Lattner8532cf62005-10-17 20:18:38 +00001236 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1237 if (CFP->isExactlyValue(-0.0))
1238 return ReplaceInstUsesWith(I, LHS);
Chris Lattner5e678e02005-10-17 17:56:38 +00001239 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001240
Chris Lattner66331a42004-04-10 22:01:55 +00001241 // X + (signbit) --> X ^ signbit
1242 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattner74c51a02006-02-07 08:05:22 +00001243 uint64_t Val = CI->getZExtValue();
Chris Lattner1a074fc2006-02-07 07:00:41 +00001244 if (Val == (1ULL << (CI->getType()->getPrimitiveSizeInBits()-1)))
Chris Lattner48595f12004-06-10 02:07:29 +00001245 return BinaryOperator::createXor(LHS, RHS);
Chris Lattner66331a42004-04-10 22:01:55 +00001246 }
Chris Lattner4e998b22004-09-29 05:07:12 +00001247
1248 if (isa<PHINode>(LHS))
1249 if (Instruction *NV = FoldOpIntoPhi(I))
1250 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +00001251
Chris Lattner4f637d42006-01-06 17:59:59 +00001252 ConstantInt *XorRHS = 0;
1253 Value *XorLHS = 0;
Chris Lattner5931c542005-09-24 23:43:33 +00001254 if (match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
1255 unsigned TySizeBits = I.getType()->getPrimitiveSizeInBits();
1256 int64_t RHSSExt = cast<ConstantInt>(RHSC)->getSExtValue();
1257 uint64_t RHSZExt = cast<ConstantInt>(RHSC)->getZExtValue();
1258
1259 uint64_t C0080Val = 1ULL << 31;
1260 int64_t CFF80Val = -C0080Val;
1261 unsigned Size = 32;
1262 do {
1263 if (TySizeBits > Size) {
1264 bool Found = false;
1265 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1266 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
1267 if (RHSSExt == CFF80Val) {
1268 if (XorRHS->getZExtValue() == C0080Val)
1269 Found = true;
1270 } else if (RHSZExt == C0080Val) {
1271 if (XorRHS->getSExtValue() == CFF80Val)
1272 Found = true;
1273 }
1274 if (Found) {
1275 // This is a sign extend if the top bits are known zero.
Chris Lattner68d5ff22006-02-09 07:38:58 +00001276 uint64_t Mask = ~0ULL;
Chris Lattner3bedbd92006-02-07 07:27:52 +00001277 Mask <<= 64-(TySizeBits-Size);
Chris Lattner68d5ff22006-02-09 07:38:58 +00001278 Mask &= XorLHS->getType()->getIntegralTypeMask();
Chris Lattner3bedbd92006-02-07 07:27:52 +00001279 if (!MaskedValueIsZero(XorLHS, Mask))
Chris Lattner5931c542005-09-24 23:43:33 +00001280 Size = 0; // Not a sign ext, but can't be any others either.
1281 goto FoundSExt;
1282 }
1283 }
1284 Size >>= 1;
1285 C0080Val >>= Size;
1286 CFF80Val >>= Size;
1287 } while (Size >= 8);
1288
1289FoundSExt:
1290 const Type *MiddleType = 0;
1291 switch (Size) {
1292 default: break;
1293 case 32: MiddleType = Type::IntTy; break;
1294 case 16: MiddleType = Type::ShortTy; break;
1295 case 8: MiddleType = Type::SByteTy; break;
1296 }
1297 if (MiddleType) {
1298 Instruction *NewTrunc = new CastInst(XorLHS, MiddleType, "sext");
1299 InsertNewInstBefore(NewTrunc, I);
1300 return new CastInst(NewTrunc, I.getType());
1301 }
1302 }
Chris Lattner66331a42004-04-10 22:01:55 +00001303 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00001304
Chris Lattner564a7272003-08-13 19:01:45 +00001305 // X + X --> X << 1
Robert Bocchino71698282004-07-27 21:02:21 +00001306 if (I.getType()->isInteger()) {
Chris Lattner564a7272003-08-13 19:01:45 +00001307 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +00001308
1309 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
1310 if (RHSI->getOpcode() == Instruction::Sub)
1311 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
1312 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
1313 }
1314 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
1315 if (LHSI->getOpcode() == Instruction::Sub)
1316 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
1317 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
1318 }
Robert Bocchino71698282004-07-27 21:02:21 +00001319 }
Chris Lattnere92d2f42003-08-13 04:18:28 +00001320
Chris Lattner5c4afb92002-05-08 22:46:53 +00001321 // -A + B --> B - A
Chris Lattner8d969642003-03-10 23:06:50 +00001322 if (Value *V = dyn_castNegVal(LHS))
Chris Lattner48595f12004-06-10 02:07:29 +00001323 return BinaryOperator::createSub(RHS, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00001324
1325 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +00001326 if (!isa<Constant>(RHS))
1327 if (Value *V = dyn_castNegVal(RHS))
Chris Lattner48595f12004-06-10 02:07:29 +00001328 return BinaryOperator::createSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001329
Misha Brukmanfd939082005-04-21 23:48:37 +00001330
Chris Lattner50af16a2004-11-13 19:50:12 +00001331 ConstantInt *C2;
1332 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
1333 if (X == RHS) // X*C + X --> X * (C+1)
1334 return BinaryOperator::createMul(RHS, AddOne(C2));
1335
1336 // X*C1 + X*C2 --> X * (C1+C2)
1337 ConstantInt *C1;
1338 if (X == dyn_castFoldableMul(RHS, C1))
1339 return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +00001340 }
1341
1342 // X + X*C --> X * (C+1)
Chris Lattner50af16a2004-11-13 19:50:12 +00001343 if (dyn_castFoldableMul(RHS, C2) == LHS)
1344 return BinaryOperator::createMul(LHS, AddOne(C2));
1345
Chris Lattnerad3448c2003-02-18 19:57:07 +00001346
Chris Lattner564a7272003-08-13 19:01:45 +00001347 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001348 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattner564a7272003-08-13 19:01:45 +00001349 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
Chris Lattnerc8802d22003-03-11 00:12:48 +00001350
Chris Lattner6b032052003-10-02 15:11:26 +00001351 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00001352 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001353 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
1354 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
1355 return BinaryOperator::createSub(C, X);
Chris Lattner6b032052003-10-02 15:11:26 +00001356 }
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001357
Chris Lattnerb99d6b12004-10-08 05:07:56 +00001358 // (X & FF00) + xx00 -> (X+xx00) & FF00
1359 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
1360 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
1361 if (Anded == CRHS) {
1362 // See if all bits from the first bit set in the Add RHS up are included
1363 // in the mask. First, get the rightmost bit.
1364 uint64_t AddRHSV = CRHS->getRawValue();
1365
1366 // Form a mask of all bits from the lowest bit added through the top.
1367 uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
Chris Lattner1a074fc2006-02-07 07:00:41 +00001368 AddRHSHighBits &= C2->getType()->getIntegralTypeMask();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00001369
1370 // See if the and mask includes all of these bits.
1371 uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getRawValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00001372
Chris Lattnerb99d6b12004-10-08 05:07:56 +00001373 if (AddRHSHighBits == AddRHSHighBitsAnd) {
1374 // Okay, the xform is safe. Insert the new add pronto.
1375 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
1376 LHS->getName()), I);
1377 return BinaryOperator::createAnd(NewAdd, C2);
1378 }
1379 }
1380 }
1381
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001382 // Try to fold constant add into select arguments.
1383 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +00001384 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001385 return R;
Chris Lattner6b032052003-10-02 15:11:26 +00001386 }
1387
Chris Lattner7e708292002-06-25 16:13:24 +00001388 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001389}
1390
Chris Lattner1ba5bcd2003-07-22 21:46:59 +00001391// isSignBit - Return true if the value represented by the constant only has the
1392// highest order bit set.
1393static bool isSignBit(ConstantInt *CI) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00001394 unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
Chris Lattnerf52d6812005-04-24 17:46:05 +00001395 return (CI->getRawValue() & (~0ULL >> (64-NumBits))) == (1ULL << (NumBits-1));
Chris Lattner1ba5bcd2003-07-22 21:46:59 +00001396}
1397
Chris Lattnerbfe492b2004-03-13 00:11:49 +00001398/// RemoveNoopCast - Strip off nonconverting casts from the value.
1399///
1400static Value *RemoveNoopCast(Value *V) {
1401 if (CastInst *CI = dyn_cast<CastInst>(V)) {
1402 const Type *CTy = CI->getType();
1403 const Type *OpTy = CI->getOperand(0)->getType();
1404 if (CTy->isInteger() && OpTy->isInteger()) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00001405 if (CTy->getPrimitiveSizeInBits() == OpTy->getPrimitiveSizeInBits())
Chris Lattnerbfe492b2004-03-13 00:11:49 +00001406 return RemoveNoopCast(CI->getOperand(0));
1407 } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
1408 return RemoveNoopCast(CI->getOperand(0));
1409 }
1410 return V;
1411}
1412
Chris Lattner7e708292002-06-25 16:13:24 +00001413Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00001414 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00001415
Chris Lattner233f7dc2002-08-12 21:17:25 +00001416 if (Op0 == Op1) // sub X, X -> 0
1417 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001418
Chris Lattner233f7dc2002-08-12 21:17:25 +00001419 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattner8d969642003-03-10 23:06:50 +00001420 if (Value *V = dyn_castNegVal(Op1))
Chris Lattner48595f12004-06-10 02:07:29 +00001421 return BinaryOperator::createAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00001422
Chris Lattnere87597f2004-10-16 18:11:37 +00001423 if (isa<UndefValue>(Op0))
1424 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
1425 if (isa<UndefValue>(Op1))
1426 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
1427
Chris Lattnerd65460f2003-11-05 01:06:05 +00001428 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
1429 // Replace (-1 - A) with (~A)...
Chris Lattnera2881962003-02-18 19:28:33 +00001430 if (C->isAllOnesValue())
1431 return BinaryOperator::createNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +00001432
Chris Lattnerd65460f2003-11-05 01:06:05 +00001433 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00001434 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001435 if (match(Op1, m_Not(m_Value(X))))
1436 return BinaryOperator::createAdd(X,
Chris Lattner48595f12004-06-10 02:07:29 +00001437 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
Chris Lattner9c290672004-03-12 23:53:13 +00001438 // -((uint)X >> 31) -> ((int)X >> 31)
1439 // -((int)X >> 31) -> ((uint)X >> 31)
Chris Lattnerbfe492b2004-03-13 00:11:49 +00001440 if (C->isNullValue()) {
1441 Value *NoopCastedRHS = RemoveNoopCast(Op1);
1442 if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
Chris Lattner9c290672004-03-12 23:53:13 +00001443 if (SI->getOpcode() == Instruction::Shr)
1444 if (ConstantUInt *CU = dyn_cast<ConstantUInt>(SI->getOperand(1))) {
1445 const Type *NewTy;
Chris Lattnerbfe492b2004-03-13 00:11:49 +00001446 if (SI->getType()->isSigned())
Chris Lattner5dd04022004-06-17 18:16:02 +00001447 NewTy = SI->getType()->getUnsignedVersion();
Chris Lattner9c290672004-03-12 23:53:13 +00001448 else
Chris Lattner5dd04022004-06-17 18:16:02 +00001449 NewTy = SI->getType()->getSignedVersion();
Chris Lattner9c290672004-03-12 23:53:13 +00001450 // Check to see if we are shifting out everything but the sign bit.
Chris Lattner484d3cf2005-04-24 06:59:08 +00001451 if (CU->getValue() == SI->getType()->getPrimitiveSizeInBits()-1) {
Chris Lattner9c290672004-03-12 23:53:13 +00001452 // Ok, the transformation is safe. Insert a cast of the incoming
1453 // value, then the new shift, then the new cast.
1454 Instruction *FirstCast = new CastInst(SI->getOperand(0), NewTy,
1455 SI->getOperand(0)->getName());
1456 Value *InV = InsertNewInstBefore(FirstCast, I);
1457 Instruction *NewShift = new ShiftInst(Instruction::Shr, FirstCast,
1458 CU, SI->getName());
Chris Lattnerbfe492b2004-03-13 00:11:49 +00001459 if (NewShift->getType() == I.getType())
1460 return NewShift;
1461 else {
1462 InV = InsertNewInstBefore(NewShift, I);
1463 return new CastInst(NewShift, I.getType());
1464 }
Chris Lattner9c290672004-03-12 23:53:13 +00001465 }
1466 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00001467 }
Chris Lattner2eefe512004-04-09 19:05:30 +00001468
1469 // Try to fold constant sub into select arguments.
1470 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00001471 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00001472 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00001473
1474 if (isa<PHINode>(Op0))
1475 if (Instruction *NV = FoldOpIntoPhi(I))
1476 return NV;
Chris Lattnerd65460f2003-11-05 01:06:05 +00001477 }
1478
Chris Lattner43d84d62005-04-07 16:15:25 +00001479 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
1480 if (Op1I->getOpcode() == Instruction::Add &&
1481 !Op0->getType()->isFloatingPoint()) {
Chris Lattner08954a22005-04-07 16:28:01 +00001482 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Chris Lattner43d84d62005-04-07 16:15:25 +00001483 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00001484 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Chris Lattner43d84d62005-04-07 16:15:25 +00001485 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00001486 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
1487 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
1488 // C1-(X+C2) --> (C1-C2)-X
1489 return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
1490 Op1I->getOperand(0));
1491 }
Chris Lattner43d84d62005-04-07 16:15:25 +00001492 }
1493
Chris Lattnerfd059242003-10-15 16:48:29 +00001494 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00001495 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
1496 // is not used by anyone else...
1497 //
Chris Lattner0517e722004-02-02 20:09:56 +00001498 if (Op1I->getOpcode() == Instruction::Sub &&
1499 !Op1I->getType()->isFloatingPoint()) {
Chris Lattnera2881962003-02-18 19:28:33 +00001500 // Swap the two operands of the subexpr...
1501 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
1502 Op1I->setOperand(0, IIOp1);
1503 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00001504
Chris Lattnera2881962003-02-18 19:28:33 +00001505 // Create the new top level add instruction...
Chris Lattner48595f12004-06-10 02:07:29 +00001506 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00001507 }
1508
1509 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
1510 //
1511 if (Op1I->getOpcode() == Instruction::And &&
1512 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
1513 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
1514
Chris Lattnerf523d062004-06-09 05:08:07 +00001515 Value *NewNot =
1516 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattner48595f12004-06-10 02:07:29 +00001517 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00001518 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00001519
Chris Lattner91ccc152004-10-06 15:08:25 +00001520 // -(X sdiv C) -> (X sdiv -C)
1521 if (Op1I->getOpcode() == Instruction::Div)
1522 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
Chris Lattner43d84d62005-04-07 16:15:25 +00001523 if (CSI->isNullValue())
Chris Lattner91ccc152004-10-06 15:08:25 +00001524 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Misha Brukmanfd939082005-04-21 23:48:37 +00001525 return BinaryOperator::createDiv(Op1I->getOperand(0),
Chris Lattner91ccc152004-10-06 15:08:25 +00001526 ConstantExpr::getNeg(DivRHS));
1527
Chris Lattnerad3448c2003-02-18 19:57:07 +00001528 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00001529 ConstantInt *C2 = 0;
Chris Lattner50af16a2004-11-13 19:50:12 +00001530 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Misha Brukmanfd939082005-04-21 23:48:37 +00001531 Constant *CP1 =
Chris Lattner50af16a2004-11-13 19:50:12 +00001532 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
Chris Lattner48595f12004-06-10 02:07:29 +00001533 return BinaryOperator::createMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00001534 }
Chris Lattner40371712002-05-09 01:29:19 +00001535 }
Chris Lattner43d84d62005-04-07 16:15:25 +00001536 }
Chris Lattnera2881962003-02-18 19:28:33 +00001537
Chris Lattner7edc8c22005-04-07 17:14:51 +00001538 if (!Op0->getType()->isFloatingPoint())
1539 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
1540 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00001541 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
1542 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
1543 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
1544 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner7edc8c22005-04-07 17:14:51 +00001545 } else if (Op0I->getOpcode() == Instruction::Sub) {
1546 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
1547 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00001548 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001549
Chris Lattner50af16a2004-11-13 19:50:12 +00001550 ConstantInt *C1;
1551 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
1552 if (X == Op1) { // X*C - X --> X * (C-1)
1553 Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
1554 return BinaryOperator::createMul(Op1, CP1);
1555 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00001556
Chris Lattner50af16a2004-11-13 19:50:12 +00001557 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
1558 if (X == dyn_castFoldableMul(Op1, C2))
1559 return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
1560 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00001561 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001562}
1563
Chris Lattner4cb170c2004-02-23 06:38:22 +00001564/// isSignBitCheck - Given an exploded setcc instruction, return true if it is
1565/// really just returns true if the most significant (sign) bit is set.
1566static bool isSignBitCheck(unsigned Opcode, Value *LHS, ConstantInt *RHS) {
1567 if (RHS->getType()->isSigned()) {
1568 // True if source is LHS < 0 or LHS <= -1
1569 return Opcode == Instruction::SetLT && RHS->isNullValue() ||
1570 Opcode == Instruction::SetLE && RHS->isAllOnesValue();
1571 } else {
1572 ConstantUInt *RHSC = cast<ConstantUInt>(RHS);
1573 // True if source is LHS > 127 or LHS >= 128, where the constants depend on
1574 // the size of the integer type.
1575 if (Opcode == Instruction::SetGE)
Chris Lattner484d3cf2005-04-24 06:59:08 +00001576 return RHSC->getValue() ==
1577 1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1);
Chris Lattner4cb170c2004-02-23 06:38:22 +00001578 if (Opcode == Instruction::SetGT)
1579 return RHSC->getValue() ==
Chris Lattner484d3cf2005-04-24 06:59:08 +00001580 (1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1))-1;
Chris Lattner4cb170c2004-02-23 06:38:22 +00001581 }
1582 return false;
1583}
1584
Chris Lattner7e708292002-06-25 16:13:24 +00001585Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00001586 bool Changed = SimplifyCommutative(I);
Chris Lattnera2881962003-02-18 19:28:33 +00001587 Value *Op0 = I.getOperand(0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001588
Chris Lattnere87597f2004-10-16 18:11:37 +00001589 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
1590 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1591
Chris Lattner233f7dc2002-08-12 21:17:25 +00001592 // Simplify mul instructions with a constant RHS...
Chris Lattnera2881962003-02-18 19:28:33 +00001593 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
1594 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00001595
1596 // ((X << C1)*C2) == (X * (C2 << C1))
1597 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
1598 if (SI->getOpcode() == Instruction::Shl)
1599 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattner48595f12004-06-10 02:07:29 +00001600 return BinaryOperator::createMul(SI->getOperand(0),
1601 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00001602
Chris Lattner515c97c2003-09-11 22:24:54 +00001603 if (CI->isNullValue())
1604 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
1605 if (CI->equalsInt(1)) // X * 1 == X
1606 return ReplaceInstUsesWith(I, Op0);
1607 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner0af1fab2003-06-25 17:09:20 +00001608 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00001609
Chris Lattner515c97c2003-09-11 22:24:54 +00001610 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getRawValue();
Chris Lattnerbcd7db52005-08-02 19:16:58 +00001611 if (isPowerOf2_64(Val)) { // Replace X*(2^C) with X << C
1612 uint64_t C = Log2_64(Val);
Chris Lattnera2881962003-02-18 19:28:33 +00001613 return new ShiftInst(Instruction::Shl, Op0,
1614 ConstantUInt::get(Type::UByteTy, C));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00001615 }
Robert Bocchino71698282004-07-27 21:02:21 +00001616 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattnera2881962003-02-18 19:28:33 +00001617 if (Op1F->isNullValue())
1618 return ReplaceInstUsesWith(I, Op1);
Chris Lattner6c1ce212002-04-29 22:24:47 +00001619
Chris Lattnera2881962003-02-18 19:28:33 +00001620 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
1621 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
1622 if (Op1F->getValue() == 1.0)
1623 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
1624 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00001625
1626 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
1627 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
1628 isa<ConstantInt>(Op0I->getOperand(1))) {
1629 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
1630 Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
1631 Op1, "tmp");
1632 InsertNewInstBefore(Add, I);
1633 Value *C1C2 = ConstantExpr::getMul(Op1,
1634 cast<Constant>(Op0I->getOperand(1)));
1635 return BinaryOperator::createAdd(Add, C1C2);
1636
1637 }
Chris Lattner2eefe512004-04-09 19:05:30 +00001638
1639 // Try to fold constant mul into select arguments.
1640 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00001641 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00001642 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00001643
1644 if (isa<PHINode>(Op0))
1645 if (Instruction *NV = FoldOpIntoPhi(I))
1646 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001647 }
1648
Chris Lattnera4f445b2003-03-10 23:23:04 +00001649 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
1650 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattner48595f12004-06-10 02:07:29 +00001651 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00001652
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00001653 // If one of the operands of the multiply is a cast from a boolean value, then
1654 // we know the bool is either zero or one, so this is a 'masking' multiply.
1655 // See if we can simplify things based on how the boolean was originally
1656 // formed.
1657 CastInst *BoolCast = 0;
1658 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(0)))
1659 if (CI->getOperand(0)->getType() == Type::BoolTy)
1660 BoolCast = CI;
1661 if (!BoolCast)
1662 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(1)))
1663 if (CI->getOperand(0)->getType() == Type::BoolTy)
1664 BoolCast = CI;
1665 if (BoolCast) {
1666 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BoolCast->getOperand(0))) {
1667 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
1668 const Type *SCOpTy = SCIOp0->getType();
1669
Chris Lattner4cb170c2004-02-23 06:38:22 +00001670 // If the setcc is true iff the sign bit of X is set, then convert this
1671 // multiply into a shift/and combination.
1672 if (isa<ConstantInt>(SCIOp1) &&
1673 isSignBitCheck(SCI->getOpcode(), SCIOp0, cast<ConstantInt>(SCIOp1))) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00001674 // Shift the X value right to turn it into "all signbits".
1675 Constant *Amt = ConstantUInt::get(Type::UByteTy,
Chris Lattner484d3cf2005-04-24 06:59:08 +00001676 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattner4cb170c2004-02-23 06:38:22 +00001677 if (SCIOp0->getType()->isUnsigned()) {
Chris Lattner5dd04022004-06-17 18:16:02 +00001678 const Type *NewTy = SCIOp0->getType()->getSignedVersion();
Chris Lattner4cb170c2004-02-23 06:38:22 +00001679 SCIOp0 = InsertNewInstBefore(new CastInst(SCIOp0, NewTy,
1680 SCIOp0->getName()), I);
1681 }
1682
1683 Value *V =
1684 InsertNewInstBefore(new ShiftInst(Instruction::Shr, SCIOp0, Amt,
1685 BoolCast->getOperand(0)->getName()+
1686 ".mask"), I);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00001687
1688 // If the multiply type is not the same as the source type, sign extend
1689 // or truncate to the multiply type.
1690 if (I.getType() != V->getType())
Chris Lattner4cb170c2004-02-23 06:38:22 +00001691 V = InsertNewInstBefore(new CastInst(V, I.getType(), V->getName()),I);
Misha Brukmanfd939082005-04-21 23:48:37 +00001692
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00001693 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattner48595f12004-06-10 02:07:29 +00001694 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00001695 }
1696 }
1697 }
1698
Chris Lattner7e708292002-06-25 16:13:24 +00001699 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001700}
1701
Chris Lattner7e708292002-06-25 16:13:24 +00001702Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00001703 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00001704
Chris Lattner857e8cd2004-12-12 21:48:58 +00001705 if (isa<UndefValue>(Op0)) // undef / X -> 0
1706 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1707 if (isa<UndefValue>(Op1))
1708 return ReplaceInstUsesWith(I, Op1); // X / undef -> undef
1709
1710 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner83a2e6e2004-04-26 14:01:59 +00001711 // div X, 1 == X
Chris Lattner233f7dc2002-08-12 21:17:25 +00001712 if (RHS->equalsInt(1))
Chris Lattner857e8cd2004-12-12 21:48:58 +00001713 return ReplaceInstUsesWith(I, Op0);
Chris Lattnera2881962003-02-18 19:28:33 +00001714
Chris Lattner83a2e6e2004-04-26 14:01:59 +00001715 // div X, -1 == -X
1716 if (RHS->isAllOnesValue())
Chris Lattner857e8cd2004-12-12 21:48:58 +00001717 return BinaryOperator::createNeg(Op0);
Chris Lattner83a2e6e2004-04-26 14:01:59 +00001718
Chris Lattner857e8cd2004-12-12 21:48:58 +00001719 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
Chris Lattner18d19ca2004-09-28 18:22:15 +00001720 if (LHS->getOpcode() == Instruction::Div)
1721 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Chris Lattner18d19ca2004-09-28 18:22:15 +00001722 // (X / C1) / C2 -> X / (C1*C2)
1723 return BinaryOperator::createDiv(LHS->getOperand(0),
1724 ConstantExpr::getMul(RHS, LHSRHS));
1725 }
1726
Chris Lattnera2881962003-02-18 19:28:33 +00001727 // Check to see if this is an unsigned division with an exact power of 2,
1728 // if so, convert to a right shift.
1729 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
1730 if (uint64_t Val = C->getValue()) // Don't break X / 0
Chris Lattnerbcd7db52005-08-02 19:16:58 +00001731 if (isPowerOf2_64(Val)) {
1732 uint64_t C = Log2_64(Val);
Chris Lattner857e8cd2004-12-12 21:48:58 +00001733 return new ShiftInst(Instruction::Shr, Op0,
Chris Lattnera2881962003-02-18 19:28:33 +00001734 ConstantUInt::get(Type::UByteTy, C));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00001735 }
Chris Lattner4e998b22004-09-29 05:07:12 +00001736
Chris Lattnera052f822004-10-09 02:50:40 +00001737 // -X/C -> X/-C
1738 if (RHS->getType()->isSigned())
Chris Lattner857e8cd2004-12-12 21:48:58 +00001739 if (Value *LHSNeg = dyn_castNegVal(Op0))
Chris Lattnera052f822004-10-09 02:50:40 +00001740 return BinaryOperator::createDiv(LHSNeg, ConstantExpr::getNeg(RHS));
1741
Chris Lattner857e8cd2004-12-12 21:48:58 +00001742 if (!RHS->isNullValue()) {
1743 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00001744 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner857e8cd2004-12-12 21:48:58 +00001745 return R;
1746 if (isa<PHINode>(Op0))
1747 if (Instruction *NV = FoldOpIntoPhi(I))
1748 return NV;
1749 }
Chris Lattnera2881962003-02-18 19:28:33 +00001750 }
1751
Chris Lattner857e8cd2004-12-12 21:48:58 +00001752 // If this is 'udiv X, (Cond ? C1, C2)' where C1&C2 are powers of two,
1753 // transform this into: '(Cond ? (udiv X, C1) : (udiv X, C2))'.
1754 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1755 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
1756 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
1757 if (STO->getValue() == 0) { // Couldn't be this argument.
1758 I.setOperand(1, SFO);
Misha Brukmanfd939082005-04-21 23:48:37 +00001759 return &I;
Chris Lattner857e8cd2004-12-12 21:48:58 +00001760 } else if (SFO->getValue() == 0) {
Chris Lattnerf9c775c2005-06-16 04:55:52 +00001761 I.setOperand(1, STO);
Misha Brukmanfd939082005-04-21 23:48:37 +00001762 return &I;
Chris Lattner857e8cd2004-12-12 21:48:58 +00001763 }
1764
Chris Lattnerbf70b832005-04-08 04:03:26 +00001765 uint64_t TVA = STO->getValue(), FVA = SFO->getValue();
Chris Lattnerbcd7db52005-08-02 19:16:58 +00001766 if (isPowerOf2_64(TVA) && isPowerOf2_64(FVA)) {
1767 unsigned TSA = Log2_64(TVA), FSA = Log2_64(FVA);
Chris Lattnerbf70b832005-04-08 04:03:26 +00001768 Constant *TC = ConstantUInt::get(Type::UByteTy, TSA);
1769 Instruction *TSI = new ShiftInst(Instruction::Shr, Op0,
1770 TC, SI->getName()+".t");
1771 TSI = InsertNewInstBefore(TSI, I);
Misha Brukmanfd939082005-04-21 23:48:37 +00001772
Chris Lattnerbf70b832005-04-08 04:03:26 +00001773 Constant *FC = ConstantUInt::get(Type::UByteTy, FSA);
1774 Instruction *FSI = new ShiftInst(Instruction::Shr, Op0,
1775 FC, SI->getName()+".f");
1776 FSI = InsertNewInstBefore(FSI, I);
1777 return new SelectInst(SI->getOperand(0), TSI, FSI);
1778 }
Chris Lattner857e8cd2004-12-12 21:48:58 +00001779 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001780
Chris Lattnera2881962003-02-18 19:28:33 +00001781 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00001782 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00001783 if (LHS->equalsInt(0))
1784 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1785
Chris Lattnerc812e5d2005-11-05 07:40:31 +00001786 if (I.getType()->isSigned()) {
Chris Lattner3bedbd92006-02-07 07:27:52 +00001787 // If the sign bits of both operands are zero (i.e. we can prove they are
Chris Lattnerc812e5d2005-11-05 07:40:31 +00001788 // unsigned inputs), turn this into a udiv.
Chris Lattner3bedbd92006-02-07 07:27:52 +00001789 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
1790 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Chris Lattnerc812e5d2005-11-05 07:40:31 +00001791 const Type *NTy = Op0->getType()->getUnsignedVersion();
1792 Instruction *LHS = new CastInst(Op0, NTy, Op0->getName());
1793 InsertNewInstBefore(LHS, I);
1794 Value *RHS;
1795 if (Constant *R = dyn_cast<Constant>(Op1))
1796 RHS = ConstantExpr::getCast(R, NTy);
1797 else
1798 RHS = InsertNewInstBefore(new CastInst(Op1, NTy, Op1->getName()), I);
1799 Instruction *Div = BinaryOperator::createDiv(LHS, RHS, I.getName());
1800 InsertNewInstBefore(Div, I);
1801 return new CastInst(Div, I.getType());
1802 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00001803 } else {
1804 // Known to be an unsigned division.
1805 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
1806 // Turn A / (C1 << N), where C1 is "1<<C2" into A >> (N+C2) [udiv only].
1807 if (RHSI->getOpcode() == Instruction::Shl &&
1808 isa<ConstantUInt>(RHSI->getOperand(0))) {
1809 unsigned C1 = cast<ConstantUInt>(RHSI->getOperand(0))->getRawValue();
1810 if (isPowerOf2_64(C1)) {
1811 unsigned C2 = Log2_64(C1);
1812 Value *Add = RHSI->getOperand(1);
1813 if (C2) {
1814 Constant *C2V = ConstantUInt::get(Add->getType(), C2);
1815 Add = InsertNewInstBefore(BinaryOperator::createAdd(Add, C2V,
1816 "tmp"), I);
1817 }
1818 return new ShiftInst(Instruction::Shr, Op0, Add);
1819 }
1820 }
1821 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00001822 }
1823
Chris Lattner3f5b8772002-05-06 16:14:14 +00001824 return 0;
1825}
1826
1827
Chris Lattnerdb3f8732006-03-02 06:50:58 +00001828/// GetFactor - If we can prove that the specified value is at least a multiple
1829/// of some factor, return that factor.
1830static Constant *GetFactor(Value *V) {
1831 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
1832 return CI;
1833
1834 // Unless we can be tricky, we know this is a multiple of 1.
1835 Constant *Result = ConstantInt::get(V->getType(), 1);
1836
1837 Instruction *I = dyn_cast<Instruction>(V);
1838 if (!I) return Result;
1839
1840 if (I->getOpcode() == Instruction::Mul) {
1841 // Handle multiplies by a constant, etc.
1842 return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
1843 GetFactor(I->getOperand(1)));
1844 } else if (I->getOpcode() == Instruction::Shl) {
1845 // (X<<C) -> X * (1 << C)
1846 if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
1847 ShRHS = ConstantExpr::getShl(Result, ShRHS);
1848 return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
1849 }
1850 } else if (I->getOpcode() == Instruction::And) {
1851 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1852 // X & 0xFFF0 is known to be a multiple of 16.
1853 unsigned Zeros = CountTrailingZeros_64(RHS->getZExtValue());
1854 if (Zeros != V->getType()->getPrimitiveSizeInBits())
1855 return ConstantExpr::getShl(Result,
1856 ConstantUInt::get(Type::UByteTy, Zeros));
1857 }
1858 } else if (I->getOpcode() == Instruction::Cast) {
1859 Value *Op = I->getOperand(0);
1860 // Only handle int->int casts.
1861 if (!Op->getType()->isInteger()) return Result;
1862 return ConstantExpr::getCast(GetFactor(Op), V->getType());
1863 }
1864 return Result;
1865}
1866
Chris Lattner7e708292002-06-25 16:13:24 +00001867Instruction *InstCombiner::visitRem(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00001868 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner19ccd5c2006-02-28 05:30:45 +00001869
1870 // 0 % X == 0, we don't need to preserve faults!
1871 if (Constant *LHS = dyn_cast<Constant>(Op0))
1872 if (LHS->isNullValue())
1873 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1874
1875 if (isa<UndefValue>(Op0)) // undef % X -> 0
1876 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1877 if (isa<UndefValue>(Op1))
1878 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
1879
Chris Lattner11a49f22005-11-05 07:28:37 +00001880 if (I.getType()->isSigned()) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00001881 if (Value *RHSNeg = dyn_castNegVal(Op1))
Chris Lattner1e3564e2004-07-06 07:11:42 +00001882 if (!isa<ConstantSInt>(RHSNeg) ||
Chris Lattnerb49f3062004-08-09 21:05:48 +00001883 cast<ConstantSInt>(RHSNeg)->getValue() > 0) {
Chris Lattner5b73c082004-07-06 07:01:22 +00001884 // X % -Y -> X % Y
1885 AddUsesToWorkList(I);
1886 I.setOperand(1, RHSNeg);
1887 return &I;
1888 }
Chris Lattner11a49f22005-11-05 07:28:37 +00001889
1890 // If the top bits of both operands are zero (i.e. we can prove they are
1891 // unsigned inputs), turn this into a urem.
Chris Lattner3bedbd92006-02-07 07:27:52 +00001892 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
1893 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Chris Lattner11a49f22005-11-05 07:28:37 +00001894 const Type *NTy = Op0->getType()->getUnsignedVersion();
1895 Instruction *LHS = new CastInst(Op0, NTy, Op0->getName());
1896 InsertNewInstBefore(LHS, I);
1897 Value *RHS;
1898 if (Constant *R = dyn_cast<Constant>(Op1))
1899 RHS = ConstantExpr::getCast(R, NTy);
1900 else
1901 RHS = InsertNewInstBefore(new CastInst(Op1, NTy, Op1->getName()), I);
1902 Instruction *Rem = BinaryOperator::createRem(LHS, RHS, I.getName());
1903 InsertNewInstBefore(Rem, I);
1904 return new CastInst(Rem, I.getType());
1905 }
1906 }
Chris Lattner5b73c082004-07-06 07:01:22 +00001907
Chris Lattner857e8cd2004-12-12 21:48:58 +00001908 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00001909 // X % 0 == undef, we don't need to preserve faults!
1910 if (RHS->equalsInt(0))
1911 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
1912
Chris Lattnera2881962003-02-18 19:28:33 +00001913 if (RHS->equalsInt(1)) // X % 1 == 0
1914 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1915
1916 // Check to see if this is an unsigned remainder with an exact power of 2,
1917 // if so, convert to a bitwise and.
1918 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
Chris Lattner19ccd5c2006-02-28 05:30:45 +00001919 if (isPowerOf2_64(C->getValue()))
1920 return BinaryOperator::createAnd(Op0, SubOne(C));
Chris Lattner857e8cd2004-12-12 21:48:58 +00001921
Chris Lattner97943922006-02-28 05:49:21 +00001922 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
1923 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
1924 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
1925 return R;
1926 } else if (isa<PHINode>(Op0I)) {
1927 if (Instruction *NV = FoldOpIntoPhi(I))
1928 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00001929 }
Chris Lattnerdb3f8732006-03-02 06:50:58 +00001930
1931 // X*C1%C2 --> 0 iff C1%C2 == 0
1932 if (ConstantExpr::getRem(GetFactor(Op0I), RHS)->isNullValue())
1933 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner97943922006-02-28 05:49:21 +00001934 }
Chris Lattnera2881962003-02-18 19:28:33 +00001935 }
1936
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00001937 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
1938 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1) [urem only].
1939 if (I.getType()->isUnsigned() &&
1940 RHSI->getOpcode() == Instruction::Shl &&
1941 isa<ConstantUInt>(RHSI->getOperand(0))) {
1942 unsigned C1 = cast<ConstantUInt>(RHSI->getOperand(0))->getRawValue();
1943 if (isPowerOf2_64(C1)) {
1944 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
1945 Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
1946 "tmp"), I);
1947 return BinaryOperator::createAnd(Op0, Add);
1948 }
1949 }
Chris Lattner19ccd5c2006-02-28 05:30:45 +00001950
1951 // If this is 'urem X, (Cond ? C1, C2)' where C1&C2 are powers of two,
1952 // transform this into: '(Cond ? (urem X, C1) : (urem X, C2))'.
1953 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1954 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
1955 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
1956 if (STO->getValue() == 0) { // Couldn't be this argument.
1957 I.setOperand(1, SFO);
1958 return &I;
1959 } else if (SFO->getValue() == 0) {
1960 I.setOperand(1, STO);
1961 return &I;
1962 }
1963
1964 if (isPowerOf2_64(STO->getValue()) && isPowerOf2_64(SFO->getValue())){
1965 Value *TrueAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
1966 SubOne(STO), SI->getName()+".t"), I);
1967 Value *FalseAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
1968 SubOne(SFO), SI->getName()+".f"), I);
1969 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
1970 }
1971 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00001972 }
1973
Chris Lattner3f5b8772002-05-06 16:14:14 +00001974 return 0;
1975}
1976
Chris Lattner8b170942002-08-09 23:47:40 +00001977// isMaxValueMinusOne - return true if this is Max-1
Chris Lattner233f7dc2002-08-12 21:17:25 +00001978static bool isMaxValueMinusOne(const ConstantInt *C) {
Chris Lattner1a074fc2006-02-07 07:00:41 +00001979 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
1980 return CU->getValue() == C->getType()->getIntegralTypeMask()-1;
Chris Lattner8b170942002-08-09 23:47:40 +00001981
1982 const ConstantSInt *CS = cast<ConstantSInt>(C);
Misha Brukmanfd939082005-04-21 23:48:37 +00001983
Chris Lattner8b170942002-08-09 23:47:40 +00001984 // Calculate 0111111111..11111
Chris Lattner484d3cf2005-04-24 06:59:08 +00001985 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner8b170942002-08-09 23:47:40 +00001986 int64_t Val = INT64_MAX; // All ones
1987 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
1988 return CS->getValue() == Val-1;
1989}
1990
1991// isMinValuePlusOne - return true if this is Min+1
Chris Lattner233f7dc2002-08-12 21:17:25 +00001992static bool isMinValuePlusOne(const ConstantInt *C) {
Chris Lattner8b170942002-08-09 23:47:40 +00001993 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
1994 return CU->getValue() == 1;
1995
1996 const ConstantSInt *CS = cast<ConstantSInt>(C);
Misha Brukmanfd939082005-04-21 23:48:37 +00001997
1998 // Calculate 1111111111000000000000
Chris Lattner484d3cf2005-04-24 06:59:08 +00001999 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner8b170942002-08-09 23:47:40 +00002000 int64_t Val = -1; // All ones
2001 Val <<= TypeBits-1; // Shift over to the right spot
2002 return CS->getValue() == Val+1;
2003}
2004
Chris Lattner457dd822004-06-09 07:59:58 +00002005// isOneBitSet - Return true if there is exactly one bit set in the specified
2006// constant.
2007static bool isOneBitSet(const ConstantInt *CI) {
2008 uint64_t V = CI->getRawValue();
2009 return V && (V & (V-1)) == 0;
2010}
2011
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00002012#if 0 // Currently unused
2013// isLowOnes - Return true if the constant is of the form 0+1+.
2014static bool isLowOnes(const ConstantInt *CI) {
2015 uint64_t V = CI->getRawValue();
2016
2017 // There won't be bits set in parts that the type doesn't contain.
2018 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
2019
2020 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2021 return U && V && (U & V) == 0;
2022}
2023#endif
2024
2025// isHighOnes - Return true if the constant is of the form 1+0+.
2026// This is the same as lowones(~X).
2027static bool isHighOnes(const ConstantInt *CI) {
2028 uint64_t V = ~CI->getRawValue();
Chris Lattner2b83af22005-08-07 07:03:10 +00002029 if (~V == 0) return false; // 0's does not match "1+"
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00002030
2031 // There won't be bits set in parts that the type doesn't contain.
2032 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
2033
2034 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2035 return U && V && (U & V) == 0;
2036}
2037
2038
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002039/// getSetCondCode - Encode a setcc opcode into a three bit mask. These bits
2040/// are carefully arranged to allow folding of expressions such as:
2041///
2042/// (A < B) | (A > B) --> (A != B)
2043///
2044/// Bit value '4' represents that the comparison is true if A > B, bit value '2'
2045/// represents that the comparison is true if A == B, and bit value '1' is true
2046/// if A < B.
2047///
2048static unsigned getSetCondCode(const SetCondInst *SCI) {
2049 switch (SCI->getOpcode()) {
2050 // False -> 0
2051 case Instruction::SetGT: return 1;
2052 case Instruction::SetEQ: return 2;
2053 case Instruction::SetGE: return 3;
2054 case Instruction::SetLT: return 4;
2055 case Instruction::SetNE: return 5;
2056 case Instruction::SetLE: return 6;
2057 // True -> 7
2058 default:
2059 assert(0 && "Invalid SetCC opcode!");
2060 return 0;
2061 }
2062}
2063
2064/// getSetCCValue - This is the complement of getSetCondCode, which turns an
2065/// opcode and two operands into either a constant true or false, or a brand new
2066/// SetCC instruction.
2067static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
2068 switch (Opcode) {
2069 case 0: return ConstantBool::False;
2070 case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
2071 case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
2072 case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
2073 case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
2074 case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
2075 case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
2076 case 7: return ConstantBool::True;
2077 default: assert(0 && "Illegal SetCCCode!"); return 0;
2078 }
2079}
2080
2081// FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
2082struct FoldSetCCLogical {
2083 InstCombiner &IC;
2084 Value *LHS, *RHS;
2085 FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
2086 : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
2087 bool shouldApply(Value *V) const {
2088 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
2089 return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
2090 SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
2091 return false;
2092 }
2093 Instruction *apply(BinaryOperator &Log) const {
2094 SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
2095 if (SCI->getOperand(0) != LHS) {
2096 assert(SCI->getOperand(1) == LHS);
2097 SCI->swapOperands(); // Swap the LHS and RHS of the SetCC
2098 }
2099
2100 unsigned LHSCode = getSetCondCode(SCI);
2101 unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
2102 unsigned Code;
2103 switch (Log.getOpcode()) {
2104 case Instruction::And: Code = LHSCode & RHSCode; break;
2105 case Instruction::Or: Code = LHSCode | RHSCode; break;
2106 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner021c1902003-09-22 20:33:34 +00002107 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002108 }
2109
2110 Value *RV = getSetCCValue(Code, LHS, RHS);
2111 if (Instruction *I = dyn_cast<Instruction>(RV))
2112 return I;
2113 // Otherwise, it's a constant boolean value...
2114 return IC.ReplaceInstUsesWith(Log, RV);
2115 }
2116};
2117
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002118// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
2119// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
2120// guaranteed to be either a shift instruction or a binary operator.
2121Instruction *InstCombiner::OptAndOp(Instruction *Op,
2122 ConstantIntegral *OpRHS,
2123 ConstantIntegral *AndRHS,
2124 BinaryOperator &TheAnd) {
2125 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00002126 Constant *Together = 0;
2127 if (!isa<ShiftInst>(Op))
Chris Lattner48595f12004-06-10 02:07:29 +00002128 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00002129
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002130 switch (Op->getOpcode()) {
2131 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00002132 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002133 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
2134 std::string OpName = Op->getName(); Op->setName("");
Chris Lattner48595f12004-06-10 02:07:29 +00002135 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002136 InsertNewInstBefore(And, TheAnd);
Chris Lattner48595f12004-06-10 02:07:29 +00002137 return BinaryOperator::createXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002138 }
2139 break;
2140 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00002141 if (Together == AndRHS) // (X | C) & C --> C
2142 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00002143
Chris Lattner6e7ba452005-01-01 16:22:27 +00002144 if (Op->hasOneUse() && Together != OpRHS) {
2145 // (X | C1) & C2 --> (X | (C1&C2)) & C2
2146 std::string Op0Name = Op->getName(); Op->setName("");
2147 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
2148 InsertNewInstBefore(Or, TheAnd);
2149 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002150 }
2151 break;
2152 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00002153 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002154 // Adding a one to a single bit bit-field should be turned into an XOR
2155 // of the bit. First thing to check is to see if this AND is with a
2156 // single bit constant.
Chris Lattner457dd822004-06-09 07:59:58 +00002157 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getRawValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002158
2159 // Clear bits that are not part of the constant.
Chris Lattner1a074fc2006-02-07 07:00:41 +00002160 AndRHSV &= AndRHS->getType()->getIntegralTypeMask();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002161
2162 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00002163 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002164 // Ok, at this point, we know that we are masking the result of the
2165 // ADD down to exactly one bit. If the constant we are adding has
2166 // no bits set below this bit, then we can eliminate the ADD.
Chris Lattner457dd822004-06-09 07:59:58 +00002167 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getRawValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00002168
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002169 // Check to see if any bits below the one bit set in AndRHSV are set.
2170 if ((AddRHS & (AndRHSV-1)) == 0) {
2171 // If not, the only thing that can effect the output of the AND is
2172 // the bit specified by AndRHSV. If that bit is set, the effect of
2173 // the XOR is to toggle the bit. If it is clear, then the ADD has
2174 // no effect.
2175 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
2176 TheAnd.setOperand(0, X);
2177 return &TheAnd;
2178 } else {
2179 std::string Name = Op->getName(); Op->setName("");
2180 // Pull the XOR out of the AND.
Chris Lattner48595f12004-06-10 02:07:29 +00002181 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002182 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner48595f12004-06-10 02:07:29 +00002183 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002184 }
2185 }
2186 }
2187 }
2188 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00002189
2190 case Instruction::Shl: {
2191 // We know that the AND will not produce any of the bits shifted in, so if
2192 // the anded constant includes them, clear them now!
2193 //
2194 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner0c967662004-09-24 15:21:34 +00002195 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
2196 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00002197
Chris Lattner0c967662004-09-24 15:21:34 +00002198 if (CI == ShlMask) { // Masking out bits that the shift already masks
2199 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
2200 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00002201 TheAnd.setOperand(1, CI);
2202 return &TheAnd;
2203 }
2204 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00002205 }
Chris Lattner62a355c2003-09-19 19:05:02 +00002206 case Instruction::Shr:
2207 // We know that the AND will not produce any of the bits shifted in, so if
2208 // the anded constant includes them, clear them now! This only applies to
2209 // unsigned shifts, because a signed shr may bring in set bits!
2210 //
2211 if (AndRHS->getType()->isUnsigned()) {
2212 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner0c967662004-09-24 15:21:34 +00002213 Constant *ShrMask = ConstantExpr::getShr(AllOne, OpRHS);
2214 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
2215
2216 if (CI == ShrMask) { // Masking out bits that the shift already masks.
2217 return ReplaceInstUsesWith(TheAnd, Op);
2218 } else if (CI != AndRHS) {
2219 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
Chris Lattner62a355c2003-09-19 19:05:02 +00002220 return &TheAnd;
2221 }
Chris Lattner0c967662004-09-24 15:21:34 +00002222 } else { // Signed shr.
2223 // See if this is shifting in some sign extension, then masking it out
2224 // with an and.
2225 if (Op->hasOneUse()) {
2226 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2227 Constant *ShrMask = ConstantExpr::getUShr(AllOne, OpRHS);
2228 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
Chris Lattner9b991822004-10-22 04:53:16 +00002229 if (CI == AndRHS) { // Masking out bits shifted in.
Chris Lattner0c967662004-09-24 15:21:34 +00002230 // Make the argument unsigned.
2231 Value *ShVal = Op->getOperand(0);
2232 ShVal = InsertCastBefore(ShVal,
2233 ShVal->getType()->getUnsignedVersion(),
2234 TheAnd);
2235 ShVal = InsertNewInstBefore(new ShiftInst(Instruction::Shr, ShVal,
2236 OpRHS, Op->getName()),
2237 TheAnd);
Chris Lattnerdc781222004-10-27 05:57:15 +00002238 Value *AndRHS2 = ConstantExpr::getCast(AndRHS, ShVal->getType());
2239 ShVal = InsertNewInstBefore(BinaryOperator::createAnd(ShVal, AndRHS2,
2240 TheAnd.getName()),
2241 TheAnd);
Chris Lattner0c967662004-09-24 15:21:34 +00002242 return new CastInst(ShVal, Op->getType());
2243 }
2244 }
Chris Lattner62a355c2003-09-19 19:05:02 +00002245 }
2246 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002247 }
2248 return 0;
2249}
2250
Chris Lattner8b170942002-08-09 23:47:40 +00002251
Chris Lattnera96879a2004-09-29 17:40:11 +00002252/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
2253/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
2254/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. IB is the location to
2255/// insert new instructions.
2256Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
2257 bool Inside, Instruction &IB) {
2258 assert(cast<ConstantBool>(ConstantExpr::getSetLE(Lo, Hi))->getValue() &&
2259 "Lo is not <= Hi in range emission code!");
2260 if (Inside) {
2261 if (Lo == Hi) // Trivially false.
2262 return new SetCondInst(Instruction::SetNE, V, V);
2263 if (cast<ConstantIntegral>(Lo)->isMinValue())
2264 return new SetCondInst(Instruction::SetLT, V, Hi);
Misha Brukmanfd939082005-04-21 23:48:37 +00002265
Chris Lattnera96879a2004-09-29 17:40:11 +00002266 Constant *AddCST = ConstantExpr::getNeg(Lo);
2267 Instruction *Add = BinaryOperator::createAdd(V, AddCST,V->getName()+".off");
2268 InsertNewInstBefore(Add, IB);
2269 // Convert to unsigned for the comparison.
2270 const Type *UnsType = Add->getType()->getUnsignedVersion();
2271 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
2272 AddCST = ConstantExpr::getAdd(AddCST, Hi);
2273 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2274 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
2275 }
2276
2277 if (Lo == Hi) // Trivially true.
2278 return new SetCondInst(Instruction::SetEQ, V, V);
2279
2280 Hi = SubOne(cast<ConstantInt>(Hi));
2281 if (cast<ConstantIntegral>(Lo)->isMinValue()) // V < 0 || V >= Hi ->'V > Hi-1'
2282 return new SetCondInst(Instruction::SetGT, V, Hi);
2283
2284 // Emit X-Lo > Hi-Lo-1
2285 Constant *AddCST = ConstantExpr::getNeg(Lo);
2286 Instruction *Add = BinaryOperator::createAdd(V, AddCST, V->getName()+".off");
2287 InsertNewInstBefore(Add, IB);
2288 // Convert to unsigned for the comparison.
2289 const Type *UnsType = Add->getType()->getUnsignedVersion();
2290 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
2291 AddCST = ConstantExpr::getAdd(AddCST, Hi);
2292 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2293 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
2294}
2295
Chris Lattner7203e152005-09-18 07:22:02 +00002296// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
2297// any number of 0s on either side. The 1s are allowed to wrap from LSB to
2298// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
2299// not, since all 1s are not contiguous.
2300static bool isRunOfOnes(ConstantIntegral *Val, unsigned &MB, unsigned &ME) {
2301 uint64_t V = Val->getRawValue();
2302 if (!isShiftedMask_64(V)) return false;
2303
2304 // look for the first zero bit after the run of ones
2305 MB = 64-CountLeadingZeros_64((V - 1) ^ V);
2306 // look for the first non-zero bit
2307 ME = 64-CountLeadingZeros_64(V);
2308 return true;
2309}
2310
2311
2312
2313/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
2314/// where isSub determines whether the operator is a sub. If we can fold one of
2315/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00002316///
2317/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
2318/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
2319/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
2320///
2321/// return (A +/- B).
2322///
2323Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
2324 ConstantIntegral *Mask, bool isSub,
2325 Instruction &I) {
2326 Instruction *LHSI = dyn_cast<Instruction>(LHS);
2327 if (!LHSI || LHSI->getNumOperands() != 2 ||
2328 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
2329
2330 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
2331
2332 switch (LHSI->getOpcode()) {
2333 default: return 0;
2334 case Instruction::And:
Chris Lattner7203e152005-09-18 07:22:02 +00002335 if (ConstantExpr::getAnd(N, Mask) == Mask) {
2336 // If the AndRHS is a power of two minus one (0+1+), this is simple.
2337 if ((Mask->getRawValue() & Mask->getRawValue()+1) == 0)
2338 break;
2339
2340 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
2341 // part, we don't need any explicit masks to take them out of A. If that
2342 // is all N is, ignore it.
2343 unsigned MB, ME;
2344 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Chris Lattner3bedbd92006-02-07 07:27:52 +00002345 uint64_t Mask = RHS->getType()->getIntegralTypeMask();
2346 Mask >>= 64-MB+1;
2347 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00002348 break;
2349 }
2350 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00002351 return 0;
2352 case Instruction::Or:
2353 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00002354 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
2355 if ((Mask->getRawValue() & Mask->getRawValue()+1) == 0 &&
2356 ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattnerc8e77562005-09-18 04:24:45 +00002357 break;
2358 return 0;
2359 }
2360
2361 Instruction *New;
2362 if (isSub)
2363 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
2364 else
2365 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
2366 return InsertNewInstBefore(New, I);
2367}
2368
Chris Lattner7e708292002-06-25 16:13:24 +00002369Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002370 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002371 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002372
Chris Lattnere87597f2004-10-16 18:11:37 +00002373 if (isa<UndefValue>(Op1)) // X & undef -> 0
2374 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2375
Chris Lattner6e7ba452005-01-01 16:22:27 +00002376 // and X, X = X
2377 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00002378 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002379
Chris Lattnerf8c36f52006-02-12 08:02:11 +00002380 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00002381 // purpose is to compute bits we don't care about.
Chris Lattner255d8912006-02-11 09:31:47 +00002382 uint64_t KnownZero, KnownOne;
Chris Lattner98509ef2006-03-25 21:58:26 +00002383 if (!isa<PackedType>(I.getType()) &&
2384 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattner255d8912006-02-11 09:31:47 +00002385 KnownZero, KnownOne))
Chris Lattner9ca96412006-02-08 03:25:32 +00002386 return &I;
2387
Chris Lattner6e7ba452005-01-01 16:22:27 +00002388 if (ConstantIntegral *AndRHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner7560c3a2006-02-08 07:34:50 +00002389 uint64_t AndRHSMask = AndRHS->getZExtValue();
2390 uint64_t TypeMask = Op0->getType()->getIntegralTypeMask();
Chris Lattner7560c3a2006-02-08 07:34:50 +00002391 uint64_t NotAndRHS = AndRHSMask^TypeMask;
Chris Lattner6e7ba452005-01-01 16:22:27 +00002392
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002393 // Optimize a variety of ((val OP C1) & C2) combinations...
2394 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
2395 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner6e7ba452005-01-01 16:22:27 +00002396 Value *Op0LHS = Op0I->getOperand(0);
2397 Value *Op0RHS = Op0I->getOperand(1);
2398 switch (Op0I->getOpcode()) {
2399 case Instruction::Xor:
2400 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00002401 // If the mask is only needed on one incoming arm, push it up.
2402 if (Op0I->hasOneUse()) {
2403 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
2404 // Not masking anything out for the LHS, move to RHS.
2405 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
2406 Op0RHS->getName()+".masked");
2407 InsertNewInstBefore(NewRHS, I);
2408 return BinaryOperator::create(
2409 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00002410 }
Chris Lattner3bedbd92006-02-07 07:27:52 +00002411 if (!isa<Constant>(Op0RHS) &&
Chris Lattnerad1e3022005-01-23 20:26:55 +00002412 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
2413 // Not masking anything out for the RHS, move to LHS.
2414 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
2415 Op0LHS->getName()+".masked");
2416 InsertNewInstBefore(NewLHS, I);
2417 return BinaryOperator::create(
2418 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
2419 }
2420 }
2421
Chris Lattner6e7ba452005-01-01 16:22:27 +00002422 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00002423 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00002424 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
2425 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
2426 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
2427 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
2428 return BinaryOperator::createAnd(V, AndRHS);
2429 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
2430 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00002431 break;
2432
2433 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00002434 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
2435 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
2436 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
2437 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
2438 return BinaryOperator::createAnd(V, AndRHS);
Chris Lattnerc8e77562005-09-18 04:24:45 +00002439 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00002440 }
2441
Chris Lattner58403262003-07-23 19:25:52 +00002442 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002443 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002444 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00002445 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
2446 const Type *SrcTy = CI->getOperand(0)->getType();
2447
Chris Lattner2b83af22005-08-07 07:03:10 +00002448 // If this is an integer truncation or change from signed-to-unsigned, and
2449 // if the source is an and/or with immediate, transform it. This
2450 // frequently occurs for bitfield accesses.
2451 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
2452 if (SrcTy->getPrimitiveSizeInBits() >=
2453 I.getType()->getPrimitiveSizeInBits() &&
2454 CastOp->getNumOperands() == 2)
Chris Lattner7560c3a2006-02-08 07:34:50 +00002455 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
Chris Lattner2b83af22005-08-07 07:03:10 +00002456 if (CastOp->getOpcode() == Instruction::And) {
2457 // Change: and (cast (and X, C1) to T), C2
2458 // into : and (cast X to T), trunc(C1)&C2
2459 // This will folds the two ands together, which may allow other
2460 // simplifications.
2461 Instruction *NewCast =
2462 new CastInst(CastOp->getOperand(0), I.getType(),
2463 CastOp->getName()+".shrunk");
2464 NewCast = InsertNewInstBefore(NewCast, I);
2465
2466 Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
2467 C3 = ConstantExpr::getAnd(C3, AndRHS); // trunc(C1)&C2
2468 return BinaryOperator::createAnd(NewCast, C3);
2469 } else if (CastOp->getOpcode() == Instruction::Or) {
2470 // Change: and (cast (or X, C1) to T), C2
2471 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
2472 Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
2473 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
2474 return ReplaceInstUsesWith(I, AndRHS);
2475 }
2476 }
Chris Lattner06782f82003-07-23 19:36:21 +00002477 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002478
2479 // Try to fold constant and into select arguments.
2480 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002481 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002482 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002483 if (isa<PHINode>(Op0))
2484 if (Instruction *NV = FoldOpIntoPhi(I))
2485 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00002486 }
2487
Chris Lattner8d969642003-03-10 23:06:50 +00002488 Value *Op0NotVal = dyn_castNotVal(Op0);
2489 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00002490
Chris Lattner5b62aa72004-06-18 06:07:51 +00002491 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
2492 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2493
Misha Brukmancb6267b2004-07-30 12:50:08 +00002494 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00002495 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattner48595f12004-06-10 02:07:29 +00002496 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
2497 I.getName()+".demorgan");
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00002498 InsertNewInstBefore(Or, I);
Chris Lattnera2881962003-02-18 19:28:33 +00002499 return BinaryOperator::createNot(Or);
2500 }
Chris Lattner2082ad92006-02-13 23:07:23 +00002501
2502 {
2503 Value *A = 0, *B = 0;
2504 ConstantInt *C1 = 0, *C2 = 0;
2505 if (match(Op0, m_Or(m_Value(A), m_Value(B))))
2506 if (A == Op1 || B == Op1) // (A | ?) & A --> A
2507 return ReplaceInstUsesWith(I, Op1);
2508 if (match(Op1, m_Or(m_Value(A), m_Value(B))))
2509 if (A == Op0 || B == Op0) // A & (A | ?) --> A
2510 return ReplaceInstUsesWith(I, Op0);
Chris Lattner64daab52006-04-01 08:03:55 +00002511
2512 if (Op0->hasOneUse() &&
2513 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
2514 if (A == Op1) { // (A^B)&A -> A&(A^B)
2515 I.swapOperands(); // Simplify below
2516 std::swap(Op0, Op1);
2517 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
2518 cast<BinaryOperator>(Op0)->swapOperands();
2519 I.swapOperands(); // Simplify below
2520 std::swap(Op0, Op1);
2521 }
2522 }
2523 if (Op1->hasOneUse() &&
2524 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
2525 if (B == Op0) { // B&(A^B) -> B&(B^A)
2526 cast<BinaryOperator>(Op1)->swapOperands();
2527 std::swap(A, B);
2528 }
2529 if (A == Op0) { // A&(A^B) -> A & ~B
2530 Instruction *NotB = BinaryOperator::createNot(B, "tmp");
2531 InsertNewInstBefore(NotB, I);
2532 return BinaryOperator::createAnd(A, NotB);
2533 }
2534 }
Chris Lattner2082ad92006-02-13 23:07:23 +00002535 }
2536
Chris Lattnera2881962003-02-18 19:28:33 +00002537
Chris Lattner955f3312004-09-28 21:48:02 +00002538 if (SetCondInst *RHS = dyn_cast<SetCondInst>(Op1)) {
2539 // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002540 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
2541 return R;
2542
Chris Lattner955f3312004-09-28 21:48:02 +00002543 Value *LHSVal, *RHSVal;
2544 ConstantInt *LHSCst, *RHSCst;
2545 Instruction::BinaryOps LHSCC, RHSCC;
2546 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
2547 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
2548 if (LHSVal == RHSVal && // Found (X setcc C1) & (X setcc C2)
2549 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
Misha Brukmanfd939082005-04-21 23:48:37 +00002550 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
Chris Lattner955f3312004-09-28 21:48:02 +00002551 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
2552 // Ensure that the larger constant is on the RHS.
2553 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
2554 SetCondInst *LHS = cast<SetCondInst>(Op0);
2555 if (cast<ConstantBool>(Cmp)->getValue()) {
2556 std::swap(LHS, RHS);
2557 std::swap(LHSCst, RHSCst);
2558 std::swap(LHSCC, RHSCC);
2559 }
2560
2561 // At this point, we know we have have two setcc instructions
2562 // comparing a value against two constants and and'ing the result
2563 // together. Because of the above check, we know that we only have
2564 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
2565 // FoldSetCCLogical check above), that the two constants are not
2566 // equal.
2567 assert(LHSCst != RHSCst && "Compares not folded above?");
2568
2569 switch (LHSCC) {
2570 default: assert(0 && "Unknown integer condition code!");
2571 case Instruction::SetEQ:
2572 switch (RHSCC) {
2573 default: assert(0 && "Unknown integer condition code!");
2574 case Instruction::SetEQ: // (X == 13 & X == 15) -> false
2575 case Instruction::SetGT: // (X == 13 & X > 15) -> false
2576 return ReplaceInstUsesWith(I, ConstantBool::False);
2577 case Instruction::SetNE: // (X == 13 & X != 15) -> X == 13
2578 case Instruction::SetLT: // (X == 13 & X < 15) -> X == 13
2579 return ReplaceInstUsesWith(I, LHS);
2580 }
2581 case Instruction::SetNE:
2582 switch (RHSCC) {
2583 default: assert(0 && "Unknown integer condition code!");
2584 case Instruction::SetLT:
2585 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X < 14) -> X < 13
2586 return new SetCondInst(Instruction::SetLT, LHSVal, LHSCst);
2587 break; // (X != 13 & X < 15) -> no change
2588 case Instruction::SetEQ: // (X != 13 & X == 15) -> X == 15
2589 case Instruction::SetGT: // (X != 13 & X > 15) -> X > 15
2590 return ReplaceInstUsesWith(I, RHS);
2591 case Instruction::SetNE:
2592 if (LHSCst == SubOne(RHSCst)) {// (X != 13 & X != 14) -> X-13 >u 1
2593 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
2594 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
2595 LHSVal->getName()+".off");
2596 InsertNewInstBefore(Add, I);
2597 const Type *UnsType = Add->getType()->getUnsignedVersion();
2598 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
2599 AddCST = ConstantExpr::getSub(RHSCst, LHSCst);
2600 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2601 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
2602 }
2603 break; // (X != 13 & X != 15) -> no change
2604 }
2605 break;
2606 case Instruction::SetLT:
2607 switch (RHSCC) {
2608 default: assert(0 && "Unknown integer condition code!");
2609 case Instruction::SetEQ: // (X < 13 & X == 15) -> false
2610 case Instruction::SetGT: // (X < 13 & X > 15) -> false
2611 return ReplaceInstUsesWith(I, ConstantBool::False);
2612 case Instruction::SetNE: // (X < 13 & X != 15) -> X < 13
2613 case Instruction::SetLT: // (X < 13 & X < 15) -> X < 13
2614 return ReplaceInstUsesWith(I, LHS);
2615 }
2616 case Instruction::SetGT:
2617 switch (RHSCC) {
2618 default: assert(0 && "Unknown integer condition code!");
2619 case Instruction::SetEQ: // (X > 13 & X == 15) -> X > 13
2620 return ReplaceInstUsesWith(I, LHS);
2621 case Instruction::SetGT: // (X > 13 & X > 15) -> X > 15
2622 return ReplaceInstUsesWith(I, RHS);
2623 case Instruction::SetNE:
2624 if (RHSCst == AddOne(LHSCst)) // (X > 13 & X != 14) -> X > 14
2625 return new SetCondInst(Instruction::SetGT, LHSVal, RHSCst);
2626 break; // (X > 13 & X != 15) -> no change
Chris Lattnera96879a2004-09-29 17:40:11 +00002627 case Instruction::SetLT: // (X > 13 & X < 15) -> (X-14) <u 1
2628 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, I);
Chris Lattner955f3312004-09-28 21:48:02 +00002629 }
2630 }
2631 }
2632 }
2633
Chris Lattner7e708292002-06-25 16:13:24 +00002634 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00002635}
2636
Chris Lattner7e708292002-06-25 16:13:24 +00002637Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002638 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002639 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002640
Chris Lattnere87597f2004-10-16 18:11:37 +00002641 if (isa<UndefValue>(Op1))
2642 return ReplaceInstUsesWith(I, // X | undef -> -1
2643 ConstantIntegral::getAllOnesValue(I.getType()));
2644
Chris Lattnerf8c36f52006-02-12 08:02:11 +00002645 // or X, X = X
2646 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00002647 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002648
Chris Lattnerf8c36f52006-02-12 08:02:11 +00002649 // See if we can simplify any instructions used by the instruction whose sole
2650 // purpose is to compute bits we don't care about.
2651 uint64_t KnownZero, KnownOne;
Chris Lattner98509ef2006-03-25 21:58:26 +00002652 if (!isa<PackedType>(I.getType()) &&
2653 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattnerf8c36f52006-02-12 08:02:11 +00002654 KnownZero, KnownOne))
2655 return &I;
2656
Chris Lattner3f5b8772002-05-06 16:14:14 +00002657 // or X, -1 == -1
Chris Lattnerad44ebf2003-07-23 18:29:44 +00002658 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002659 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002660 // (X & C1) | C2 --> (X | C2) & (C1|C2)
2661 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattner6e4c6492005-05-09 04:58:36 +00002662 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0->getName());
2663 Op0->setName("");
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002664 InsertNewInstBefore(Or, I);
2665 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
2666 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00002667
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002668 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
2669 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
2670 std::string Op0Name = Op0->getName(); Op0->setName("");
2671 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
2672 InsertNewInstBefore(Or, I);
2673 return BinaryOperator::createXor(Or,
2674 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00002675 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002676
2677 // Try to fold constant and into select arguments.
2678 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002679 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002680 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002681 if (isa<PHINode>(Op0))
2682 if (Instruction *NV = FoldOpIntoPhi(I))
2683 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00002684 }
2685
Chris Lattner4f637d42006-01-06 17:59:59 +00002686 Value *A = 0, *B = 0;
2687 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00002688
2689 if (match(Op0, m_And(m_Value(A), m_Value(B))))
2690 if (A == Op1 || B == Op1) // (A & ?) | A --> A
2691 return ReplaceInstUsesWith(I, Op1);
2692 if (match(Op1, m_And(m_Value(A), m_Value(B))))
2693 if (A == Op0 || B == Op0) // A | (A & ?) --> A
2694 return ReplaceInstUsesWith(I, Op0);
2695
Chris Lattner6e4c6492005-05-09 04:58:36 +00002696 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
2697 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattner3bedbd92006-02-07 07:27:52 +00002698 MaskedValueIsZero(Op1, C1->getZExtValue())) {
Chris Lattner6e4c6492005-05-09 04:58:36 +00002699 Instruction *NOr = BinaryOperator::createOr(A, Op1, Op0->getName());
2700 Op0->setName("");
2701 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
2702 }
2703
2704 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
2705 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattner3bedbd92006-02-07 07:27:52 +00002706 MaskedValueIsZero(Op0, C1->getZExtValue())) {
Chris Lattner6e4c6492005-05-09 04:58:36 +00002707 Instruction *NOr = BinaryOperator::createOr(A, Op0, Op1->getName());
2708 Op0->setName("");
2709 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
2710 }
2711
Chris Lattnere9bed7d2005-09-18 03:42:07 +00002712 // (A & C1)|(B & C2)
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002713 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattnere9bed7d2005-09-18 03:42:07 +00002714 match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
2715
2716 if (A == B) // (A & C1)|(A & C2) == A & (C1|C2)
2717 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
2718
2719
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00002720 // If we have: ((V + N) & C1) | (V & C2)
2721 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
2722 // replace with V+N.
2723 if (C1 == ConstantExpr::getNot(C2)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002724 Value *V1 = 0, *V2 = 0;
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00002725 if ((C2->getRawValue() & (C2->getRawValue()+1)) == 0 && // C2 == 0+1+
2726 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
2727 // Add commutes, try both ways.
Chris Lattner3bedbd92006-02-07 07:27:52 +00002728 if (V1 == B && MaskedValueIsZero(V2, C2->getZExtValue()))
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00002729 return ReplaceInstUsesWith(I, A);
Chris Lattner3bedbd92006-02-07 07:27:52 +00002730 if (V2 == B && MaskedValueIsZero(V1, C2->getZExtValue()))
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00002731 return ReplaceInstUsesWith(I, A);
2732 }
2733 // Or commutes, try both ways.
2734 if ((C1->getRawValue() & (C1->getRawValue()+1)) == 0 &&
2735 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
2736 // Add commutes, try both ways.
Chris Lattner3bedbd92006-02-07 07:27:52 +00002737 if (V1 == A && MaskedValueIsZero(V2, C1->getZExtValue()))
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00002738 return ReplaceInstUsesWith(I, B);
Chris Lattner3bedbd92006-02-07 07:27:52 +00002739 if (V2 == A && MaskedValueIsZero(V1, C1->getZExtValue()))
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00002740 return ReplaceInstUsesWith(I, B);
Chris Lattnere9bed7d2005-09-18 03:42:07 +00002741 }
2742 }
2743 }
Chris Lattner67ca7682003-08-12 19:11:07 +00002744
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002745 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
2746 if (A == Op1) // ~A | A == -1
Misha Brukmanfd939082005-04-21 23:48:37 +00002747 return ReplaceInstUsesWith(I,
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002748 ConstantIntegral::getAllOnesValue(I.getType()));
2749 } else {
2750 A = 0;
2751 }
Chris Lattnerf4d4c872005-05-07 23:49:08 +00002752 // Note, A is still live here!
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002753 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
2754 if (Op0 == B)
Misha Brukmanfd939082005-04-21 23:48:37 +00002755 return ReplaceInstUsesWith(I,
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002756 ConstantIntegral::getAllOnesValue(I.getType()));
Chris Lattnera27231a2003-03-10 23:13:59 +00002757
Misha Brukmancb6267b2004-07-30 12:50:08 +00002758 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002759 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
2760 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
2761 I.getName()+".demorgan"), I);
2762 return BinaryOperator::createNot(And);
2763 }
Chris Lattnera27231a2003-03-10 23:13:59 +00002764 }
Chris Lattnera2881962003-02-18 19:28:33 +00002765
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002766 // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
Chris Lattnerb4f40d22004-09-28 22:33:08 +00002767 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1))) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002768 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
2769 return R;
2770
Chris Lattnerb4f40d22004-09-28 22:33:08 +00002771 Value *LHSVal, *RHSVal;
2772 ConstantInt *LHSCst, *RHSCst;
2773 Instruction::BinaryOps LHSCC, RHSCC;
2774 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
2775 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
2776 if (LHSVal == RHSVal && // Found (X setcc C1) | (X setcc C2)
2777 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
Misha Brukmanfd939082005-04-21 23:48:37 +00002778 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
Chris Lattnerb4f40d22004-09-28 22:33:08 +00002779 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
2780 // Ensure that the larger constant is on the RHS.
2781 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
2782 SetCondInst *LHS = cast<SetCondInst>(Op0);
2783 if (cast<ConstantBool>(Cmp)->getValue()) {
2784 std::swap(LHS, RHS);
2785 std::swap(LHSCst, RHSCst);
2786 std::swap(LHSCC, RHSCC);
2787 }
2788
2789 // At this point, we know we have have two setcc instructions
2790 // comparing a value against two constants and or'ing the result
2791 // together. Because of the above check, we know that we only have
2792 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
2793 // FoldSetCCLogical check above), that the two constants are not
2794 // equal.
2795 assert(LHSCst != RHSCst && "Compares not folded above?");
2796
2797 switch (LHSCC) {
2798 default: assert(0 && "Unknown integer condition code!");
2799 case Instruction::SetEQ:
2800 switch (RHSCC) {
2801 default: assert(0 && "Unknown integer condition code!");
2802 case Instruction::SetEQ:
2803 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
2804 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
2805 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
2806 LHSVal->getName()+".off");
2807 InsertNewInstBefore(Add, I);
2808 const Type *UnsType = Add->getType()->getUnsignedVersion();
2809 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
2810 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
2811 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2812 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
2813 }
2814 break; // (X == 13 | X == 15) -> no change
2815
Chris Lattner240d6f42005-04-19 06:04:18 +00002816 case Instruction::SetGT: // (X == 13 | X > 14) -> no change
2817 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00002818 case Instruction::SetNE: // (X == 13 | X != 15) -> X != 15
2819 case Instruction::SetLT: // (X == 13 | X < 15) -> X < 15
2820 return ReplaceInstUsesWith(I, RHS);
2821 }
2822 break;
2823 case Instruction::SetNE:
2824 switch (RHSCC) {
2825 default: assert(0 && "Unknown integer condition code!");
Chris Lattnerb4f40d22004-09-28 22:33:08 +00002826 case Instruction::SetEQ: // (X != 13 | X == 15) -> X != 13
2827 case Instruction::SetGT: // (X != 13 | X > 15) -> X != 13
2828 return ReplaceInstUsesWith(I, LHS);
2829 case Instruction::SetNE: // (X != 13 | X != 15) -> true
Chris Lattnere88b7532005-06-17 03:59:17 +00002830 case Instruction::SetLT: // (X != 13 | X < 15) -> true
Chris Lattnerb4f40d22004-09-28 22:33:08 +00002831 return ReplaceInstUsesWith(I, ConstantBool::True);
2832 }
2833 break;
2834 case Instruction::SetLT:
2835 switch (RHSCC) {
2836 default: assert(0 && "Unknown integer condition code!");
2837 case Instruction::SetEQ: // (X < 13 | X == 14) -> no change
2838 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00002839 case Instruction::SetGT: // (X < 13 | X > 15) -> (X-13) > 2
2840 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, I);
Chris Lattnerb4f40d22004-09-28 22:33:08 +00002841 case Instruction::SetNE: // (X < 13 | X != 15) -> X != 15
2842 case Instruction::SetLT: // (X < 13 | X < 15) -> X < 15
2843 return ReplaceInstUsesWith(I, RHS);
2844 }
2845 break;
2846 case Instruction::SetGT:
2847 switch (RHSCC) {
2848 default: assert(0 && "Unknown integer condition code!");
2849 case Instruction::SetEQ: // (X > 13 | X == 15) -> X > 13
2850 case Instruction::SetGT: // (X > 13 | X > 15) -> X > 13
2851 return ReplaceInstUsesWith(I, LHS);
2852 case Instruction::SetNE: // (X > 13 | X != 15) -> true
2853 case Instruction::SetLT: // (X > 13 | X < 15) -> true
2854 return ReplaceInstUsesWith(I, ConstantBool::True);
2855 }
2856 }
2857 }
2858 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00002859
Chris Lattner7e708292002-06-25 16:13:24 +00002860 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00002861}
2862
Chris Lattnerc317d392004-02-16 01:20:27 +00002863// XorSelf - Implements: X ^ X --> 0
2864struct XorSelf {
2865 Value *RHS;
2866 XorSelf(Value *rhs) : RHS(rhs) {}
2867 bool shouldApply(Value *LHS) const { return LHS == RHS; }
2868 Instruction *apply(BinaryOperator &Xor) const {
2869 return &Xor;
2870 }
2871};
Chris Lattner3f5b8772002-05-06 16:14:14 +00002872
2873
Chris Lattner7e708292002-06-25 16:13:24 +00002874Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002875 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002876 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002877
Chris Lattnere87597f2004-10-16 18:11:37 +00002878 if (isa<UndefValue>(Op1))
2879 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
2880
Chris Lattnerc317d392004-02-16 01:20:27 +00002881 // xor X, X = 0, even if X is nested in a sequence of Xor's.
2882 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
2883 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattner233f7dc2002-08-12 21:17:25 +00002884 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00002885 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00002886
2887 // See if we can simplify any instructions used by the instruction whose sole
2888 // purpose is to compute bits we don't care about.
2889 uint64_t KnownZero, KnownOne;
Chris Lattner98509ef2006-03-25 21:58:26 +00002890 if (!isa<PackedType>(I.getType()) &&
2891 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattnerf8c36f52006-02-12 08:02:11 +00002892 KnownZero, KnownOne))
2893 return &I;
Chris Lattner3f5b8772002-05-06 16:14:14 +00002894
Chris Lattnereca0c5c2003-07-23 21:37:07 +00002895 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattnereca0c5c2003-07-23 21:37:07 +00002896 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner05bd1b22002-08-20 18:24:26 +00002897 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
Chris Lattnereca0c5c2003-07-23 21:37:07 +00002898 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
Chris Lattnerfd059242003-10-15 16:48:29 +00002899 if (RHS == ConstantBool::True && SCI->hasOneUse())
Chris Lattner05bd1b22002-08-20 18:24:26 +00002900 return new SetCondInst(SCI->getInverseCondition(),
2901 SCI->getOperand(0), SCI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00002902
Chris Lattnerd65460f2003-11-05 01:06:05 +00002903 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00002904 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
2905 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattner48595f12004-06-10 02:07:29 +00002906 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
2907 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattner7c4049c2004-01-12 19:35:11 +00002908 ConstantInt::get(I.getType(), 1));
Chris Lattner48595f12004-06-10 02:07:29 +00002909 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00002910 }
Chris Lattner5b62aa72004-06-18 06:07:51 +00002911
2912 // ~(~X & Y) --> (X | ~Y)
2913 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
2914 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
2915 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
2916 Instruction *NotY =
Misha Brukmanfd939082005-04-21 23:48:37 +00002917 BinaryOperator::createNot(Op0I->getOperand(1),
Chris Lattner5b62aa72004-06-18 06:07:51 +00002918 Op0I->getOperand(1)->getName()+".not");
2919 InsertNewInstBefore(NotY, I);
2920 return BinaryOperator::createOr(Op0NotVal, NotY);
2921 }
2922 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002923
Chris Lattnereca0c5c2003-07-23 21:37:07 +00002924 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattnerf8c36f52006-02-12 08:02:11 +00002925 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00002926 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00002927 if (RHS->isAllOnesValue()) {
Chris Lattner48595f12004-06-10 02:07:29 +00002928 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
2929 return BinaryOperator::createSub(
2930 ConstantExpr::getSub(NegOp0CI,
Chris Lattner7c4049c2004-01-12 19:35:11 +00002931 ConstantInt::get(I.getType(), 1)),
Chris Lattner689d24b2003-11-04 23:37:10 +00002932 Op0I->getOperand(0));
Chris Lattner7c4049c2004-01-12 19:35:11 +00002933 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00002934 } else if (Op0I->getOpcode() == Instruction::Or) {
2935 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
2936 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getZExtValue())) {
2937 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
2938 // Anything in both C1 and C2 is known to be zero, remove it from
2939 // NewRHS.
2940 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
2941 NewRHS = ConstantExpr::getAnd(NewRHS,
2942 ConstantExpr::getNot(CommonBits));
2943 WorkList.push_back(Op0I);
2944 I.setOperand(0, Op0I->getOperand(0));
2945 I.setOperand(1, NewRHS);
2946 return &I;
2947 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00002948 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00002949 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002950
2951 // Try to fold constant and into select arguments.
2952 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002953 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002954 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002955 if (isa<PHINode>(Op0))
2956 if (Instruction *NV = FoldOpIntoPhi(I))
2957 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00002958 }
2959
Chris Lattner8d969642003-03-10 23:06:50 +00002960 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00002961 if (X == Op1)
2962 return ReplaceInstUsesWith(I,
2963 ConstantIntegral::getAllOnesValue(I.getType()));
2964
Chris Lattner8d969642003-03-10 23:06:50 +00002965 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00002966 if (X == Op0)
2967 return ReplaceInstUsesWith(I,
2968 ConstantIntegral::getAllOnesValue(I.getType()));
2969
Chris Lattner64daab52006-04-01 08:03:55 +00002970 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
Chris Lattner26ca7e12004-02-16 03:54:20 +00002971 if (Op1I->getOpcode() == Instruction::Or) {
Chris Lattnercb40a372003-03-10 18:24:17 +00002972 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00002973 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00002974 I.swapOperands();
2975 std::swap(Op0, Op1);
2976 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00002977 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00002978 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00002979 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00002980 } else if (Op1I->getOpcode() == Instruction::Xor) {
2981 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
2982 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
2983 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
2984 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
Chris Lattner64daab52006-04-01 08:03:55 +00002985 } else if (Op1I->getOpcode() == Instruction::And && Op1I->hasOneUse()) {
2986 if (Op1I->getOperand(0) == Op0) // A^(A&B) -> A^(B&A)
2987 Op1I->swapOperands();
2988 if (Op0 == Op1I->getOperand(1)) { // A^(B&A) -> (B&A)^A
2989 I.swapOperands(); // Simplified below.
2990 std::swap(Op0, Op1);
2991 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00002992 }
Chris Lattnercb40a372003-03-10 18:24:17 +00002993
Chris Lattner64daab52006-04-01 08:03:55 +00002994 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
Chris Lattnerfd059242003-10-15 16:48:29 +00002995 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
Chris Lattnercb40a372003-03-10 18:24:17 +00002996 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00002997 Op0I->swapOperands();
Chris Lattner4f98c562003-03-10 21:43:22 +00002998 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattner64daab52006-04-01 08:03:55 +00002999 Instruction *NotB = BinaryOperator::createNot(Op1, "tmp");
3000 InsertNewInstBefore(NotB, I);
Chris Lattner48595f12004-06-10 02:07:29 +00003001 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
Chris Lattnercb40a372003-03-10 18:24:17 +00003002 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00003003 } else if (Op0I->getOpcode() == Instruction::Xor) {
3004 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
3005 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
3006 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
3007 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner64daab52006-04-01 08:03:55 +00003008 } else if (Op0I->getOpcode() == Instruction::And && Op0I->hasOneUse()) {
3009 if (Op0I->getOperand(0) == Op1) // (A&B)^A -> (B&A)^A
3010 Op0I->swapOperands();
Chris Lattnerae1ab392006-04-01 22:05:01 +00003011 if (Op0I->getOperand(1) == Op1 && // (B&A)^A == ~B & A
3012 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner64daab52006-04-01 08:03:55 +00003013 Instruction *N = BinaryOperator::createNot(Op0I->getOperand(0), "tmp");
3014 InsertNewInstBefore(N, I);
3015 return BinaryOperator::createAnd(N, Op1);
3016 }
Chris Lattnercb40a372003-03-10 18:24:17 +00003017 }
3018
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003019 // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
3020 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
3021 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
3022 return R;
3023
Chris Lattner7e708292002-06-25 16:13:24 +00003024 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00003025}
3026
Chris Lattnera96879a2004-09-29 17:40:11 +00003027/// MulWithOverflow - Compute Result = In1*In2, returning true if the result
3028/// overflowed for this type.
3029static bool MulWithOverflow(ConstantInt *&Result, ConstantInt *In1,
3030 ConstantInt *In2) {
3031 Result = cast<ConstantInt>(ConstantExpr::getMul(In1, In2));
3032 return !In2->isNullValue() && ConstantExpr::getDiv(Result, In2) != In1;
3033}
3034
3035static bool isPositive(ConstantInt *C) {
3036 return cast<ConstantSInt>(C)->getValue() >= 0;
3037}
3038
3039/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
3040/// overflowed for this type.
3041static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
3042 ConstantInt *In2) {
3043 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
3044
3045 if (In1->getType()->isUnsigned())
3046 return cast<ConstantUInt>(Result)->getValue() <
3047 cast<ConstantUInt>(In1)->getValue();
3048 if (isPositive(In1) != isPositive(In2))
3049 return false;
3050 if (isPositive(In1))
3051 return cast<ConstantSInt>(Result)->getValue() <
3052 cast<ConstantSInt>(In1)->getValue();
3053 return cast<ConstantSInt>(Result)->getValue() >
3054 cast<ConstantSInt>(In1)->getValue();
3055}
3056
Chris Lattner574da9b2005-01-13 20:14:25 +00003057/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
3058/// code necessary to compute the offset from the base pointer (without adding
3059/// in the base pointer). Return the result as a signed integer of intptr size.
3060static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
3061 TargetData &TD = IC.getTargetData();
3062 gep_type_iterator GTI = gep_type_begin(GEP);
3063 const Type *UIntPtrTy = TD.getIntPtrType();
3064 const Type *SIntPtrTy = UIntPtrTy->getSignedVersion();
3065 Value *Result = Constant::getNullValue(SIntPtrTy);
3066
3067 // Build a mask for high order bits.
Chris Lattner1a074fc2006-02-07 07:00:41 +00003068 uint64_t PtrSizeMask = ~0ULL >> (64-TD.getPointerSize()*8);
Chris Lattner574da9b2005-01-13 20:14:25 +00003069
Chris Lattner574da9b2005-01-13 20:14:25 +00003070 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
3071 Value *Op = GEP->getOperand(i);
Chris Lattner0b84c802005-01-13 23:26:48 +00003072 uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattner574da9b2005-01-13 20:14:25 +00003073 Constant *Scale = ConstantExpr::getCast(ConstantUInt::get(UIntPtrTy, Size),
3074 SIntPtrTy);
3075 if (Constant *OpC = dyn_cast<Constant>(Op)) {
3076 if (!OpC->isNullValue()) {
Chris Lattner5bdf04c2005-01-13 20:40:58 +00003077 OpC = ConstantExpr::getCast(OpC, SIntPtrTy);
Chris Lattner574da9b2005-01-13 20:14:25 +00003078 Scale = ConstantExpr::getMul(OpC, Scale);
3079 if (Constant *RC = dyn_cast<Constant>(Result))
3080 Result = ConstantExpr::getAdd(RC, Scale);
3081 else {
3082 // Emit an add instruction.
3083 Result = IC.InsertNewInstBefore(
3084 BinaryOperator::createAdd(Result, Scale,
3085 GEP->getName()+".offs"), I);
3086 }
3087 }
3088 } else {
Chris Lattner6f7f02f2005-01-14 17:17:59 +00003089 // Convert to correct type.
3090 Op = IC.InsertNewInstBefore(new CastInst(Op, SIntPtrTy,
3091 Op->getName()+".c"), I);
3092 if (Size != 1)
Chris Lattner5bdf04c2005-01-13 20:40:58 +00003093 // We'll let instcombine(mul) convert this to a shl if possible.
3094 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
3095 GEP->getName()+".idx"), I);
Chris Lattner574da9b2005-01-13 20:14:25 +00003096
3097 // Emit an add instruction.
Chris Lattner5bdf04c2005-01-13 20:40:58 +00003098 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
Chris Lattner574da9b2005-01-13 20:14:25 +00003099 GEP->getName()+".offs"), I);
3100 }
3101 }
3102 return Result;
3103}
3104
3105/// FoldGEPSetCC - Fold comparisons between a GEP instruction and something
3106/// else. At this point we know that the GEP is on the LHS of the comparison.
3107Instruction *InstCombiner::FoldGEPSetCC(User *GEPLHS, Value *RHS,
3108 Instruction::BinaryOps Cond,
3109 Instruction &I) {
3110 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattnere9d782b2005-01-13 22:25:21 +00003111
3112 if (CastInst *CI = dyn_cast<CastInst>(RHS))
3113 if (isa<PointerType>(CI->getOperand(0)->getType()))
3114 RHS = CI->getOperand(0);
3115
Chris Lattner574da9b2005-01-13 20:14:25 +00003116 Value *PtrBase = GEPLHS->getOperand(0);
3117 if (PtrBase == RHS) {
3118 // As an optimization, we don't actually have to compute the actual value of
3119 // OFFSET if this is a seteq or setne comparison, just return whether each
3120 // index is zero or not.
Chris Lattnere9d782b2005-01-13 22:25:21 +00003121 if (Cond == Instruction::SetEQ || Cond == Instruction::SetNE) {
3122 Instruction *InVal = 0;
Chris Lattnerad5fec12005-01-28 19:32:01 +00003123 gep_type_iterator GTI = gep_type_begin(GEPLHS);
3124 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattnere9d782b2005-01-13 22:25:21 +00003125 bool EmitIt = true;
3126 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
3127 if (isa<UndefValue>(C)) // undef index -> undef.
3128 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3129 if (C->isNullValue())
3130 EmitIt = false;
Chris Lattnerad5fec12005-01-28 19:32:01 +00003131 else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
3132 EmitIt = false; // This is indexing into a zero sized array?
Misha Brukmanfd939082005-04-21 23:48:37 +00003133 } else if (isa<ConstantInt>(C))
Chris Lattnere9d782b2005-01-13 22:25:21 +00003134 return ReplaceInstUsesWith(I, // No comparison is needed here.
3135 ConstantBool::get(Cond == Instruction::SetNE));
3136 }
3137
3138 if (EmitIt) {
Misha Brukmanfd939082005-04-21 23:48:37 +00003139 Instruction *Comp =
Chris Lattnere9d782b2005-01-13 22:25:21 +00003140 new SetCondInst(Cond, GEPLHS->getOperand(i),
3141 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
3142 if (InVal == 0)
3143 InVal = Comp;
3144 else {
3145 InVal = InsertNewInstBefore(InVal, I);
3146 InsertNewInstBefore(Comp, I);
3147 if (Cond == Instruction::SetNE) // True if any are unequal
3148 InVal = BinaryOperator::createOr(InVal, Comp);
3149 else // True if all are equal
3150 InVal = BinaryOperator::createAnd(InVal, Comp);
3151 }
3152 }
3153 }
3154
3155 if (InVal)
3156 return InVal;
3157 else
3158 ReplaceInstUsesWith(I, // No comparison is needed here, all indexes = 0
3159 ConstantBool::get(Cond == Instruction::SetEQ));
3160 }
Chris Lattner574da9b2005-01-13 20:14:25 +00003161
3162 // Only lower this if the setcc is the only user of the GEP or if we expect
3163 // the result to fold to a constant!
3164 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
3165 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
3166 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
3167 return new SetCondInst(Cond, Offset,
3168 Constant::getNullValue(Offset->getType()));
3169 }
3170 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00003171 // If the base pointers are different, but the indices are the same, just
3172 // compare the base pointer.
3173 if (PtrBase != GEPRHS->getOperand(0)) {
3174 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00003175 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00003176 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00003177 if (IndicesTheSame)
3178 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
3179 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
3180 IndicesTheSame = false;
3181 break;
3182 }
3183
3184 // If all indices are the same, just compare the base pointers.
3185 if (IndicesTheSame)
3186 return new SetCondInst(Cond, GEPLHS->getOperand(0),
3187 GEPRHS->getOperand(0));
3188
3189 // Otherwise, the base pointers are different and the indices are
3190 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00003191 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00003192 }
Chris Lattner574da9b2005-01-13 20:14:25 +00003193
Chris Lattnere9d782b2005-01-13 22:25:21 +00003194 // If one of the GEPs has all zero indices, recurse.
3195 bool AllZeros = true;
3196 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
3197 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
3198 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
3199 AllZeros = false;
3200 break;
3201 }
3202 if (AllZeros)
3203 return FoldGEPSetCC(GEPRHS, GEPLHS->getOperand(0),
3204 SetCondInst::getSwappedCondition(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00003205
3206 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00003207 AllZeros = true;
3208 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
3209 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
3210 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
3211 AllZeros = false;
3212 break;
3213 }
3214 if (AllZeros)
3215 return FoldGEPSetCC(GEPLHS, GEPRHS->getOperand(0), Cond, I);
3216
Chris Lattner4401c9c2005-01-14 00:20:05 +00003217 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
3218 // If the GEPs only differ by one index, compare it.
3219 unsigned NumDifferences = 0; // Keep track of # differences.
3220 unsigned DiffOperand = 0; // The operand that differs.
3221 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
3222 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00003223 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
3224 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00003225 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00003226 NumDifferences = 2;
3227 break;
3228 } else {
3229 if (NumDifferences++) break;
3230 DiffOperand = i;
3231 }
3232 }
3233
3234 if (NumDifferences == 0) // SAME GEP?
3235 return ReplaceInstUsesWith(I, // No comparison is needed here.
3236 ConstantBool::get(Cond == Instruction::SetEQ));
3237 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00003238 Value *LHSV = GEPLHS->getOperand(DiffOperand);
3239 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Chris Lattner7911f032005-07-18 23:07:33 +00003240
3241 // Convert the operands to signed values to make sure to perform a
3242 // signed comparison.
3243 const Type *NewTy = LHSV->getType()->getSignedVersion();
3244 if (LHSV->getType() != NewTy)
3245 LHSV = InsertNewInstBefore(new CastInst(LHSV, NewTy,
3246 LHSV->getName()), I);
3247 if (RHSV->getType() != NewTy)
3248 RHSV = InsertNewInstBefore(new CastInst(RHSV, NewTy,
3249 RHSV->getName()), I);
3250 return new SetCondInst(Cond, LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00003251 }
3252 }
3253
Chris Lattner574da9b2005-01-13 20:14:25 +00003254 // Only lower this if the setcc is the only user of the GEP or if we expect
3255 // the result to fold to a constant!
3256 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
3257 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
3258 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
3259 Value *L = EmitGEPOffset(GEPLHS, I, *this);
3260 Value *R = EmitGEPOffset(GEPRHS, I, *this);
3261 return new SetCondInst(Cond, L, R);
3262 }
3263 }
3264 return 0;
3265}
3266
3267
Chris Lattner484d3cf2005-04-24 06:59:08 +00003268Instruction *InstCombiner::visitSetCondInst(SetCondInst &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003269 bool Changed = SimplifyCommutative(I);
Chris Lattner8b170942002-08-09 23:47:40 +00003270 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3271 const Type *Ty = Op0->getType();
Chris Lattner3f5b8772002-05-06 16:14:14 +00003272
3273 // setcc X, X
Chris Lattner8b170942002-08-09 23:47:40 +00003274 if (Op0 == Op1)
3275 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
Chris Lattner53a5b572002-05-09 20:11:54 +00003276
Chris Lattnere87597f2004-10-16 18:11:37 +00003277 if (isa<UndefValue>(Op1)) // X setcc undef -> undef
3278 return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
3279
Chris Lattner711b3402004-11-14 07:33:16 +00003280 // setcc <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
3281 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanfd939082005-04-21 23:48:37 +00003282 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
3283 isa<ConstantPointerNull>(Op0)) &&
3284 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner711b3402004-11-14 07:33:16 +00003285 isa<ConstantPointerNull>(Op1)))
Chris Lattner8b170942002-08-09 23:47:40 +00003286 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
3287
3288 // setcc's with boolean values can always be turned into bitwise operations
3289 if (Ty == Type::BoolTy) {
Chris Lattner5dbef222004-08-11 00:50:51 +00003290 switch (I.getOpcode()) {
3291 default: assert(0 && "Invalid setcc instruction!");
3292 case Instruction::SetEQ: { // seteq bool %A, %B -> ~(A^B)
Chris Lattner48595f12004-06-10 02:07:29 +00003293 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner8b170942002-08-09 23:47:40 +00003294 InsertNewInstBefore(Xor, I);
Chris Lattnerde90b762003-11-03 04:25:02 +00003295 return BinaryOperator::createNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00003296 }
Chris Lattner5dbef222004-08-11 00:50:51 +00003297 case Instruction::SetNE:
3298 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00003299
Chris Lattner5dbef222004-08-11 00:50:51 +00003300 case Instruction::SetGT:
3301 std::swap(Op0, Op1); // Change setgt -> setlt
3302 // FALL THROUGH
3303 case Instruction::SetLT: { // setlt bool A, B -> ~X & Y
3304 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
3305 InsertNewInstBefore(Not, I);
3306 return BinaryOperator::createAnd(Not, Op1);
3307 }
3308 case Instruction::SetGE:
Chris Lattner8b170942002-08-09 23:47:40 +00003309 std::swap(Op0, Op1); // Change setge -> setle
Chris Lattner5dbef222004-08-11 00:50:51 +00003310 // FALL THROUGH
3311 case Instruction::SetLE: { // setle bool %A, %B -> ~A | B
3312 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
3313 InsertNewInstBefore(Not, I);
3314 return BinaryOperator::createOr(Not, Op1);
3315 }
3316 }
Chris Lattner8b170942002-08-09 23:47:40 +00003317 }
3318
Chris Lattner2be51ae2004-06-09 04:24:29 +00003319 // See if we are doing a comparison between a constant and an instruction that
3320 // can be folded into the comparison.
Chris Lattner8b170942002-08-09 23:47:40 +00003321 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnera96879a2004-09-29 17:40:11 +00003322 // Check to see if we are comparing against the minimum or maximum value...
3323 if (CI->isMinValue()) {
3324 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
3325 return ReplaceInstUsesWith(I, ConstantBool::False);
3326 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
3327 return ReplaceInstUsesWith(I, ConstantBool::True);
3328 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
3329 return BinaryOperator::createSetEQ(Op0, Op1);
3330 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
3331 return BinaryOperator::createSetNE(Op0, Op1);
3332
3333 } else if (CI->isMaxValue()) {
3334 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
3335 return ReplaceInstUsesWith(I, ConstantBool::False);
3336 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
3337 return ReplaceInstUsesWith(I, ConstantBool::True);
3338 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
3339 return BinaryOperator::createSetEQ(Op0, Op1);
3340 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
3341 return BinaryOperator::createSetNE(Op0, Op1);
3342
3343 // Comparing against a value really close to min or max?
3344 } else if (isMinValuePlusOne(CI)) {
3345 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
3346 return BinaryOperator::createSetEQ(Op0, SubOne(CI));
3347 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
3348 return BinaryOperator::createSetNE(Op0, SubOne(CI));
3349
3350 } else if (isMaxValueMinusOne(CI)) {
3351 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
3352 return BinaryOperator::createSetEQ(Op0, AddOne(CI));
3353 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
3354 return BinaryOperator::createSetNE(Op0, AddOne(CI));
3355 }
3356
3357 // If we still have a setle or setge instruction, turn it into the
3358 // appropriate setlt or setgt instruction. Since the border cases have
3359 // already been handled above, this requires little checking.
3360 //
3361 if (I.getOpcode() == Instruction::SetLE)
3362 return BinaryOperator::createSetLT(Op0, AddOne(CI));
3363 if (I.getOpcode() == Instruction::SetGE)
3364 return BinaryOperator::createSetGT(Op0, SubOne(CI));
3365
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00003366
3367 // See if we can fold the comparison based on bits known to be zero or one
3368 // in the input.
3369 uint64_t KnownZero, KnownOne;
3370 if (SimplifyDemandedBits(Op0, Ty->getIntegralTypeMask(),
3371 KnownZero, KnownOne, 0))
3372 return &I;
3373
3374 // Given the known and unknown bits, compute a range that the LHS could be
3375 // in.
3376 if (KnownOne | KnownZero) {
3377 if (Ty->isUnsigned()) { // Unsigned comparison.
3378 uint64_t Min, Max;
3379 uint64_t RHSVal = CI->getZExtValue();
3380 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,
3381 Min, Max);
3382 switch (I.getOpcode()) { // LE/GE have been folded already.
3383 default: assert(0 && "Unknown setcc opcode!");
3384 case Instruction::SetEQ:
3385 if (Max < RHSVal || Min > RHSVal)
3386 return ReplaceInstUsesWith(I, ConstantBool::False);
3387 break;
3388 case Instruction::SetNE:
3389 if (Max < RHSVal || Min > RHSVal)
3390 return ReplaceInstUsesWith(I, ConstantBool::True);
3391 break;
3392 case Instruction::SetLT:
3393 if (Max < RHSVal) return ReplaceInstUsesWith(I, ConstantBool::True);
3394 if (Min > RHSVal) return ReplaceInstUsesWith(I, ConstantBool::False);
3395 break;
3396 case Instruction::SetGT:
3397 if (Min > RHSVal) return ReplaceInstUsesWith(I, ConstantBool::True);
3398 if (Max < RHSVal) return ReplaceInstUsesWith(I, ConstantBool::False);
3399 break;
3400 }
3401 } else { // Signed comparison.
3402 int64_t Min, Max;
3403 int64_t RHSVal = CI->getSExtValue();
3404 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,
3405 Min, Max);
3406 switch (I.getOpcode()) { // LE/GE have been folded already.
3407 default: assert(0 && "Unknown setcc opcode!");
3408 case Instruction::SetEQ:
3409 if (Max < RHSVal || Min > RHSVal)
3410 return ReplaceInstUsesWith(I, ConstantBool::False);
3411 break;
3412 case Instruction::SetNE:
3413 if (Max < RHSVal || Min > RHSVal)
3414 return ReplaceInstUsesWith(I, ConstantBool::True);
3415 break;
3416 case Instruction::SetLT:
3417 if (Max < RHSVal) return ReplaceInstUsesWith(I, ConstantBool::True);
3418 if (Min > RHSVal) return ReplaceInstUsesWith(I, ConstantBool::False);
3419 break;
3420 case Instruction::SetGT:
3421 if (Min > RHSVal) return ReplaceInstUsesWith(I, ConstantBool::True);
3422 if (Max < RHSVal) return ReplaceInstUsesWith(I, ConstantBool::False);
3423 break;
3424 }
3425 }
3426 }
3427
3428
Chris Lattner3c6a0d42004-05-25 06:32:08 +00003429 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner648e3bc2004-09-23 21:52:49 +00003430 switch (LHSI->getOpcode()) {
3431 case Instruction::And:
3432 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
3433 LHSI->getOperand(0)->hasOneUse()) {
3434 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
3435 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
3436 // happens a LOT in code produced by the C front-end, for bitfield
3437 // access.
3438 ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00003439 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
3440
3441 // Check to see if there is a noop-cast between the shift and the and.
3442 if (!Shift) {
3443 if (CastInst *CI = dyn_cast<CastInst>(LHSI->getOperand(0)))
3444 if (CI->getOperand(0)->getType()->isIntegral() &&
3445 CI->getOperand(0)->getType()->getPrimitiveSizeInBits() ==
3446 CI->getType()->getPrimitiveSizeInBits())
3447 Shift = dyn_cast<ShiftInst>(CI->getOperand(0));
3448 }
3449
Chris Lattner648e3bc2004-09-23 21:52:49 +00003450 ConstantUInt *ShAmt;
3451 ShAmt = Shift ? dyn_cast<ConstantUInt>(Shift->getOperand(1)) : 0;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00003452 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
3453 const Type *AndTy = AndCST->getType(); // Type of the and.
Misha Brukmanfd939082005-04-21 23:48:37 +00003454
Chris Lattner648e3bc2004-09-23 21:52:49 +00003455 // We can fold this as long as we can't shift unknown bits
3456 // into the mask. This can only happen with signed shift
3457 // rights, as they sign-extend.
3458 if (ShAmt) {
3459 bool CanFold = Shift->getOpcode() != Instruction::Shr ||
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00003460 Ty->isUnsigned();
Chris Lattner648e3bc2004-09-23 21:52:49 +00003461 if (!CanFold) {
3462 // To test for the bad case of the signed shr, see if any
3463 // of the bits shifted in could be tested after the mask.
Chris Lattnerd7e31cf2005-06-17 01:29:28 +00003464 int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getValue();
3465 if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
3466
3467 Constant *OShAmt = ConstantUInt::get(Type::UByteTy, ShAmtVal);
Misha Brukmanfd939082005-04-21 23:48:37 +00003468 Constant *ShVal =
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00003469 ConstantExpr::getShl(ConstantInt::getAllOnesValue(AndTy),
3470 OShAmt);
Chris Lattner648e3bc2004-09-23 21:52:49 +00003471 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
3472 CanFold = true;
3473 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003474
Chris Lattner648e3bc2004-09-23 21:52:49 +00003475 if (CanFold) {
Chris Lattner0cba71b2004-09-28 17:54:07 +00003476 Constant *NewCst;
3477 if (Shift->getOpcode() == Instruction::Shl)
3478 NewCst = ConstantExpr::getUShr(CI, ShAmt);
3479 else
3480 NewCst = ConstantExpr::getShl(CI, ShAmt);
Chris Lattner83c4ec02004-09-27 19:29:18 +00003481
Chris Lattner648e3bc2004-09-23 21:52:49 +00003482 // Check to see if we are shifting out any of the bits being
3483 // compared.
3484 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
3485 // If we shifted bits out, the fold is not going to work out.
3486 // As a special case, check to see if this means that the
3487 // result is always true or false now.
3488 if (I.getOpcode() == Instruction::SetEQ)
3489 return ReplaceInstUsesWith(I, ConstantBool::False);
3490 if (I.getOpcode() == Instruction::SetNE)
3491 return ReplaceInstUsesWith(I, ConstantBool::True);
3492 } else {
3493 I.setOperand(1, NewCst);
Chris Lattner0cba71b2004-09-28 17:54:07 +00003494 Constant *NewAndCST;
3495 if (Shift->getOpcode() == Instruction::Shl)
3496 NewAndCST = ConstantExpr::getUShr(AndCST, ShAmt);
3497 else
3498 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
3499 LHSI->setOperand(1, NewAndCST);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00003500 if (AndTy == Ty)
3501 LHSI->setOperand(0, Shift->getOperand(0));
3502 else {
3503 Value *NewCast = InsertCastBefore(Shift->getOperand(0), AndTy,
3504 *Shift);
3505 LHSI->setOperand(0, NewCast);
3506 }
Chris Lattner648e3bc2004-09-23 21:52:49 +00003507 WorkList.push_back(Shift); // Shift is dead.
3508 AddUsesToWorkList(I);
3509 return &I;
Chris Lattner5eb91942004-07-21 19:50:44 +00003510 }
3511 }
Chris Lattner457dd822004-06-09 07:59:58 +00003512 }
Chris Lattner648e3bc2004-09-23 21:52:49 +00003513 }
3514 break;
Chris Lattner83c4ec02004-09-27 19:29:18 +00003515
Chris Lattner18d19ca2004-09-28 18:22:15 +00003516 case Instruction::Shl: // (setcc (shl X, ShAmt), CI)
3517 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
3518 switch (I.getOpcode()) {
3519 default: break;
3520 case Instruction::SetEQ:
3521 case Instruction::SetNE: {
Chris Lattnere17a1282005-06-15 20:53:31 +00003522 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
3523
3524 // Check that the shift amount is in range. If not, don't perform
3525 // undefined shifts. When the shift is visited it will be
3526 // simplified.
3527 if (ShAmt->getValue() >= TypeBits)
3528 break;
3529
Chris Lattner18d19ca2004-09-28 18:22:15 +00003530 // If we are comparing against bits always shifted out, the
3531 // comparison cannot succeed.
Misha Brukmanfd939082005-04-21 23:48:37 +00003532 Constant *Comp =
Chris Lattner18d19ca2004-09-28 18:22:15 +00003533 ConstantExpr::getShl(ConstantExpr::getShr(CI, ShAmt), ShAmt);
3534 if (Comp != CI) {// Comparing against a bit that we know is zero.
3535 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
3536 Constant *Cst = ConstantBool::get(IsSetNE);
3537 return ReplaceInstUsesWith(I, Cst);
3538 }
3539
3540 if (LHSI->hasOneUse()) {
3541 // Otherwise strength reduce the shift into an and.
Chris Lattner652f3cf2005-01-08 19:42:22 +00003542 unsigned ShAmtVal = (unsigned)ShAmt->getValue();
Chris Lattner18d19ca2004-09-28 18:22:15 +00003543 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
3544
3545 Constant *Mask;
3546 if (CI->getType()->isUnsigned()) {
3547 Mask = ConstantUInt::get(CI->getType(), Val);
3548 } else if (ShAmtVal != 0) {
3549 Mask = ConstantSInt::get(CI->getType(), Val);
3550 } else {
3551 Mask = ConstantInt::getAllOnesValue(CI->getType());
3552 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003553
Chris Lattner18d19ca2004-09-28 18:22:15 +00003554 Instruction *AndI =
3555 BinaryOperator::createAnd(LHSI->getOperand(0),
3556 Mask, LHSI->getName()+".mask");
3557 Value *And = InsertNewInstBefore(AndI, I);
3558 return new SetCondInst(I.getOpcode(), And,
3559 ConstantExpr::getUShr(CI, ShAmt));
3560 }
3561 }
3562 }
3563 }
3564 break;
3565
Chris Lattner83c4ec02004-09-27 19:29:18 +00003566 case Instruction::Shr: // (setcc (shr X, ShAmt), CI)
Chris Lattnerf63f6472004-09-27 16:18:50 +00003567 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
Chris Lattnerf63f6472004-09-27 16:18:50 +00003568 switch (I.getOpcode()) {
3569 default: break;
3570 case Instruction::SetEQ:
3571 case Instruction::SetNE: {
Chris Lattnere17a1282005-06-15 20:53:31 +00003572
3573 // Check that the shift amount is in range. If not, don't perform
3574 // undefined shifts. When the shift is visited it will be
3575 // simplified.
Chris Lattneraa457ac2005-06-16 01:52:07 +00003576 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
Chris Lattnere17a1282005-06-15 20:53:31 +00003577 if (ShAmt->getValue() >= TypeBits)
3578 break;
3579
Chris Lattnerf63f6472004-09-27 16:18:50 +00003580 // If we are comparing against bits always shifted out, the
3581 // comparison cannot succeed.
Misha Brukmanfd939082005-04-21 23:48:37 +00003582 Constant *Comp =
Chris Lattnerf63f6472004-09-27 16:18:50 +00003583 ConstantExpr::getShr(ConstantExpr::getShl(CI, ShAmt), ShAmt);
Misha Brukmanfd939082005-04-21 23:48:37 +00003584
Chris Lattnerf63f6472004-09-27 16:18:50 +00003585 if (Comp != CI) {// Comparing against a bit that we know is zero.
3586 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
3587 Constant *Cst = ConstantBool::get(IsSetNE);
3588 return ReplaceInstUsesWith(I, Cst);
3589 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003590
Chris Lattnerf63f6472004-09-27 16:18:50 +00003591 if (LHSI->hasOneUse() || CI->isNullValue()) {
Chris Lattner652f3cf2005-01-08 19:42:22 +00003592 unsigned ShAmtVal = (unsigned)ShAmt->getValue();
Chris Lattner18d19ca2004-09-28 18:22:15 +00003593
Chris Lattnerf63f6472004-09-27 16:18:50 +00003594 // Otherwise strength reduce the shift into an and.
3595 uint64_t Val = ~0ULL; // All ones.
3596 Val <<= ShAmtVal; // Shift over to the right spot.
3597
3598 Constant *Mask;
3599 if (CI->getType()->isUnsigned()) {
Chris Lattnerf52d6812005-04-24 17:46:05 +00003600 Val &= ~0ULL >> (64-TypeBits);
Chris Lattnerf63f6472004-09-27 16:18:50 +00003601 Mask = ConstantUInt::get(CI->getType(), Val);
3602 } else {
3603 Mask = ConstantSInt::get(CI->getType(), Val);
3604 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003605
Chris Lattnerf63f6472004-09-27 16:18:50 +00003606 Instruction *AndI =
3607 BinaryOperator::createAnd(LHSI->getOperand(0),
3608 Mask, LHSI->getName()+".mask");
3609 Value *And = InsertNewInstBefore(AndI, I);
3610 return new SetCondInst(I.getOpcode(), And,
3611 ConstantExpr::getShl(CI, ShAmt));
3612 }
3613 break;
3614 }
3615 }
3616 }
3617 break;
Chris Lattner0c967662004-09-24 15:21:34 +00003618
Chris Lattnera96879a2004-09-29 17:40:11 +00003619 case Instruction::Div:
3620 // Fold: (div X, C1) op C2 -> range check
3621 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
3622 // Fold this div into the comparison, producing a range check.
3623 // Determine, based on the divide type, what the range is being
3624 // checked. If there is an overflow on the low or high side, remember
3625 // it, otherwise compute the range [low, hi) bounding the new value.
3626 bool LoOverflow = false, HiOverflow = 0;
3627 ConstantInt *LoBound = 0, *HiBound = 0;
3628
3629 ConstantInt *Prod;
3630 bool ProdOV = MulWithOverflow(Prod, CI, DivRHS);
3631
Chris Lattner6a9fdfa2004-10-11 19:40:04 +00003632 Instruction::BinaryOps Opcode = I.getOpcode();
3633
Chris Lattnera96879a2004-09-29 17:40:11 +00003634 if (DivRHS->isNullValue()) { // Don't hack on divide by zeros.
3635 } else if (LHSI->getType()->isUnsigned()) { // udiv
3636 LoBound = Prod;
3637 LoOverflow = ProdOV;
3638 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
3639 } else if (isPositive(DivRHS)) { // Divisor is > 0.
3640 if (CI->isNullValue()) { // (X / pos) op 0
3641 // Can't overflow.
3642 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
3643 HiBound = DivRHS;
3644 } else if (isPositive(CI)) { // (X / pos) op pos
3645 LoBound = Prod;
3646 LoOverflow = ProdOV;
3647 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
3648 } else { // (X / pos) op neg
3649 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
3650 LoOverflow = AddWithOverflow(LoBound, Prod,
3651 cast<ConstantInt>(DivRHSH));
3652 HiBound = Prod;
3653 HiOverflow = ProdOV;
3654 }
3655 } else { // Divisor is < 0.
3656 if (CI->isNullValue()) { // (X / neg) op 0
3657 LoBound = AddOne(DivRHS);
3658 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner56625032005-06-17 02:05:55 +00003659 if (HiBound == DivRHS)
3660 LoBound = 0; // - INTMIN = INTMIN
Chris Lattnera96879a2004-09-29 17:40:11 +00003661 } else if (isPositive(CI)) { // (X / neg) op pos
3662 HiOverflow = LoOverflow = ProdOV;
3663 if (!LoOverflow)
3664 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
3665 HiBound = AddOne(Prod);
3666 } else { // (X / neg) op neg
3667 LoBound = Prod;
3668 LoOverflow = HiOverflow = ProdOV;
3669 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
3670 }
Chris Lattner340a05f2004-10-08 19:15:44 +00003671
Chris Lattner6a9fdfa2004-10-11 19:40:04 +00003672 // Dividing by a negate swaps the condition.
3673 Opcode = SetCondInst::getSwappedCondition(Opcode);
Chris Lattnera96879a2004-09-29 17:40:11 +00003674 }
3675
3676 if (LoBound) {
3677 Value *X = LHSI->getOperand(0);
Chris Lattner6a9fdfa2004-10-11 19:40:04 +00003678 switch (Opcode) {
Chris Lattnera96879a2004-09-29 17:40:11 +00003679 default: assert(0 && "Unhandled setcc opcode!");
3680 case Instruction::SetEQ:
3681 if (LoOverflow && HiOverflow)
3682 return ReplaceInstUsesWith(I, ConstantBool::False);
3683 else if (HiOverflow)
3684 return new SetCondInst(Instruction::SetGE, X, LoBound);
3685 else if (LoOverflow)
3686 return new SetCondInst(Instruction::SetLT, X, HiBound);
3687 else
3688 return InsertRangeTest(X, LoBound, HiBound, true, I);
3689 case Instruction::SetNE:
3690 if (LoOverflow && HiOverflow)
3691 return ReplaceInstUsesWith(I, ConstantBool::True);
3692 else if (HiOverflow)
3693 return new SetCondInst(Instruction::SetLT, X, LoBound);
3694 else if (LoOverflow)
3695 return new SetCondInst(Instruction::SetGE, X, HiBound);
3696 else
3697 return InsertRangeTest(X, LoBound, HiBound, false, I);
3698 case Instruction::SetLT:
3699 if (LoOverflow)
3700 return ReplaceInstUsesWith(I, ConstantBool::False);
3701 return new SetCondInst(Instruction::SetLT, X, LoBound);
3702 case Instruction::SetGT:
3703 if (HiOverflow)
3704 return ReplaceInstUsesWith(I, ConstantBool::False);
3705 return new SetCondInst(Instruction::SetGE, X, HiBound);
3706 }
3707 }
3708 }
3709 break;
Chris Lattner648e3bc2004-09-23 21:52:49 +00003710 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003711
Chris Lattnerbc5d4142003-07-23 17:02:11 +00003712 // Simplify seteq and setne instructions...
3713 if (I.getOpcode() == Instruction::SetEQ ||
3714 I.getOpcode() == Instruction::SetNE) {
3715 bool isSetNE = I.getOpcode() == Instruction::SetNE;
3716
Chris Lattner00b1a7e2003-07-23 17:26:36 +00003717 // If the first operand is (and|or|xor) with a constant, and the second
Chris Lattnerbc5d4142003-07-23 17:02:11 +00003718 // operand is a constant, simplify a bit.
Chris Lattner934754b2003-08-13 05:33:12 +00003719 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
3720 switch (BO->getOpcode()) {
Chris Lattner3571b722004-07-06 07:38:18 +00003721 case Instruction::Rem:
3722 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
3723 if (CI->isNullValue() && isa<ConstantSInt>(BO->getOperand(1)) &&
3724 BO->hasOneUse() &&
Chris Lattnerbcd7db52005-08-02 19:16:58 +00003725 cast<ConstantSInt>(BO->getOperand(1))->getValue() > 1) {
3726 int64_t V = cast<ConstantSInt>(BO->getOperand(1))->getValue();
3727 if (isPowerOf2_64(V)) {
3728 unsigned L2 = Log2_64(V);
Chris Lattner3571b722004-07-06 07:38:18 +00003729 const Type *UTy = BO->getType()->getUnsignedVersion();
3730 Value *NewX = InsertNewInstBefore(new CastInst(BO->getOperand(0),
3731 UTy, "tmp"), I);
3732 Constant *RHSCst = ConstantUInt::get(UTy, 1ULL << L2);
3733 Value *NewRem =InsertNewInstBefore(BinaryOperator::createRem(NewX,
3734 RHSCst, BO->getName()), I);
3735 return BinaryOperator::create(I.getOpcode(), NewRem,
3736 Constant::getNullValue(UTy));
3737 }
Chris Lattnerbcd7db52005-08-02 19:16:58 +00003738 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003739 break;
Chris Lattner3571b722004-07-06 07:38:18 +00003740
Chris Lattner934754b2003-08-13 05:33:12 +00003741 case Instruction::Add:
Chris Lattner15d58b62004-06-27 22:51:36 +00003742 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
3743 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattner3d834bf2004-09-21 21:35:23 +00003744 if (BO->hasOneUse())
3745 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
3746 ConstantExpr::getSub(CI, BOp1C));
Chris Lattner15d58b62004-06-27 22:51:36 +00003747 } else if (CI->isNullValue()) {
Chris Lattner934754b2003-08-13 05:33:12 +00003748 // Replace ((add A, B) != 0) with (A != -B) if A or B is
3749 // efficiently invertible, or if the add has just this one use.
3750 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Misha Brukmanfd939082005-04-21 23:48:37 +00003751
Chris Lattner934754b2003-08-13 05:33:12 +00003752 if (Value *NegVal = dyn_castNegVal(BOp1))
3753 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
3754 else if (Value *NegVal = dyn_castNegVal(BOp0))
3755 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
Chris Lattnerfd059242003-10-15 16:48:29 +00003756 else if (BO->hasOneUse()) {
Chris Lattner934754b2003-08-13 05:33:12 +00003757 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
3758 BO->setName("");
3759 InsertNewInstBefore(Neg, I);
3760 return new SetCondInst(I.getOpcode(), BOp0, Neg);
3761 }
3762 }
3763 break;
3764 case Instruction::Xor:
3765 // For the xor case, we can xor two constants together, eliminating
3766 // the explicit xor.
3767 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
3768 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
Chris Lattner48595f12004-06-10 02:07:29 +00003769 ConstantExpr::getXor(CI, BOC));
Chris Lattner934754b2003-08-13 05:33:12 +00003770
3771 // FALLTHROUGH
3772 case Instruction::Sub:
3773 // Replace (([sub|xor] A, B) != 0) with (A != B)
3774 if (CI->isNullValue())
3775 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
3776 BO->getOperand(1));
3777 break;
3778
3779 case Instruction::Or:
3780 // If bits are being or'd in that are not present in the constant we
3781 // are comparing against, then the comparison could never succeed!
Chris Lattner7c4049c2004-01-12 19:35:11 +00003782 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattner448c3232004-06-10 02:12:35 +00003783 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattner48595f12004-06-10 02:07:29 +00003784 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Chris Lattnerbc5d4142003-07-23 17:02:11 +00003785 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattner7c4049c2004-01-12 19:35:11 +00003786 }
Chris Lattner934754b2003-08-13 05:33:12 +00003787 break;
3788
3789 case Instruction::And:
3790 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerbc5d4142003-07-23 17:02:11 +00003791 // If bits are being compared against that are and'd out, then the
3792 // comparison can never succeed!
Chris Lattner448c3232004-06-10 02:12:35 +00003793 if (!ConstantExpr::getAnd(CI,
3794 ConstantExpr::getNot(BOC))->isNullValue())
Chris Lattnerbc5d4142003-07-23 17:02:11 +00003795 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattner934754b2003-08-13 05:33:12 +00003796
Chris Lattner457dd822004-06-09 07:59:58 +00003797 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattner3285a6f2004-06-10 02:33:20 +00003798 if (CI == BOC && isOneBitSet(CI))
Chris Lattner457dd822004-06-09 07:59:58 +00003799 return new SetCondInst(isSetNE ? Instruction::SetEQ :
3800 Instruction::SetNE, Op0,
3801 Constant::getNullValue(CI->getType()));
Chris Lattner457dd822004-06-09 07:59:58 +00003802
Chris Lattner934754b2003-08-13 05:33:12 +00003803 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
3804 // to be a signed value as appropriate.
3805 if (isSignBit(BOC)) {
3806 Value *X = BO->getOperand(0);
3807 // If 'X' is not signed, insert a cast now...
3808 if (!BOC->getType()->isSigned()) {
Chris Lattner5dd04022004-06-17 18:16:02 +00003809 const Type *DestTy = BOC->getType()->getSignedVersion();
Chris Lattner83c4ec02004-09-27 19:29:18 +00003810 X = InsertCastBefore(X, DestTy, I);
Chris Lattner934754b2003-08-13 05:33:12 +00003811 }
3812 return new SetCondInst(isSetNE ? Instruction::SetLT :
3813 Instruction::SetGE, X,
3814 Constant::getNullValue(X->getType()));
3815 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003816
Chris Lattner83c4ec02004-09-27 19:29:18 +00003817 // ((X & ~7) == 0) --> X < 8
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003818 if (CI->isNullValue() && isHighOnes(BOC)) {
3819 Value *X = BO->getOperand(0);
Chris Lattner83c4ec02004-09-27 19:29:18 +00003820 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003821
3822 // If 'X' is signed, insert a cast now.
Chris Lattner83c4ec02004-09-27 19:29:18 +00003823 if (NegX->getType()->isSigned()) {
3824 const Type *DestTy = NegX->getType()->getUnsignedVersion();
3825 X = InsertCastBefore(X, DestTy, I);
3826 NegX = ConstantExpr::getCast(NegX, DestTy);
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003827 }
3828
3829 return new SetCondInst(isSetNE ? Instruction::SetGE :
Chris Lattner83c4ec02004-09-27 19:29:18 +00003830 Instruction::SetLT, X, NegX);
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003831 }
3832
Chris Lattnerbc5d4142003-07-23 17:02:11 +00003833 }
Chris Lattner934754b2003-08-13 05:33:12 +00003834 default: break;
3835 }
3836 }
Chris Lattnerc5943fb2004-02-23 07:16:20 +00003837 } else { // Not a SetEQ/SetNE
Misha Brukmanfd939082005-04-21 23:48:37 +00003838 // If the LHS is a cast from an integral value of the same size,
Chris Lattnerc5943fb2004-02-23 07:16:20 +00003839 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
3840 Value *CastOp = Cast->getOperand(0);
3841 const Type *SrcTy = CastOp->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00003842 unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
Chris Lattnerc5943fb2004-02-23 07:16:20 +00003843 if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
Chris Lattner484d3cf2005-04-24 06:59:08 +00003844 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
Misha Brukmanfd939082005-04-21 23:48:37 +00003845 assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) &&
Chris Lattnerc5943fb2004-02-23 07:16:20 +00003846 "Source and destination signednesses should differ!");
3847 if (Cast->getType()->isSigned()) {
3848 // If this is a signed comparison, check for comparisons in the
3849 // vicinity of zero.
3850 if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
3851 // X < 0 => x > 127
Chris Lattner48595f12004-06-10 02:07:29 +00003852 return BinaryOperator::createSetGT(CastOp,
Chris Lattner484d3cf2005-04-24 06:59:08 +00003853 ConstantUInt::get(SrcTy, (1ULL << (SrcTySize-1))-1));
Chris Lattnerc5943fb2004-02-23 07:16:20 +00003854 else if (I.getOpcode() == Instruction::SetGT &&
3855 cast<ConstantSInt>(CI)->getValue() == -1)
3856 // X > -1 => x < 128
Chris Lattner48595f12004-06-10 02:07:29 +00003857 return BinaryOperator::createSetLT(CastOp,
Chris Lattner484d3cf2005-04-24 06:59:08 +00003858 ConstantUInt::get(SrcTy, 1ULL << (SrcTySize-1)));
Chris Lattnerc5943fb2004-02-23 07:16:20 +00003859 } else {
3860 ConstantUInt *CUI = cast<ConstantUInt>(CI);
3861 if (I.getOpcode() == Instruction::SetLT &&
Chris Lattner484d3cf2005-04-24 06:59:08 +00003862 CUI->getValue() == 1ULL << (SrcTySize-1))
Chris Lattnerc5943fb2004-02-23 07:16:20 +00003863 // X < 128 => X > -1
Chris Lattner48595f12004-06-10 02:07:29 +00003864 return BinaryOperator::createSetGT(CastOp,
3865 ConstantSInt::get(SrcTy, -1));
Chris Lattnerc5943fb2004-02-23 07:16:20 +00003866 else if (I.getOpcode() == Instruction::SetGT &&
Chris Lattner484d3cf2005-04-24 06:59:08 +00003867 CUI->getValue() == (1ULL << (SrcTySize-1))-1)
Chris Lattnerc5943fb2004-02-23 07:16:20 +00003868 // X > 127 => X < 0
Chris Lattner48595f12004-06-10 02:07:29 +00003869 return BinaryOperator::createSetLT(CastOp,
3870 Constant::getNullValue(SrcTy));
Chris Lattnerc5943fb2004-02-23 07:16:20 +00003871 }
3872 }
3873 }
Chris Lattner40f5d702003-06-04 05:10:11 +00003874 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00003875 }
3876
Chris Lattner6970b662005-04-23 15:31:55 +00003877 // Handle setcc with constant RHS's that can be integer, FP or pointer.
3878 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
3879 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
3880 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00003881 case Instruction::GetElementPtr:
3882 if (RHSC->isNullValue()) {
3883 // Transform setcc GEP P, int 0, int 0, int 0, null -> setcc P, null
3884 bool isAllZeros = true;
3885 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
3886 if (!isa<Constant>(LHSI->getOperand(i)) ||
3887 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
3888 isAllZeros = false;
3889 break;
3890 }
3891 if (isAllZeros)
3892 return new SetCondInst(I.getOpcode(), LHSI->getOperand(0),
3893 Constant::getNullValue(LHSI->getOperand(0)->getType()));
3894 }
3895 break;
3896
Chris Lattner6970b662005-04-23 15:31:55 +00003897 case Instruction::PHI:
3898 if (Instruction *NV = FoldOpIntoPhi(I))
3899 return NV;
3900 break;
3901 case Instruction::Select:
3902 // If either operand of the select is a constant, we can fold the
3903 // comparison into the select arms, which will cause one to be
3904 // constant folded and the select turned into a bitwise or.
3905 Value *Op1 = 0, *Op2 = 0;
3906 if (LHSI->hasOneUse()) {
3907 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
3908 // Fold the known value into the constant operand.
3909 Op1 = ConstantExpr::get(I.getOpcode(), C, RHSC);
3910 // Insert a new SetCC of the other select operand.
3911 Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
3912 LHSI->getOperand(2), RHSC,
3913 I.getName()), I);
3914 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
3915 // Fold the known value into the constant operand.
3916 Op2 = ConstantExpr::get(I.getOpcode(), C, RHSC);
3917 // Insert a new SetCC of the other select operand.
3918 Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
3919 LHSI->getOperand(1), RHSC,
3920 I.getName()), I);
3921 }
3922 }
Jeff Cohen9d809302005-04-23 21:38:35 +00003923
Chris Lattner6970b662005-04-23 15:31:55 +00003924 if (Op1)
3925 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
3926 break;
3927 }
3928 }
3929
Chris Lattner574da9b2005-01-13 20:14:25 +00003930 // If we can optimize a 'setcc GEP, P' or 'setcc P, GEP', do so now.
3931 if (User *GEP = dyn_castGetElementPtr(Op0))
3932 if (Instruction *NI = FoldGEPSetCC(GEP, Op1, I.getOpcode(), I))
3933 return NI;
3934 if (User *GEP = dyn_castGetElementPtr(Op1))
3935 if (Instruction *NI = FoldGEPSetCC(GEP, Op0,
3936 SetCondInst::getSwappedCondition(I.getOpcode()), I))
3937 return NI;
3938
Chris Lattnerde90b762003-11-03 04:25:02 +00003939 // Test to see if the operands of the setcc are casted versions of other
3940 // values. If the cast can be stripped off both arguments, we do so now.
Chris Lattner68708052003-11-03 05:17:03 +00003941 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3942 Value *CastOp0 = CI->getOperand(0);
3943 if (CastOp0->getType()->isLosslesslyConvertibleTo(CI->getType()) &&
Chris Lattner0cea42a2004-03-13 23:54:27 +00003944 (isa<Constant>(Op1) || isa<CastInst>(Op1)) &&
Chris Lattnerde90b762003-11-03 04:25:02 +00003945 (I.getOpcode() == Instruction::SetEQ ||
3946 I.getOpcode() == Instruction::SetNE)) {
3947 // We keep moving the cast from the left operand over to the right
3948 // operand, where it can often be eliminated completely.
Chris Lattner68708052003-11-03 05:17:03 +00003949 Op0 = CastOp0;
Misha Brukmanfd939082005-04-21 23:48:37 +00003950
Chris Lattnerde90b762003-11-03 04:25:02 +00003951 // If operand #1 is a cast instruction, see if we can eliminate it as
3952 // well.
Chris Lattner68708052003-11-03 05:17:03 +00003953 if (CastInst *CI2 = dyn_cast<CastInst>(Op1))
3954 if (CI2->getOperand(0)->getType()->isLosslesslyConvertibleTo(
Chris Lattnerde90b762003-11-03 04:25:02 +00003955 Op0->getType()))
Chris Lattner68708052003-11-03 05:17:03 +00003956 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00003957
Chris Lattnerde90b762003-11-03 04:25:02 +00003958 // If Op1 is a constant, we can fold the cast into the constant.
3959 if (Op1->getType() != Op0->getType())
3960 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
3961 Op1 = ConstantExpr::getCast(Op1C, Op0->getType());
3962 } else {
3963 // Otherwise, cast the RHS right before the setcc
3964 Op1 = new CastInst(Op1, Op0->getType(), Op1->getName());
3965 InsertNewInstBefore(cast<Instruction>(Op1), I);
3966 }
3967 return BinaryOperator::create(I.getOpcode(), Op0, Op1);
3968 }
3969
Chris Lattner68708052003-11-03 05:17:03 +00003970 // Handle the special case of: setcc (cast bool to X), <cst>
3971 // This comes up when you have code like
3972 // int X = A < B;
3973 // if (X) ...
3974 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00003975 // with a constant or another cast from the same type.
3976 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
3977 if (Instruction *R = visitSetCondInstWithCastAndCast(I))
3978 return R;
Chris Lattner68708052003-11-03 05:17:03 +00003979 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00003980
3981 if (I.getOpcode() == Instruction::SetNE ||
3982 I.getOpcode() == Instruction::SetEQ) {
3983 Value *A, *B;
3984 if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
3985 (A == Op1 || B == Op1)) {
3986 // (A^B) == A -> B == 0
3987 Value *OtherVal = A == Op1 ? B : A;
3988 return BinaryOperator::create(I.getOpcode(), OtherVal,
3989 Constant::getNullValue(A->getType()));
3990 } else if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
3991 (A == Op0 || B == Op0)) {
3992 // A == (A^B) -> B == 0
3993 Value *OtherVal = A == Op0 ? B : A;
3994 return BinaryOperator::create(I.getOpcode(), OtherVal,
3995 Constant::getNullValue(A->getType()));
3996 } else if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
3997 // (A-B) == A -> B == 0
3998 return BinaryOperator::create(I.getOpcode(), B,
3999 Constant::getNullValue(B->getType()));
4000 } else if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
4001 // A == (A-B) -> B == 0
4002 return BinaryOperator::create(I.getOpcode(), B,
4003 Constant::getNullValue(B->getType()));
4004 }
4005 }
Chris Lattner7e708292002-06-25 16:13:24 +00004006 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004007}
4008
Chris Lattner484d3cf2005-04-24 06:59:08 +00004009// visitSetCondInstWithCastAndCast - Handle setcond (cast x to y), (cast/cst).
4010// We only handle extending casts so far.
4011//
4012Instruction *InstCombiner::visitSetCondInstWithCastAndCast(SetCondInst &SCI) {
4013 Value *LHSCIOp = cast<CastInst>(SCI.getOperand(0))->getOperand(0);
4014 const Type *SrcTy = LHSCIOp->getType();
4015 const Type *DestTy = SCI.getOperand(0)->getType();
4016 Value *RHSCIOp;
4017
4018 if (!DestTy->isIntegral() || !SrcTy->isIntegral())
Chris Lattnerb352fa52005-01-17 03:20:02 +00004019 return 0;
4020
Chris Lattner484d3cf2005-04-24 06:59:08 +00004021 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
4022 unsigned DestBits = DestTy->getPrimitiveSizeInBits();
4023 if (SrcBits >= DestBits) return 0; // Only handle extending cast.
4024
4025 // Is this a sign or zero extension?
4026 bool isSignSrc = SrcTy->isSigned();
4027 bool isSignDest = DestTy->isSigned();
4028
4029 if (CastInst *CI = dyn_cast<CastInst>(SCI.getOperand(1))) {
4030 // Not an extension from the same type?
4031 RHSCIOp = CI->getOperand(0);
4032 if (RHSCIOp->getType() != LHSCIOp->getType()) return 0;
4033 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(SCI.getOperand(1))) {
4034 // Compute the constant that would happen if we truncated to SrcTy then
4035 // reextended to DestTy.
4036 Constant *Res = ConstantExpr::getCast(CI, SrcTy);
4037
4038 if (ConstantExpr::getCast(Res, DestTy) == CI) {
4039 RHSCIOp = Res;
4040 } else {
4041 // If the value cannot be represented in the shorter type, we cannot emit
4042 // a simple comparison.
4043 if (SCI.getOpcode() == Instruction::SetEQ)
4044 return ReplaceInstUsesWith(SCI, ConstantBool::False);
4045 if (SCI.getOpcode() == Instruction::SetNE)
4046 return ReplaceInstUsesWith(SCI, ConstantBool::True);
4047
Chris Lattner484d3cf2005-04-24 06:59:08 +00004048 // Evaluate the comparison for LT.
4049 Value *Result;
4050 if (DestTy->isSigned()) {
4051 // We're performing a signed comparison.
4052 if (isSignSrc) {
4053 // Signed extend and signed comparison.
4054 if (cast<ConstantSInt>(CI)->getValue() < 0) // X < (small) --> false
4055 Result = ConstantBool::False;
4056 else
4057 Result = ConstantBool::True; // X < (large) --> true
4058 } else {
4059 // Unsigned extend and signed comparison.
4060 if (cast<ConstantSInt>(CI)->getValue() < 0)
4061 Result = ConstantBool::False;
4062 else
4063 Result = ConstantBool::True;
4064 }
4065 } else {
4066 // We're performing an unsigned comparison.
4067 if (!isSignSrc) {
4068 // Unsigned extend & compare -> always true.
4069 Result = ConstantBool::True;
4070 } else {
4071 // We're performing an unsigned comp with a sign extended value.
4072 // This is true if the input is >= 0. [aka >s -1]
4073 Constant *NegOne = ConstantIntegral::getAllOnesValue(SrcTy);
4074 Result = InsertNewInstBefore(BinaryOperator::createSetGT(LHSCIOp,
4075 NegOne, SCI.getName()), SCI);
4076 }
Reid Spencer6731d5c2004-11-28 21:31:15 +00004077 }
Chris Lattnerb352fa52005-01-17 03:20:02 +00004078
Jeff Cohen00b168892005-07-27 06:12:32 +00004079 // Finally, return the value computed.
Chris Lattner484d3cf2005-04-24 06:59:08 +00004080 if (SCI.getOpcode() == Instruction::SetLT) {
4081 return ReplaceInstUsesWith(SCI, Result);
4082 } else {
4083 assert(SCI.getOpcode()==Instruction::SetGT &&"SetCC should be folded!");
4084 if (Constant *CI = dyn_cast<Constant>(Result))
4085 return ReplaceInstUsesWith(SCI, ConstantExpr::getNot(CI));
4086 else
4087 return BinaryOperator::createNot(Result);
4088 }
Chris Lattnerb352fa52005-01-17 03:20:02 +00004089 }
Chris Lattner484d3cf2005-04-24 06:59:08 +00004090 } else {
4091 return 0;
Reid Spencer6731d5c2004-11-28 21:31:15 +00004092 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00004093
Chris Lattner8d7089e2005-06-16 03:00:08 +00004094 // Okay, just insert a compare of the reduced operands now!
Chris Lattner484d3cf2005-04-24 06:59:08 +00004095 return BinaryOperator::create(SCI.getOpcode(), LHSCIOp, RHSCIOp);
4096}
Chris Lattner3f5b8772002-05-06 16:14:14 +00004097
Chris Lattnerea340052003-03-10 19:16:08 +00004098Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00004099 assert(I.getOperand(1)->getType() == Type::UByteTy);
4100 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdf17af12003-08-12 21:53:41 +00004101 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004102
4103 // shl X, 0 == X and shr X, 0 == X
4104 // shl 0, X == 0 and shr 0, X == 0
4105 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
Chris Lattner233f7dc2002-08-12 21:17:25 +00004106 Op0 == Constant::getNullValue(Op0->getType()))
4107 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00004108
Chris Lattnere87597f2004-10-16 18:11:37 +00004109 if (isa<UndefValue>(Op0)) { // undef >>s X -> undef
4110 if (!isLeftShift && I.getType()->isSigned())
Chris Lattner79a564c2004-10-16 23:28:04 +00004111 return ReplaceInstUsesWith(I, Op0);
Chris Lattnere87597f2004-10-16 18:11:37 +00004112 else // undef << X -> 0 AND undef >>u X -> 0
4113 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4114 }
4115 if (isa<UndefValue>(Op1)) {
Chris Lattnerf9944f12005-07-20 18:49:28 +00004116 if (isLeftShift || I.getType()->isUnsigned())// X << undef, X >>u undef -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00004117 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4118 else
4119 return ReplaceInstUsesWith(I, Op0); // X >>s undef -> X
4120 }
4121
Chris Lattnerdf17af12003-08-12 21:53:41 +00004122 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
4123 if (!isLeftShift)
4124 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
4125 if (CSI->isAllOnesValue())
4126 return ReplaceInstUsesWith(I, CSI);
4127
Chris Lattner2eefe512004-04-09 19:05:30 +00004128 // Try to fold constant and into select arguments.
4129 if (isa<Constant>(Op0))
4130 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004131 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004132 return R;
4133
Chris Lattner120347e2005-05-08 17:34:56 +00004134 // See if we can turn a signed shr into an unsigned shr.
4135 if (!isLeftShift && I.getType()->isSigned()) {
Chris Lattner3bedbd92006-02-07 07:27:52 +00004136 if (MaskedValueIsZero(Op0,
4137 1ULL << (I.getType()->getPrimitiveSizeInBits()-1))) {
Chris Lattner120347e2005-05-08 17:34:56 +00004138 Value *V = InsertCastBefore(Op0, I.getType()->getUnsignedVersion(), I);
4139 V = InsertNewInstBefore(new ShiftInst(Instruction::Shr, V, Op1,
4140 I.getName()), I);
4141 return new CastInst(V, I.getType());
4142 }
4143 }
Jeff Cohen00b168892005-07-27 06:12:32 +00004144
Chris Lattner4d5542c2006-01-06 07:12:35 +00004145 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1))
4146 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
4147 return Res;
4148 return 0;
4149}
4150
4151Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantUInt *Op1,
4152 ShiftInst &I) {
4153 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner830ed032006-01-06 07:22:22 +00004154 bool isSignedShift = Op0->getType()->isSigned();
4155 bool isUnsignedShift = !isSignedShift;
Chris Lattner4d5542c2006-01-06 07:12:35 +00004156
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00004157 // See if we can simplify any instructions used by the instruction whose sole
4158 // purpose is to compute bits we don't care about.
4159 uint64_t KnownZero, KnownOne;
4160 if (SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
4161 KnownZero, KnownOne))
4162 return &I;
4163
Chris Lattner4d5542c2006-01-06 07:12:35 +00004164 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
4165 // of a signed value.
4166 //
4167 unsigned TypeBits = Op0->getType()->getPrimitiveSizeInBits();
4168 if (Op1->getValue() >= TypeBits) {
Chris Lattner830ed032006-01-06 07:22:22 +00004169 if (isUnsignedShift || isLeftShift)
Chris Lattner4d5542c2006-01-06 07:12:35 +00004170 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
4171 else {
4172 I.setOperand(1, ConstantUInt::get(Type::UByteTy, TypeBits-1));
4173 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00004174 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00004175 }
4176
4177 // ((X*C1) << C2) == (X * (C1 << C2))
4178 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
4179 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
4180 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
4181 return BinaryOperator::createMul(BO->getOperand(0),
4182 ConstantExpr::getShl(BOOp, Op1));
4183
4184 // Try to fold constant and into select arguments.
4185 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4186 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4187 return R;
4188 if (isa<PHINode>(Op0))
4189 if (Instruction *NV = FoldOpIntoPhi(I))
4190 return NV;
4191
4192 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00004193 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
4194 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
4195 Value *V1, *V2;
4196 ConstantInt *CC;
4197 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00004198 default: break;
4199 case Instruction::Add:
4200 case Instruction::And:
4201 case Instruction::Or:
4202 case Instruction::Xor:
4203 // These operators commute.
4204 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00004205 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
4206 match(Op0BO->getOperand(1),
Chris Lattner4d5542c2006-01-06 07:12:35 +00004207 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Chris Lattner150f12a2005-09-18 06:30:59 +00004208 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner4d5542c2006-01-06 07:12:35 +00004209 Op0BO->getOperand(0), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00004210 Op0BO->getName());
4211 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00004212 Instruction *X =
4213 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
4214 Op0BO->getOperand(1)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00004215 InsertNewInstBefore(X, I); // (X + (Y << C))
4216 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner4d5542c2006-01-06 07:12:35 +00004217 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner150f12a2005-09-18 06:30:59 +00004218 return BinaryOperator::createAnd(X, C2);
4219 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00004220
Chris Lattner150f12a2005-09-18 06:30:59 +00004221 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
4222 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
4223 match(Op0BO->getOperand(1),
4224 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner4d5542c2006-01-06 07:12:35 +00004225 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00004226 cast<BinaryOperator>(Op0BO->getOperand(1))->getOperand(0)->hasOneUse()) {
Chris Lattner150f12a2005-09-18 06:30:59 +00004227 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner4d5542c2006-01-06 07:12:35 +00004228 Op0BO->getOperand(0), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00004229 Op0BO->getName());
4230 InsertNewInstBefore(YS, I); // (Y << C)
4231 Instruction *XM =
Chris Lattner4d5542c2006-01-06 07:12:35 +00004232 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00004233 V1->getName()+".mask");
4234 InsertNewInstBefore(XM, I); // X & (CC << C)
4235
4236 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
4237 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00004238
Chris Lattner150f12a2005-09-18 06:30:59 +00004239 // FALL THROUGH.
Chris Lattner11021cb2005-09-18 05:12:10 +00004240 case Instruction::Sub:
4241 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00004242 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
4243 match(Op0BO->getOperand(0),
Chris Lattner4d5542c2006-01-06 07:12:35 +00004244 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Chris Lattner150f12a2005-09-18 06:30:59 +00004245 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner4d5542c2006-01-06 07:12:35 +00004246 Op0BO->getOperand(1), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00004247 Op0BO->getName());
4248 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00004249 Instruction *X =
4250 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
4251 Op0BO->getOperand(0)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00004252 InsertNewInstBefore(X, I); // (X + (Y << C))
4253 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner4d5542c2006-01-06 07:12:35 +00004254 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner150f12a2005-09-18 06:30:59 +00004255 return BinaryOperator::createAnd(X, C2);
4256 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00004257
Chris Lattner150f12a2005-09-18 06:30:59 +00004258 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
4259 match(Op0BO->getOperand(0),
4260 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner4d5542c2006-01-06 07:12:35 +00004261 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00004262 cast<BinaryOperator>(Op0BO->getOperand(0))
4263 ->getOperand(0)->hasOneUse()) {
Chris Lattner150f12a2005-09-18 06:30:59 +00004264 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner4d5542c2006-01-06 07:12:35 +00004265 Op0BO->getOperand(1), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00004266 Op0BO->getName());
4267 InsertNewInstBefore(YS, I); // (Y << C)
4268 Instruction *XM =
Chris Lattner4d5542c2006-01-06 07:12:35 +00004269 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00004270 V1->getName()+".mask");
4271 InsertNewInstBefore(XM, I); // X & (CC << C)
4272
4273 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
4274 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00004275
Chris Lattner11021cb2005-09-18 05:12:10 +00004276 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00004277 }
4278
4279
4280 // If the operand is an bitwise operator with a constant RHS, and the
4281 // shift is the only use, we can pull it out of the shift.
4282 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
4283 bool isValid = true; // Valid only for And, Or, Xor
4284 bool highBitSet = false; // Transform if high bit of constant set?
4285
4286 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00004287 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00004288 case Instruction::Add:
4289 isValid = isLeftShift;
4290 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00004291 case Instruction::Or:
4292 case Instruction::Xor:
4293 highBitSet = false;
4294 break;
4295 case Instruction::And:
4296 highBitSet = true;
4297 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00004298 }
4299
4300 // If this is a signed shift right, and the high bit is modified
4301 // by the logical operation, do not perform the transformation.
4302 // The highBitSet boolean indicates the value of the high bit of
4303 // the constant which would cause it to be modified for this
4304 // operation.
4305 //
Chris Lattner830ed032006-01-06 07:22:22 +00004306 if (isValid && !isLeftShift && isSignedShift) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00004307 uint64_t Val = Op0C->getRawValue();
4308 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
4309 }
4310
4311 if (isValid) {
4312 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
4313
4314 Instruction *NewShift =
4315 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), Op1,
4316 Op0BO->getName());
4317 Op0BO->setName("");
4318 InsertNewInstBefore(NewShift, I);
4319
4320 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
4321 NewRHS);
4322 }
4323 }
4324 }
4325 }
4326
Chris Lattnerad0124c2006-01-06 07:52:12 +00004327 // Find out if this is a shift of a shift by a constant.
4328 ShiftInst *ShiftOp = 0;
Chris Lattner4d5542c2006-01-06 07:12:35 +00004329 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
Chris Lattnerad0124c2006-01-06 07:52:12 +00004330 ShiftOp = Op0SI;
4331 else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4332 // If this is a noop-integer case of a shift instruction, use the shift.
4333 if (CI->getOperand(0)->getType()->isInteger() &&
4334 CI->getOperand(0)->getType()->getPrimitiveSizeInBits() ==
4335 CI->getType()->getPrimitiveSizeInBits() &&
4336 isa<ShiftInst>(CI->getOperand(0))) {
4337 ShiftOp = cast<ShiftInst>(CI->getOperand(0));
4338 }
4339 }
4340
4341 if (ShiftOp && isa<ConstantUInt>(ShiftOp->getOperand(1))) {
4342 // Find the operands and properties of the input shift. Note that the
4343 // signedness of the input shift may differ from the current shift if there
4344 // is a noop cast between the two.
4345 bool isShiftOfLeftShift = ShiftOp->getOpcode() == Instruction::Shl;
4346 bool isShiftOfSignedShift = ShiftOp->getType()->isSigned();
Chris Lattnere8d56c52006-01-07 01:32:28 +00004347 bool isShiftOfUnsignedShift = !isShiftOfSignedShift;
Chris Lattnerad0124c2006-01-06 07:52:12 +00004348
4349 ConstantUInt *ShiftAmt1C = cast<ConstantUInt>(ShiftOp->getOperand(1));
4350
4351 unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getValue();
4352 unsigned ShiftAmt2 = (unsigned)Op1->getValue();
4353
4354 // Check for (A << c1) << c2 and (A >> c1) >> c2.
4355 if (isLeftShift == isShiftOfLeftShift) {
4356 // Do not fold these shifts if the first one is signed and the second one
4357 // is unsigned and this is a right shift. Further, don't do any folding
4358 // on them.
4359 if (isShiftOfSignedShift && isUnsignedShift && !isLeftShift)
4360 return 0;
Chris Lattner4d5542c2006-01-06 07:12:35 +00004361
Chris Lattnerad0124c2006-01-06 07:52:12 +00004362 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
4363 if (Amt > Op0->getType()->getPrimitiveSizeInBits())
4364 Amt = Op0->getType()->getPrimitiveSizeInBits();
Chris Lattner4d5542c2006-01-06 07:12:35 +00004365
Chris Lattnerad0124c2006-01-06 07:52:12 +00004366 Value *Op = ShiftOp->getOperand(0);
4367 if (isShiftOfSignedShift != isSignedShift)
4368 Op = InsertNewInstBefore(new CastInst(Op, I.getType(), "tmp"), I);
4369 return new ShiftInst(I.getOpcode(), Op,
4370 ConstantUInt::get(Type::UByteTy, Amt));
4371 }
4372
4373 // Check for (A << c1) >> c2 or (A >> c1) << c2. If we are dealing with
4374 // signed types, we can only support the (A >> c1) << c2 configuration,
4375 // because it can not turn an arbitrary bit of A into a sign bit.
4376 if (isUnsignedShift || isLeftShift) {
4377 // Calculate bitmask for what gets shifted off the edge.
4378 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
4379 if (isLeftShift)
4380 C = ConstantExpr::getShl(C, ShiftAmt1C);
4381 else
Chris Lattnere8d56c52006-01-07 01:32:28 +00004382 C = ConstantExpr::getUShr(C, ShiftAmt1C);
Chris Lattnerad0124c2006-01-06 07:52:12 +00004383
4384 Value *Op = ShiftOp->getOperand(0);
4385 if (isShiftOfSignedShift != isSignedShift)
4386 Op = InsertNewInstBefore(new CastInst(Op, I.getType(),Op->getName()),I);
4387
4388 Instruction *Mask =
4389 BinaryOperator::createAnd(Op, C, Op->getName()+".mask");
4390 InsertNewInstBefore(Mask, I);
4391
4392 // Figure out what flavor of shift we should use...
Chris Lattnere8d56c52006-01-07 01:32:28 +00004393 if (ShiftAmt1 == ShiftAmt2) {
Chris Lattnerad0124c2006-01-06 07:52:12 +00004394 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
Chris Lattnere8d56c52006-01-07 01:32:28 +00004395 } else if (ShiftAmt1 < ShiftAmt2) {
Chris Lattnerad0124c2006-01-06 07:52:12 +00004396 return new ShiftInst(I.getOpcode(), Mask,
4397 ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
Chris Lattnere8d56c52006-01-07 01:32:28 +00004398 } else if (isShiftOfUnsignedShift || isShiftOfLeftShift) {
4399 if (isShiftOfUnsignedShift && !isShiftOfLeftShift && isSignedShift) {
4400 // Make sure to emit an unsigned shift right, not a signed one.
4401 Mask = InsertNewInstBefore(new CastInst(Mask,
4402 Mask->getType()->getUnsignedVersion(),
4403 Op->getName()), I);
4404 Mask = new ShiftInst(Instruction::Shr, Mask,
Chris Lattnerad0124c2006-01-06 07:52:12 +00004405 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
Chris Lattnere8d56c52006-01-07 01:32:28 +00004406 InsertNewInstBefore(Mask, I);
4407 return new CastInst(Mask, I.getType());
4408 } else {
4409 return new ShiftInst(ShiftOp->getOpcode(), Mask,
4410 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
4411 }
4412 } else {
4413 // (X >>s C1) << C2 where C1 > C2 === (X >>s (C1-C2)) & mask
4414 Op = InsertNewInstBefore(new CastInst(Mask,
4415 I.getType()->getSignedVersion(),
4416 Mask->getName()), I);
4417 Instruction *Shift =
4418 new ShiftInst(ShiftOp->getOpcode(), Op,
4419 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
4420 InsertNewInstBefore(Shift, I);
4421
4422 C = ConstantIntegral::getAllOnesValue(Shift->getType());
4423 C = ConstantExpr::getShl(C, Op1);
4424 Mask = BinaryOperator::createAnd(Shift, C, Op->getName()+".mask");
4425 InsertNewInstBefore(Mask, I);
4426 return new CastInst(Mask, I.getType());
Chris Lattnerad0124c2006-01-06 07:52:12 +00004427 }
4428 } else {
Chris Lattnere8d56c52006-01-07 01:32:28 +00004429 // We can handle signed (X << C1) >>s C2 if it's a sign extend. In
Chris Lattnerad0124c2006-01-06 07:52:12 +00004430 // this case, C1 == C2 and C1 is 8, 16, or 32.
4431 if (ShiftAmt1 == ShiftAmt2) {
4432 const Type *SExtType = 0;
4433 switch (ShiftAmt1) {
4434 case 8 : SExtType = Type::SByteTy; break;
4435 case 16: SExtType = Type::ShortTy; break;
4436 case 32: SExtType = Type::IntTy; break;
4437 }
4438
4439 if (SExtType) {
4440 Instruction *NewTrunc = new CastInst(ShiftOp->getOperand(0),
4441 SExtType, "sext");
4442 InsertNewInstBefore(NewTrunc, I);
4443 return new CastInst(NewTrunc, I.getType());
Chris Lattnerdf17af12003-08-12 21:53:41 +00004444 }
Chris Lattner11021cb2005-09-18 05:12:10 +00004445 }
Chris Lattner6e7ba452005-01-01 16:22:27 +00004446 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00004447 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00004448 return 0;
4449}
4450
Chris Lattnerbee7e762004-07-20 00:59:32 +00004451enum CastType {
4452 Noop = 0,
4453 Truncate = 1,
4454 Signext = 2,
4455 Zeroext = 3
4456};
4457
4458/// getCastType - In the future, we will split the cast instruction into these
4459/// various types. Until then, we have to do the analysis here.
4460static CastType getCastType(const Type *Src, const Type *Dest) {
4461 assert(Src->isIntegral() && Dest->isIntegral() &&
4462 "Only works on integral types!");
Chris Lattner484d3cf2005-04-24 06:59:08 +00004463 unsigned SrcSize = Src->getPrimitiveSizeInBits();
4464 unsigned DestSize = Dest->getPrimitiveSizeInBits();
Chris Lattnerbee7e762004-07-20 00:59:32 +00004465
4466 if (SrcSize == DestSize) return Noop;
4467 if (SrcSize > DestSize) return Truncate;
4468 if (Src->isSigned()) return Signext;
4469 return Zeroext;
4470}
4471
Chris Lattner3f5b8772002-05-06 16:14:14 +00004472
Chris Lattnera1be5662002-05-02 17:06:02 +00004473// isEliminableCastOfCast - Return true if it is valid to eliminate the CI
4474// instruction.
4475//
Chris Lattnerbc528ef2006-01-19 07:40:22 +00004476static bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
4477 const Type *DstTy, TargetData *TD) {
Chris Lattnera1be5662002-05-02 17:06:02 +00004478
Chris Lattner8fd217c2002-08-02 20:00:25 +00004479 // It is legal to eliminate the instruction if casting A->B->A if the sizes
Misha Brukmanfd939082005-04-21 23:48:37 +00004480 // are identical and the bits don't get reinterpreted (for example
Chris Lattner5eb91942004-07-21 19:50:44 +00004481 // int->float->int would not be allowed).
Misha Brukmanf117cc92003-05-20 18:45:36 +00004482 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
Chris Lattner8fd217c2002-08-02 20:00:25 +00004483 return true;
Chris Lattnera1be5662002-05-02 17:06:02 +00004484
Chris Lattnere8a7e592004-07-21 04:27:24 +00004485 // If we are casting between pointer and integer types, treat pointers as
4486 // integers of the appropriate size for the code below.
4487 if (isa<PointerType>(SrcTy)) SrcTy = TD->getIntPtrType();
4488 if (isa<PointerType>(MidTy)) MidTy = TD->getIntPtrType();
4489 if (isa<PointerType>(DstTy)) DstTy = TD->getIntPtrType();
Chris Lattner59a20772004-07-20 05:21:00 +00004490
Chris Lattnera1be5662002-05-02 17:06:02 +00004491 // Allow free casting and conversion of sizes as long as the sign doesn't
4492 // change...
Chris Lattner0c4e8862002-09-03 01:08:28 +00004493 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
Chris Lattnerbee7e762004-07-20 00:59:32 +00004494 CastType FirstCast = getCastType(SrcTy, MidTy);
4495 CastType SecondCast = getCastType(MidTy, DstTy);
Chris Lattner8fd217c2002-08-02 20:00:25 +00004496
Chris Lattnerbee7e762004-07-20 00:59:32 +00004497 // Capture the effect of these two casts. If the result is a legal cast,
4498 // the CastType is stored here, otherwise a special code is used.
4499 static const unsigned CastResult[] = {
4500 // First cast is noop
4501 0, 1, 2, 3,
4502 // First cast is a truncate
4503 1, 1, 4, 4, // trunc->extend is not safe to eliminate
4504 // First cast is a sign ext
Chris Lattner5eb91942004-07-21 19:50:44 +00004505 2, 5, 2, 4, // signext->zeroext never ok
Chris Lattnerbee7e762004-07-20 00:59:32 +00004506 // First cast is a zero ext
Chris Lattner5eb91942004-07-21 19:50:44 +00004507 3, 5, 3, 3,
Chris Lattnerbee7e762004-07-20 00:59:32 +00004508 };
4509
4510 unsigned Result = CastResult[FirstCast*4+SecondCast];
4511 switch (Result) {
4512 default: assert(0 && "Illegal table value!");
4513 case 0:
4514 case 1:
4515 case 2:
4516 case 3:
4517 // FIXME: in the future, when LLVM has explicit sign/zeroextends and
4518 // truncates, we could eliminate more casts.
4519 return (unsigned)getCastType(SrcTy, DstTy) == Result;
4520 case 4:
4521 return false; // Not possible to eliminate this here.
4522 case 5:
Chris Lattner5eb91942004-07-21 19:50:44 +00004523 // Sign or zero extend followed by truncate is always ok if the result
4524 // is a truncate or noop.
4525 CastType ResultCast = getCastType(SrcTy, DstTy);
4526 if (ResultCast == Noop || ResultCast == Truncate)
4527 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +00004528 // Otherwise we are still growing the value, we are only safe if the
Chris Lattner5eb91942004-07-21 19:50:44 +00004529 // result will match the sign/zeroextendness of the result.
4530 return ResultCast == FirstCast;
Chris Lattner3ecce662002-08-15 16:15:25 +00004531 }
Chris Lattner8fd217c2002-08-02 20:00:25 +00004532 }
Chris Lattnerbc528ef2006-01-19 07:40:22 +00004533
4534 // If this is a cast from 'float -> double -> integer', cast from
4535 // 'float -> integer' directly, as the value isn't changed by the
4536 // float->double conversion.
4537 if (SrcTy->isFloatingPoint() && MidTy->isFloatingPoint() &&
4538 DstTy->isIntegral() &&
4539 SrcTy->getPrimitiveSize() < MidTy->getPrimitiveSize())
4540 return true;
4541
Chris Lattner4132afb2006-04-02 05:43:13 +00004542 // Packed type conversions don't modify bits.
4543 if (isa<PackedType>(SrcTy) && isa<PackedType>(MidTy) &&isa<PackedType>(DstTy))
4544 return true;
4545
Chris Lattnera1be5662002-05-02 17:06:02 +00004546 return false;
4547}
4548
Chris Lattner59a20772004-07-20 05:21:00 +00004549static bool ValueRequiresCast(const Value *V, const Type *Ty, TargetData *TD) {
Chris Lattner24c8e382003-07-24 17:35:25 +00004550 if (V->getType() == Ty || isa<Constant>(V)) return false;
4551 if (const CastInst *CI = dyn_cast<CastInst>(V))
Chris Lattner59a20772004-07-20 05:21:00 +00004552 if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty,
4553 TD))
Chris Lattner24c8e382003-07-24 17:35:25 +00004554 return false;
4555 return true;
4556}
4557
4558/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
4559/// InsertBefore instruction. This is specialized a bit to avoid inserting
4560/// casts that are known to not do anything...
4561///
4562Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
4563 Instruction *InsertBefore) {
4564 if (V->getType() == DestTy) return V;
4565 if (Constant *C = dyn_cast<Constant>(V))
4566 return ConstantExpr::getCast(C, DestTy);
4567
4568 CastInst *CI = new CastInst(V, DestTy, V->getName());
4569 InsertNewInstBefore(CI, *InsertBefore);
4570 return CI;
4571}
Chris Lattnera1be5662002-05-02 17:06:02 +00004572
Chris Lattnercfd65102005-10-29 04:36:15 +00004573/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
4574/// expression. If so, decompose it, returning some value X, such that Val is
4575/// X*Scale+Offset.
4576///
4577static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
4578 unsigned &Offset) {
4579 assert(Val->getType() == Type::UIntTy && "Unexpected allocation size type!");
4580 if (ConstantUInt *CI = dyn_cast<ConstantUInt>(Val)) {
4581 Offset = CI->getValue();
4582 Scale = 1;
4583 return ConstantUInt::get(Type::UIntTy, 0);
4584 } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
4585 if (I->getNumOperands() == 2) {
4586 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(I->getOperand(1))) {
4587 if (I->getOpcode() == Instruction::Shl) {
4588 // This is a value scaled by '1 << the shift amt'.
4589 Scale = 1U << CUI->getValue();
4590 Offset = 0;
4591 return I->getOperand(0);
4592 } else if (I->getOpcode() == Instruction::Mul) {
4593 // This value is scaled by 'CUI'.
4594 Scale = CUI->getValue();
4595 Offset = 0;
4596 return I->getOperand(0);
4597 } else if (I->getOpcode() == Instruction::Add) {
4598 // We have X+C. Check to see if we really have (X*C2)+C1, where C1 is
4599 // divisible by C2.
4600 unsigned SubScale;
4601 Value *SubVal = DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
4602 Offset);
4603 Offset += CUI->getValue();
4604 if (SubScale > 1 && (Offset % SubScale == 0)) {
4605 Scale = SubScale;
4606 return SubVal;
4607 }
4608 }
4609 }
4610 }
4611 }
4612
4613 // Otherwise, we can't look past this.
4614 Scale = 1;
4615 Offset = 0;
4616 return Val;
4617}
4618
4619
Chris Lattnerb3f83972005-10-24 06:03:58 +00004620/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
4621/// try to eliminate the cast by moving the type information into the alloc.
4622Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
4623 AllocationInst &AI) {
4624 const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
Chris Lattner0ddac2a2005-10-27 05:53:56 +00004625 if (!PTy) return 0; // Not casting the allocation to a pointer type.
Chris Lattnerb3f83972005-10-24 06:03:58 +00004626
Chris Lattnerb53c2382005-10-24 06:22:12 +00004627 // Remove any uses of AI that are dead.
4628 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
4629 std::vector<Instruction*> DeadUsers;
4630 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
4631 Instruction *User = cast<Instruction>(*UI++);
4632 if (isInstructionTriviallyDead(User)) {
4633 while (UI != E && *UI == User)
4634 ++UI; // If this instruction uses AI more than once, don't break UI.
4635
4636 // Add operands to the worklist.
4637 AddUsesToWorkList(*User);
4638 ++NumDeadInst;
4639 DEBUG(std::cerr << "IC: DCE: " << *User);
4640
4641 User->eraseFromParent();
4642 removeFromWorkList(User);
4643 }
4644 }
4645
Chris Lattnerb3f83972005-10-24 06:03:58 +00004646 // Get the type really allocated and the type casted to.
4647 const Type *AllocElTy = AI.getAllocatedType();
4648 const Type *CastElTy = PTy->getElementType();
4649 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00004650
4651 unsigned AllocElTyAlign = TD->getTypeSize(AllocElTy);
4652 unsigned CastElTyAlign = TD->getTypeSize(CastElTy);
4653 if (CastElTyAlign < AllocElTyAlign) return 0;
4654
Chris Lattner39387a52005-10-24 06:35:18 +00004655 // If the allocation has multiple uses, only promote it if we are strictly
4656 // increasing the alignment of the resultant allocation. If we keep it the
4657 // same, we open the door to infinite loops of various kinds.
4658 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
4659
Chris Lattnerb3f83972005-10-24 06:03:58 +00004660 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
4661 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00004662 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00004663
Chris Lattner455fcc82005-10-29 03:19:53 +00004664 // See if we can satisfy the modulus by pulling a scale out of the array
4665 // size argument.
Chris Lattnercfd65102005-10-29 04:36:15 +00004666 unsigned ArraySizeScale, ArrayOffset;
4667 Value *NumElements = // See if the array size is a decomposable linear expr.
4668 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
4669
Chris Lattner455fcc82005-10-29 03:19:53 +00004670 // If we can now satisfy the modulus, by using a non-1 scale, we really can
4671 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00004672 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
4673 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00004674
Chris Lattner455fcc82005-10-29 03:19:53 +00004675 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
4676 Value *Amt = 0;
4677 if (Scale == 1) {
4678 Amt = NumElements;
4679 } else {
4680 Amt = ConstantUInt::get(Type::UIntTy, Scale);
4681 if (ConstantUInt *CI = dyn_cast<ConstantUInt>(NumElements))
4682 Amt = ConstantExpr::getMul(CI, cast<ConstantUInt>(Amt));
4683 else if (Scale != 1) {
4684 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
4685 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattner8142b0a2005-10-27 06:12:00 +00004686 }
Chris Lattner0ddac2a2005-10-27 05:53:56 +00004687 }
4688
Chris Lattnercfd65102005-10-29 04:36:15 +00004689 if (unsigned Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
4690 Value *Off = ConstantUInt::get(Type::UIntTy, Offset);
4691 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
4692 Amt = InsertNewInstBefore(Tmp, AI);
4693 }
4694
Chris Lattnerb3f83972005-10-24 06:03:58 +00004695 std::string Name = AI.getName(); AI.setName("");
4696 AllocationInst *New;
4697 if (isa<MallocInst>(AI))
Nate Begeman14b05292005-11-05 09:21:28 +00004698 New = new MallocInst(CastElTy, Amt, AI.getAlignment(), Name);
Chris Lattnerb3f83972005-10-24 06:03:58 +00004699 else
Nate Begeman14b05292005-11-05 09:21:28 +00004700 New = new AllocaInst(CastElTy, Amt, AI.getAlignment(), Name);
Chris Lattnerb3f83972005-10-24 06:03:58 +00004701 InsertNewInstBefore(New, AI);
Chris Lattner39387a52005-10-24 06:35:18 +00004702
4703 // If the allocation has multiple uses, insert a cast and change all things
4704 // that used it to use the new cast. This will also hack on CI, but it will
4705 // die soon.
4706 if (!AI.hasOneUse()) {
4707 AddUsesToWorkList(AI);
4708 CastInst *NewCast = new CastInst(New, AI.getType(), "tmpcast");
4709 InsertNewInstBefore(NewCast, AI);
4710 AI.replaceAllUsesWith(NewCast);
4711 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00004712 return ReplaceInstUsesWith(CI, New);
4713}
4714
4715
Chris Lattnera1be5662002-05-02 17:06:02 +00004716// CastInst simplification
Chris Lattnerdd841ae2002-04-18 17:39:14 +00004717//
Chris Lattner7e708292002-06-25 16:13:24 +00004718Instruction *InstCombiner::visitCastInst(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00004719 Value *Src = CI.getOperand(0);
4720
Chris Lattnera1be5662002-05-02 17:06:02 +00004721 // If the user is casting a value to the same type, eliminate this cast
4722 // instruction...
Chris Lattner79d35b32003-06-23 21:59:52 +00004723 if (CI.getType() == Src->getType())
4724 return ReplaceInstUsesWith(CI, Src);
Chris Lattnera1be5662002-05-02 17:06:02 +00004725
Chris Lattnere87597f2004-10-16 18:11:37 +00004726 if (isa<UndefValue>(Src)) // cast undef -> undef
4727 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
4728
Chris Lattnera1be5662002-05-02 17:06:02 +00004729 // If casting the result of another cast instruction, try to eliminate this
4730 // one!
4731 //
Chris Lattner6e7ba452005-01-01 16:22:27 +00004732 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
4733 Value *A = CSrc->getOperand(0);
4734 if (isEliminableCastOfCast(A->getType(), CSrc->getType(),
4735 CI.getType(), TD)) {
Chris Lattnera1be5662002-05-02 17:06:02 +00004736 // This instruction now refers directly to the cast's src operand. This
4737 // has a good chance of making CSrc dead.
Chris Lattner7e708292002-06-25 16:13:24 +00004738 CI.setOperand(0, CSrc->getOperand(0));
4739 return &CI;
Chris Lattnera1be5662002-05-02 17:06:02 +00004740 }
4741
Chris Lattner8fd217c2002-08-02 20:00:25 +00004742 // If this is an A->B->A cast, and we are dealing with integral types, try
4743 // to convert this into a logical 'and' instruction.
4744 //
Misha Brukmanfd939082005-04-21 23:48:37 +00004745 if (A->getType()->isInteger() &&
Chris Lattner0c4e8862002-09-03 01:08:28 +00004746 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
Chris Lattner6e7ba452005-01-01 16:22:27 +00004747 CSrc->getType()->isUnsigned() && // B->A cast must zero extend
Chris Lattner484d3cf2005-04-24 06:59:08 +00004748 CSrc->getType()->getPrimitiveSizeInBits() <
4749 CI.getType()->getPrimitiveSizeInBits()&&
4750 A->getType()->getPrimitiveSizeInBits() ==
4751 CI.getType()->getPrimitiveSizeInBits()) {
Chris Lattner8fd217c2002-08-02 20:00:25 +00004752 assert(CSrc->getType() != Type::ULongTy &&
4753 "Cannot have type bigger than ulong!");
Chris Lattner1a074fc2006-02-07 07:00:41 +00004754 uint64_t AndValue = CSrc->getType()->getIntegralTypeMask();
Chris Lattner6e7ba452005-01-01 16:22:27 +00004755 Constant *AndOp = ConstantUInt::get(A->getType()->getUnsignedVersion(),
4756 AndValue);
4757 AndOp = ConstantExpr::getCast(AndOp, A->getType());
4758 Instruction *And = BinaryOperator::createAnd(CSrc->getOperand(0), AndOp);
4759 if (And->getType() != CI.getType()) {
4760 And->setName(CSrc->getName()+".mask");
4761 InsertNewInstBefore(And, CI);
4762 And = new CastInst(And, CI.getType());
4763 }
4764 return And;
Chris Lattner8fd217c2002-08-02 20:00:25 +00004765 }
4766 }
Chris Lattner6dce1a72006-02-07 06:56:34 +00004767
Chris Lattnera710ddc2004-05-25 04:29:21 +00004768 // If this is a cast to bool, turn it into the appropriate setne instruction.
4769 if (CI.getType() == Type::BoolTy)
Chris Lattner48595f12004-06-10 02:07:29 +00004770 return BinaryOperator::createSetNE(CI.getOperand(0),
Chris Lattnera710ddc2004-05-25 04:29:21 +00004771 Constant::getNullValue(CI.getOperand(0)->getType()));
4772
Chris Lattner6dce1a72006-02-07 06:56:34 +00004773 // See if we can simplify any instructions used by the LHS whose sole
4774 // purpose is to compute bits we don't care about.
Chris Lattner255d8912006-02-11 09:31:47 +00004775 if (CI.getType()->isInteger() && CI.getOperand(0)->getType()->isIntegral()) {
4776 uint64_t KnownZero, KnownOne;
4777 if (SimplifyDemandedBits(&CI, CI.getType()->getIntegralTypeMask(),
4778 KnownZero, KnownOne))
4779 return &CI;
4780 }
Chris Lattner6dce1a72006-02-07 06:56:34 +00004781
Chris Lattner797249b2003-06-21 23:12:02 +00004782 // If casting the result of a getelementptr instruction with no offset, turn
4783 // this into a cast of the original pointer!
4784 //
Chris Lattner79d35b32003-06-23 21:59:52 +00004785 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner797249b2003-06-21 23:12:02 +00004786 bool AllZeroOperands = true;
4787 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
4788 if (!isa<Constant>(GEP->getOperand(i)) ||
4789 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
4790 AllZeroOperands = false;
4791 break;
4792 }
4793 if (AllZeroOperands) {
4794 CI.setOperand(0, GEP->getOperand(0));
4795 return &CI;
4796 }
4797 }
4798
Chris Lattnerbc61e662003-11-02 05:57:39 +00004799 // If we are casting a malloc or alloca to a pointer to a type of the same
4800 // size, rewrite the allocation instruction to allocate the "right" type.
4801 //
4802 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattnerb3f83972005-10-24 06:03:58 +00004803 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
4804 return V;
Chris Lattnerbc61e662003-11-02 05:57:39 +00004805
Chris Lattner6e7ba452005-01-01 16:22:27 +00004806 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
4807 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
4808 return NV;
Chris Lattner4e998b22004-09-29 05:07:12 +00004809 if (isa<PHINode>(Src))
4810 if (Instruction *NV = FoldOpIntoPhi(CI))
4811 return NV;
4812
Chris Lattner24c8e382003-07-24 17:35:25 +00004813 // If the source value is an instruction with only this use, we can attempt to
4814 // propagate the cast into the instruction. Also, only handle integral types
4815 // for now.
4816 if (Instruction *SrcI = dyn_cast<Instruction>(Src))
Chris Lattnerfd059242003-10-15 16:48:29 +00004817 if (SrcI->hasOneUse() && Src->getType()->isIntegral() &&
Chris Lattner24c8e382003-07-24 17:35:25 +00004818 CI.getType()->isInteger()) { // Don't mess with casts to bool here
4819 const Type *DestTy = CI.getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00004820 unsigned SrcBitSize = Src->getType()->getPrimitiveSizeInBits();
4821 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
Chris Lattner24c8e382003-07-24 17:35:25 +00004822
4823 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
4824 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
4825
4826 switch (SrcI->getOpcode()) {
4827 case Instruction::Add:
4828 case Instruction::Mul:
4829 case Instruction::And:
4830 case Instruction::Or:
4831 case Instruction::Xor:
4832 // If we are discarding information, or just changing the sign, rewrite.
4833 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
4834 // Don't insert two casts if they cannot be eliminated. We allow two
4835 // casts to be inserted if the sizes are the same. This could only be
4836 // converting signedness, which is a noop.
Chris Lattner59a20772004-07-20 05:21:00 +00004837 if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy,TD) ||
4838 !ValueRequiresCast(Op0, DestTy, TD)) {
Chris Lattner24c8e382003-07-24 17:35:25 +00004839 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
4840 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
4841 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
4842 ->getOpcode(), Op0c, Op1c);
4843 }
4844 }
Chris Lattner7aed7ac2005-05-06 02:07:39 +00004845
4846 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
4847 if (SrcBitSize == 1 && SrcI->getOpcode() == Instruction::Xor &&
4848 Op1 == ConstantBool::True &&
4849 (!Op0->hasOneUse() || !isa<SetCondInst>(Op0))) {
4850 Value *New = InsertOperandCastBefore(Op0, DestTy, &CI);
4851 return BinaryOperator::createXor(New,
4852 ConstantInt::get(CI.getType(), 1));
4853 }
Chris Lattner24c8e382003-07-24 17:35:25 +00004854 break;
4855 case Instruction::Shl:
4856 // Allow changing the sign of the source operand. Do not allow changing
4857 // the size of the shift, UNLESS the shift amount is a constant. We
4858 // mush not change variable sized shifts to a smaller size, because it
4859 // is undefined to shift more bits out than exist in the value.
4860 if (DestBitSize == SrcBitSize ||
4861 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
4862 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
4863 return new ShiftInst(Instruction::Shl, Op0c, Op1);
4864 }
4865 break;
Chris Lattnerd7115b02005-05-06 04:18:52 +00004866 case Instruction::Shr:
4867 // If this is a signed shr, and if all bits shifted in are about to be
4868 // truncated off, turn it into an unsigned shr to allow greater
4869 // simplifications.
4870 if (DestBitSize < SrcBitSize && Src->getType()->isSigned() &&
4871 isa<ConstantInt>(Op1)) {
4872 unsigned ShiftAmt = cast<ConstantUInt>(Op1)->getValue();
4873 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
4874 // Convert to unsigned.
4875 Value *N1 = InsertOperandCastBefore(Op0,
4876 Op0->getType()->getUnsignedVersion(), &CI);
4877 // Insert the new shift, which is now unsigned.
4878 N1 = InsertNewInstBefore(new ShiftInst(Instruction::Shr, N1,
4879 Op1, Src->getName()), CI);
4880 return new CastInst(N1, CI.getType());
4881 }
4882 }
4883 break;
4884
Chris Lattner3e88a4d2006-02-27 02:38:23 +00004885 case Instruction::SetEQ:
Chris Lattner693787a2005-05-04 19:10:26 +00004886 case Instruction::SetNE:
Chris Lattner3e88a4d2006-02-27 02:38:23 +00004887 // We if we are just checking for a seteq of a single bit and casting it
4888 // to an integer. If so, shift the bit to the appropriate place then
4889 // cast to integer to avoid the comparison.
Chris Lattner693787a2005-05-04 19:10:26 +00004890 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner3e88a4d2006-02-27 02:38:23 +00004891 uint64_t Op1CV = Op1C->getZExtValue();
4892 // cast (X == 0) to int --> X^1 iff X has only the low bit set.
4893 // cast (X == 0) to int --> (X>>1)^1 iff X has only the 2nd bit set.
4894 // cast (X == 1) to int --> X iff X has only the low bit set.
4895 // cast (X == 2) to int --> X>>1 iff X has only the 2nd bit set.
4896 // cast (X != 0) to int --> X iff X has only the low bit set.
4897 // cast (X != 0) to int --> X>>1 iff X has only the 2nd bit set.
4898 // cast (X != 1) to int --> X^1 iff X has only the low bit set.
4899 // cast (X != 2) to int --> (X>>1)^1 iff X has only the 2nd bit set.
4900 if (Op1CV == 0 || isPowerOf2_64(Op1CV)) {
4901 // If Op1C some other power of two, convert:
4902 uint64_t KnownZero, KnownOne;
4903 uint64_t TypeMask = Op1->getType()->getIntegralTypeMask();
4904 ComputeMaskedBits(Op0, TypeMask, KnownZero, KnownOne);
4905
4906 if (isPowerOf2_64(KnownZero^TypeMask)) { // Exactly one possible 1?
4907 bool isSetNE = SrcI->getOpcode() == Instruction::SetNE;
4908 if (Op1CV && (Op1CV != (KnownZero^TypeMask))) {
4909 // (X&4) == 2 --> false
4910 // (X&4) != 2 --> true
Chris Lattner06e1e252006-02-28 19:47:20 +00004911 Constant *Res = ConstantBool::get(isSetNE);
4912 Res = ConstantExpr::getCast(Res, CI.getType());
4913 return ReplaceInstUsesWith(CI, Res);
Chris Lattner3e88a4d2006-02-27 02:38:23 +00004914 }
4915
4916 unsigned ShiftAmt = Log2_64(KnownZero^TypeMask);
4917 Value *In = Op0;
4918 if (ShiftAmt) {
Chris Lattnerd1523802005-05-06 01:53:19 +00004919 // Perform an unsigned shr by shiftamt. Convert input to
4920 // unsigned if it is signed.
Chris Lattnerd1523802005-05-06 01:53:19 +00004921 if (In->getType()->isSigned())
4922 In = InsertNewInstBefore(new CastInst(In,
4923 In->getType()->getUnsignedVersion(), In->getName()),CI);
4924 // Insert the shift to put the result in the low bit.
4925 In = InsertNewInstBefore(new ShiftInst(Instruction::Shr, In,
Chris Lattner3e88a4d2006-02-27 02:38:23 +00004926 ConstantInt::get(Type::UByteTy, ShiftAmt),
4927 In->getName()+".lobit"), CI);
Chris Lattnerd1523802005-05-06 01:53:19 +00004928 }
Chris Lattner3e88a4d2006-02-27 02:38:23 +00004929
4930 if ((Op1CV != 0) == isSetNE) { // Toggle the low bit.
4931 Constant *One = ConstantInt::get(In->getType(), 1);
4932 In = BinaryOperator::createXor(In, One, "tmp");
4933 InsertNewInstBefore(cast<Instruction>(In), CI);
Chris Lattnerd1523802005-05-06 01:53:19 +00004934 }
Chris Lattner3e88a4d2006-02-27 02:38:23 +00004935
4936 if (CI.getType() == In->getType())
4937 return ReplaceInstUsesWith(CI, In);
4938 else
4939 return new CastInst(In, CI.getType());
Chris Lattnerd1523802005-05-06 01:53:19 +00004940 }
Chris Lattner693787a2005-05-04 19:10:26 +00004941 }
4942 }
4943 break;
Chris Lattner24c8e382003-07-24 17:35:25 +00004944 }
4945 }
Chris Lattner0ddac2a2005-10-27 05:53:56 +00004946
Chris Lattnerdd841ae2002-04-18 17:39:14 +00004947 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00004948}
4949
Chris Lattnere576b912004-04-09 23:46:01 +00004950/// GetSelectFoldableOperands - We want to turn code that looks like this:
4951/// %C = or %A, %B
4952/// %D = select %cond, %C, %A
4953/// into:
4954/// %C = select %cond, %B, 0
4955/// %D = or %A, %C
4956///
4957/// Assuming that the specified instruction is an operand to the select, return
4958/// a bitmask indicating which operands of this instruction are foldable if they
4959/// equal the other incoming value of the select.
4960///
4961static unsigned GetSelectFoldableOperands(Instruction *I) {
4962 switch (I->getOpcode()) {
4963 case Instruction::Add:
4964 case Instruction::Mul:
4965 case Instruction::And:
4966 case Instruction::Or:
4967 case Instruction::Xor:
4968 return 3; // Can fold through either operand.
4969 case Instruction::Sub: // Can only fold on the amount subtracted.
4970 case Instruction::Shl: // Can only fold on the shift amount.
4971 case Instruction::Shr:
Misha Brukmanfd939082005-04-21 23:48:37 +00004972 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00004973 default:
4974 return 0; // Cannot fold
4975 }
4976}
4977
4978/// GetSelectFoldableConstant - For the same transformation as the previous
4979/// function, return the identity constant that goes into the select.
4980static Constant *GetSelectFoldableConstant(Instruction *I) {
4981 switch (I->getOpcode()) {
4982 default: assert(0 && "This cannot happen!"); abort();
4983 case Instruction::Add:
4984 case Instruction::Sub:
4985 case Instruction::Or:
4986 case Instruction::Xor:
4987 return Constant::getNullValue(I->getType());
4988 case Instruction::Shl:
4989 case Instruction::Shr:
4990 return Constant::getNullValue(Type::UByteTy);
4991 case Instruction::And:
4992 return ConstantInt::getAllOnesValue(I->getType());
4993 case Instruction::Mul:
4994 return ConstantInt::get(I->getType(), 1);
4995 }
4996}
4997
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00004998/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
4999/// have the same opcode and only one use each. Try to simplify this.
5000Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
5001 Instruction *FI) {
5002 if (TI->getNumOperands() == 1) {
5003 // If this is a non-volatile load or a cast from the same type,
5004 // merge.
5005 if (TI->getOpcode() == Instruction::Cast) {
5006 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
5007 return 0;
5008 } else {
5009 return 0; // unknown unary op.
5010 }
Misha Brukmanfd939082005-04-21 23:48:37 +00005011
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00005012 // Fold this by inserting a select from the input values.
5013 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
5014 FI->getOperand(0), SI.getName()+".v");
5015 InsertNewInstBefore(NewSI, SI);
5016 return new CastInst(NewSI, TI->getType());
5017 }
5018
5019 // Only handle binary operators here.
5020 if (!isa<ShiftInst>(TI) && !isa<BinaryOperator>(TI))
5021 return 0;
5022
5023 // Figure out if the operations have any operands in common.
5024 Value *MatchOp, *OtherOpT, *OtherOpF;
5025 bool MatchIsOpZero;
5026 if (TI->getOperand(0) == FI->getOperand(0)) {
5027 MatchOp = TI->getOperand(0);
5028 OtherOpT = TI->getOperand(1);
5029 OtherOpF = FI->getOperand(1);
5030 MatchIsOpZero = true;
5031 } else if (TI->getOperand(1) == FI->getOperand(1)) {
5032 MatchOp = TI->getOperand(1);
5033 OtherOpT = TI->getOperand(0);
5034 OtherOpF = FI->getOperand(0);
5035 MatchIsOpZero = false;
5036 } else if (!TI->isCommutative()) {
5037 return 0;
5038 } else if (TI->getOperand(0) == FI->getOperand(1)) {
5039 MatchOp = TI->getOperand(0);
5040 OtherOpT = TI->getOperand(1);
5041 OtherOpF = FI->getOperand(0);
5042 MatchIsOpZero = true;
5043 } else if (TI->getOperand(1) == FI->getOperand(0)) {
5044 MatchOp = TI->getOperand(1);
5045 OtherOpT = TI->getOperand(0);
5046 OtherOpF = FI->getOperand(1);
5047 MatchIsOpZero = true;
5048 } else {
5049 return 0;
5050 }
5051
5052 // If we reach here, they do have operations in common.
5053 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
5054 OtherOpF, SI.getName()+".v");
5055 InsertNewInstBefore(NewSI, SI);
5056
5057 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
5058 if (MatchIsOpZero)
5059 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
5060 else
5061 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
5062 } else {
5063 if (MatchIsOpZero)
5064 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), MatchOp, NewSI);
5065 else
5066 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), NewSI, MatchOp);
5067 }
5068}
5069
Chris Lattner3d69f462004-03-12 05:52:32 +00005070Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00005071 Value *CondVal = SI.getCondition();
5072 Value *TrueVal = SI.getTrueValue();
5073 Value *FalseVal = SI.getFalseValue();
5074
5075 // select true, X, Y -> X
5076 // select false, X, Y -> Y
5077 if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
Chris Lattner3d69f462004-03-12 05:52:32 +00005078 if (C == ConstantBool::True)
Chris Lattnerc32b30a2004-03-30 19:37:13 +00005079 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner3d69f462004-03-12 05:52:32 +00005080 else {
5081 assert(C == ConstantBool::False);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00005082 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattner3d69f462004-03-12 05:52:32 +00005083 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00005084
5085 // select C, X, X -> X
5086 if (TrueVal == FalseVal)
5087 return ReplaceInstUsesWith(SI, TrueVal);
5088
Chris Lattnere87597f2004-10-16 18:11:37 +00005089 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
5090 return ReplaceInstUsesWith(SI, FalseVal);
5091 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
5092 return ReplaceInstUsesWith(SI, TrueVal);
5093 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
5094 if (isa<Constant>(TrueVal))
5095 return ReplaceInstUsesWith(SI, TrueVal);
5096 else
5097 return ReplaceInstUsesWith(SI, FalseVal);
5098 }
5099
Chris Lattner0c199a72004-04-08 04:43:23 +00005100 if (SI.getType() == Type::BoolTy)
5101 if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
5102 if (C == ConstantBool::True) {
5103 // Change: A = select B, true, C --> A = or B, C
Chris Lattner48595f12004-06-10 02:07:29 +00005104 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00005105 } else {
5106 // Change: A = select B, false, C --> A = and !B, C
5107 Value *NotCond =
5108 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
5109 "not."+CondVal->getName()), SI);
Chris Lattner48595f12004-06-10 02:07:29 +00005110 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00005111 }
5112 } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
5113 if (C == ConstantBool::False) {
5114 // Change: A = select B, C, false --> A = and B, C
Chris Lattner48595f12004-06-10 02:07:29 +00005115 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00005116 } else {
5117 // Change: A = select B, C, true --> A = or !B, C
5118 Value *NotCond =
5119 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
5120 "not."+CondVal->getName()), SI);
Chris Lattner48595f12004-06-10 02:07:29 +00005121 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00005122 }
5123 }
5124
Chris Lattner2eefe512004-04-09 19:05:30 +00005125 // Selecting between two integer constants?
5126 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
5127 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
5128 // select C, 1, 0 -> cast C to int
5129 if (FalseValC->isNullValue() && TrueValC->getRawValue() == 1) {
5130 return new CastInst(CondVal, SI.getType());
5131 } else if (TrueValC->isNullValue() && FalseValC->getRawValue() == 1) {
5132 // select C, 0, 1 -> cast !C to int
5133 Value *NotCond =
5134 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00005135 "not."+CondVal->getName()), SI);
Chris Lattner2eefe512004-04-09 19:05:30 +00005136 return new CastInst(NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00005137 }
Chris Lattner457dd822004-06-09 07:59:58 +00005138
5139 // If one of the constants is zero (we know they can't both be) and we
5140 // have a setcc instruction with zero, and we have an 'and' with the
5141 // non-constant value, eliminate this whole mess. This corresponds to
5142 // cases like this: ((X & 27) ? 27 : 0)
5143 if (TrueValC->isNullValue() || FalseValC->isNullValue())
5144 if (Instruction *IC = dyn_cast<Instruction>(SI.getCondition()))
5145 if ((IC->getOpcode() == Instruction::SetEQ ||
5146 IC->getOpcode() == Instruction::SetNE) &&
5147 isa<ConstantInt>(IC->getOperand(1)) &&
5148 cast<Constant>(IC->getOperand(1))->isNullValue())
5149 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
5150 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00005151 isa<ConstantInt>(ICA->getOperand(1)) &&
5152 (ICA->getOperand(1) == TrueValC ||
5153 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00005154 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
5155 // Okay, now we know that everything is set up, we just don't
5156 // know whether we have a setne or seteq and whether the true or
5157 // false val is the zero.
5158 bool ShouldNotVal = !TrueValC->isNullValue();
5159 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
5160 Value *V = ICA;
5161 if (ShouldNotVal)
5162 V = InsertNewInstBefore(BinaryOperator::create(
5163 Instruction::Xor, V, ICA->getOperand(1)), SI);
5164 return ReplaceInstUsesWith(SI, V);
5165 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00005166 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00005167
5168 // See if we are selecting two values based on a comparison of the two values.
5169 if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
5170 if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
5171 // Transform (X == Y) ? X : Y -> Y
5172 if (SCI->getOpcode() == Instruction::SetEQ)
5173 return ReplaceInstUsesWith(SI, FalseVal);
5174 // Transform (X != Y) ? X : Y -> X
5175 if (SCI->getOpcode() == Instruction::SetNE)
5176 return ReplaceInstUsesWith(SI, TrueVal);
5177 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
5178
5179 } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
5180 // Transform (X == Y) ? Y : X -> X
5181 if (SCI->getOpcode() == Instruction::SetEQ)
Chris Lattnerfbede522004-04-11 01:39:19 +00005182 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattnerd76956d2004-04-10 22:21:27 +00005183 // Transform (X != Y) ? Y : X -> Y
5184 if (SCI->getOpcode() == Instruction::SetNE)
Chris Lattnerfbede522004-04-11 01:39:19 +00005185 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerd76956d2004-04-10 22:21:27 +00005186 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
5187 }
5188 }
Misha Brukmanfd939082005-04-21 23:48:37 +00005189
Chris Lattner87875da2005-01-13 22:52:24 +00005190 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
5191 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
5192 if (TI->hasOneUse() && FI->hasOneUse()) {
5193 bool isInverse = false;
5194 Instruction *AddOp = 0, *SubOp = 0;
5195
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00005196 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
5197 if (TI->getOpcode() == FI->getOpcode())
5198 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
5199 return IV;
5200
5201 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
5202 // even legal for FP.
Chris Lattner87875da2005-01-13 22:52:24 +00005203 if (TI->getOpcode() == Instruction::Sub &&
5204 FI->getOpcode() == Instruction::Add) {
5205 AddOp = FI; SubOp = TI;
5206 } else if (FI->getOpcode() == Instruction::Sub &&
5207 TI->getOpcode() == Instruction::Add) {
5208 AddOp = TI; SubOp = FI;
5209 }
5210
5211 if (AddOp) {
5212 Value *OtherAddOp = 0;
5213 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
5214 OtherAddOp = AddOp->getOperand(1);
5215 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
5216 OtherAddOp = AddOp->getOperand(0);
5217 }
5218
5219 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00005220 // So at this point we know we have (Y -> OtherAddOp):
5221 // select C, (add X, Y), (sub X, Z)
5222 Value *NegVal; // Compute -Z
5223 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
5224 NegVal = ConstantExpr::getNeg(C);
5225 } else {
5226 NegVal = InsertNewInstBefore(
5227 BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00005228 }
Chris Lattner97f37a42006-02-24 18:05:58 +00005229
5230 Value *NewTrueOp = OtherAddOp;
5231 Value *NewFalseOp = NegVal;
5232 if (AddOp != TI)
5233 std::swap(NewTrueOp, NewFalseOp);
5234 Instruction *NewSel =
5235 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
5236
5237 NewSel = InsertNewInstBefore(NewSel, SI);
5238 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00005239 }
5240 }
5241 }
Misha Brukmanfd939082005-04-21 23:48:37 +00005242
Chris Lattnere576b912004-04-09 23:46:01 +00005243 // See if we can fold the select into one of our operands.
5244 if (SI.getType()->isInteger()) {
5245 // See the comment above GetSelectFoldableOperands for a description of the
5246 // transformation we are doing here.
5247 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
5248 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
5249 !isa<Constant>(FalseVal))
5250 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
5251 unsigned OpToFold = 0;
5252 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
5253 OpToFold = 1;
5254 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
5255 OpToFold = 2;
5256 }
5257
5258 if (OpToFold) {
5259 Constant *C = GetSelectFoldableConstant(TVI);
5260 std::string Name = TVI->getName(); TVI->setName("");
5261 Instruction *NewSel =
5262 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
5263 Name);
5264 InsertNewInstBefore(NewSel, SI);
5265 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
5266 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
5267 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
5268 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
5269 else {
5270 assert(0 && "Unknown instruction!!");
5271 }
5272 }
5273 }
Chris Lattnera96879a2004-09-29 17:40:11 +00005274
Chris Lattnere576b912004-04-09 23:46:01 +00005275 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
5276 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
5277 !isa<Constant>(TrueVal))
5278 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
5279 unsigned OpToFold = 0;
5280 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
5281 OpToFold = 1;
5282 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
5283 OpToFold = 2;
5284 }
5285
5286 if (OpToFold) {
5287 Constant *C = GetSelectFoldableConstant(FVI);
5288 std::string Name = FVI->getName(); FVI->setName("");
5289 Instruction *NewSel =
5290 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
5291 Name);
5292 InsertNewInstBefore(NewSel, SI);
5293 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
5294 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
5295 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
5296 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
5297 else {
5298 assert(0 && "Unknown instruction!!");
5299 }
5300 }
5301 }
5302 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00005303
5304 if (BinaryOperator::isNot(CondVal)) {
5305 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
5306 SI.setOperand(1, FalseVal);
5307 SI.setOperand(2, TrueVal);
5308 return &SI;
5309 }
5310
Chris Lattner3d69f462004-03-12 05:52:32 +00005311 return 0;
5312}
5313
Chris Lattner95a959d2006-03-06 20:18:44 +00005314/// GetKnownAlignment - If the specified pointer has an alignment that we can
5315/// determine, return it, otherwise return 0.
5316static unsigned GetKnownAlignment(Value *V, TargetData *TD) {
5317 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
5318 unsigned Align = GV->getAlignment();
5319 if (Align == 0 && TD)
5320 Align = TD->getTypeAlignment(GV->getType()->getElementType());
5321 return Align;
5322 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
5323 unsigned Align = AI->getAlignment();
5324 if (Align == 0 && TD) {
5325 if (isa<AllocaInst>(AI))
5326 Align = TD->getTypeAlignment(AI->getType()->getElementType());
5327 else if (isa<MallocInst>(AI)) {
5328 // Malloc returns maximally aligned memory.
5329 Align = TD->getTypeAlignment(AI->getType()->getElementType());
5330 Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::DoubleTy));
5331 Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::LongTy));
5332 }
5333 }
5334 return Align;
Chris Lattner51c26e92006-03-07 01:28:57 +00005335 } else if (isa<CastInst>(V) ||
5336 (isa<ConstantExpr>(V) &&
5337 cast<ConstantExpr>(V)->getOpcode() == Instruction::Cast)) {
5338 User *CI = cast<User>(V);
Chris Lattner95a959d2006-03-06 20:18:44 +00005339 if (isa<PointerType>(CI->getOperand(0)->getType()))
5340 return GetKnownAlignment(CI->getOperand(0), TD);
5341 return 0;
Chris Lattner51c26e92006-03-07 01:28:57 +00005342 } else if (isa<GetElementPtrInst>(V) ||
5343 (isa<ConstantExpr>(V) &&
5344 cast<ConstantExpr>(V)->getOpcode()==Instruction::GetElementPtr)) {
5345 User *GEPI = cast<User>(V);
Chris Lattner95a959d2006-03-06 20:18:44 +00005346 unsigned BaseAlignment = GetKnownAlignment(GEPI->getOperand(0), TD);
5347 if (BaseAlignment == 0) return 0;
5348
5349 // If all indexes are zero, it is just the alignment of the base pointer.
5350 bool AllZeroOperands = true;
5351 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
5352 if (!isa<Constant>(GEPI->getOperand(i)) ||
5353 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
5354 AllZeroOperands = false;
5355 break;
5356 }
5357 if (AllZeroOperands)
5358 return BaseAlignment;
5359
5360 // Otherwise, if the base alignment is >= the alignment we expect for the
5361 // base pointer type, then we know that the resultant pointer is aligned at
5362 // least as much as its type requires.
5363 if (!TD) return 0;
5364
5365 const Type *BasePtrTy = GEPI->getOperand(0)->getType();
5366 if (TD->getTypeAlignment(cast<PointerType>(BasePtrTy)->getElementType())
Chris Lattner51c26e92006-03-07 01:28:57 +00005367 <= BaseAlignment) {
5368 const Type *GEPTy = GEPI->getType();
5369 return TD->getTypeAlignment(cast<PointerType>(GEPTy)->getElementType());
5370 }
Chris Lattner95a959d2006-03-06 20:18:44 +00005371 return 0;
5372 }
5373 return 0;
5374}
5375
Chris Lattner3d69f462004-03-12 05:52:32 +00005376
Chris Lattner8b0ea312006-01-13 20:11:04 +00005377/// visitCallInst - CallInst simplification. This mostly only handles folding
5378/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
5379/// the heavy lifting.
5380///
Chris Lattner9fe38862003-06-19 17:00:31 +00005381Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattner8b0ea312006-01-13 20:11:04 +00005382 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
5383 if (!II) return visitCallSite(&CI);
5384
Chris Lattner7bcc0e72004-02-28 05:22:00 +00005385 // Intrinsics cannot occur in an invoke, so handle them here instead of in
5386 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00005387 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00005388 bool Changed = false;
5389
5390 // memmove/cpy/set of zero bytes is a noop.
5391 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
5392 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
5393
Chris Lattner35b9e482004-10-12 04:52:52 +00005394 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
5395 if (CI->getRawValue() == 1) {
5396 // Replace the instruction with just byte operations. We would
5397 // transform other cases to loads/stores, but we don't know if
5398 // alignment is sufficient.
5399 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00005400 }
5401
Chris Lattner35b9e482004-10-12 04:52:52 +00005402 // If we have a memmove and the source operation is a constant global,
5403 // then the source and dest pointers can't alias, so we can change this
5404 // into a call to memcpy.
Chris Lattner95a959d2006-03-06 20:18:44 +00005405 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00005406 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
5407 if (GVSrc->isConstant()) {
5408 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner21959392006-03-03 01:34:17 +00005409 const char *Name;
5410 if (CI.getCalledFunction()->getFunctionType()->getParamType(3) ==
5411 Type::UIntTy)
5412 Name = "llvm.memcpy.i32";
5413 else
5414 Name = "llvm.memcpy.i64";
5415 Function *MemCpy = M->getOrInsertFunction(Name,
Chris Lattner35b9e482004-10-12 04:52:52 +00005416 CI.getCalledFunction()->getFunctionType());
5417 CI.setOperand(0, MemCpy);
5418 Changed = true;
5419 }
Chris Lattner95a959d2006-03-06 20:18:44 +00005420 }
Chris Lattner35b9e482004-10-12 04:52:52 +00005421
Chris Lattner95a959d2006-03-06 20:18:44 +00005422 // If we can determine a pointer alignment that is bigger than currently
5423 // set, update the alignment.
5424 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
5425 unsigned Alignment1 = GetKnownAlignment(MI->getOperand(1), TD);
5426 unsigned Alignment2 = GetKnownAlignment(MI->getOperand(2), TD);
5427 unsigned Align = std::min(Alignment1, Alignment2);
5428 if (MI->getAlignment()->getRawValue() < Align) {
5429 MI->setAlignment(ConstantUInt::get(Type::UIntTy, Align));
5430 Changed = true;
5431 }
5432 } else if (isa<MemSetInst>(MI)) {
5433 unsigned Alignment = GetKnownAlignment(MI->getDest(), TD);
5434 if (MI->getAlignment()->getRawValue() < Alignment) {
5435 MI->setAlignment(ConstantUInt::get(Type::UIntTy, Alignment));
5436 Changed = true;
5437 }
5438 }
5439
Chris Lattner8b0ea312006-01-13 20:11:04 +00005440 if (Changed) return II;
Chris Lattnera728ddc2006-01-13 21:28:09 +00005441 } else {
5442 switch (II->getIntrinsicID()) {
5443 default: break;
Chris Lattner82ed58f2006-04-02 05:30:25 +00005444 case Intrinsic::ppc_altivec_lvx:
5445 case Intrinsic::ppc_altivec_lvxl:
5446 // Turn lvx -> load if the pointer is known aligned.
5447 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
5448 Instruction *Ptr = new CastInst(II->getOperand(1),
5449 PointerType::get(II->getType()), "tmp");
5450 InsertNewInstBefore(Ptr, CI);
5451 return new LoadInst(Ptr);
5452 }
5453 break;
5454 case Intrinsic::ppc_altivec_stvx:
5455 case Intrinsic::ppc_altivec_stvxl:
5456 // Turn stvx -> store if the pointer is known aligned.
5457 if (GetKnownAlignment(II->getOperand(2), TD) >= 16) {
5458 const Type *OpTy = II->getOperand(1)->getType();
5459 Instruction *Ptr = new CastInst(II->getOperand(2),
5460 PointerType::get(OpTy), "tmp");
5461 InsertNewInstBefore(Ptr, CI);
5462 return new StoreInst(II->getOperand(1), Ptr);
5463 }
5464 break;
5465
Chris Lattnera728ddc2006-01-13 21:28:09 +00005466 case Intrinsic::stackrestore: {
5467 // If the save is right next to the restore, remove the restore. This can
5468 // happen when variable allocas are DCE'd.
5469 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
5470 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
5471 BasicBlock::iterator BI = SS;
5472 if (&*++BI == II)
5473 return EraseInstFromFunction(CI);
5474 }
5475 }
5476
5477 // If the stack restore is in a return/unwind block and if there are no
5478 // allocas or calls between the restore and the return, nuke the restore.
5479 TerminatorInst *TI = II->getParent()->getTerminator();
5480 if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
5481 BasicBlock::iterator BI = II;
5482 bool CannotRemove = false;
5483 for (++BI; &*BI != TI; ++BI) {
5484 if (isa<AllocaInst>(BI) ||
5485 (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
5486 CannotRemove = true;
5487 break;
5488 }
5489 }
5490 if (!CannotRemove)
5491 return EraseInstFromFunction(CI);
5492 }
5493 break;
5494 }
5495 }
Chris Lattner35b9e482004-10-12 04:52:52 +00005496 }
5497
Chris Lattner8b0ea312006-01-13 20:11:04 +00005498 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +00005499}
5500
5501// InvokeInst simplification
5502//
5503Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +00005504 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +00005505}
5506
Chris Lattnera44d8a22003-10-07 22:32:43 +00005507// visitCallSite - Improvements for call and invoke instructions.
5508//
5509Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +00005510 bool Changed = false;
5511
5512 // If the callee is a constexpr cast of a function, attempt to move the cast
5513 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +00005514 if (transformConstExprCastCall(CS)) return 0;
5515
Chris Lattner6c266db2003-10-07 22:54:13 +00005516 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +00005517
Chris Lattner08b22ec2005-05-13 07:09:09 +00005518 if (Function *CalleeF = dyn_cast<Function>(Callee))
5519 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
5520 Instruction *OldCall = CS.getInstruction();
5521 // If the call and callee calling conventions don't match, this call must
5522 // be unreachable, as the call is undefined.
5523 new StoreInst(ConstantBool::True,
5524 UndefValue::get(PointerType::get(Type::BoolTy)), OldCall);
5525 if (!OldCall->use_empty())
5526 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
5527 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
5528 return EraseInstFromFunction(*OldCall);
5529 return 0;
5530 }
5531
Chris Lattner17be6352004-10-18 02:59:09 +00005532 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
5533 // This instruction is not reachable, just remove it. We insert a store to
5534 // undef so that we know that this code is not reachable, despite the fact
5535 // that we can't modify the CFG here.
5536 new StoreInst(ConstantBool::True,
5537 UndefValue::get(PointerType::get(Type::BoolTy)),
5538 CS.getInstruction());
5539
5540 if (!CS.getInstruction()->use_empty())
5541 CS.getInstruction()->
5542 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
5543
5544 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
5545 // Don't break the CFG, insert a dummy cond branch.
5546 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
5547 ConstantBool::True, II);
Chris Lattnere87597f2004-10-16 18:11:37 +00005548 }
Chris Lattner17be6352004-10-18 02:59:09 +00005549 return EraseInstFromFunction(*CS.getInstruction());
5550 }
Chris Lattnere87597f2004-10-16 18:11:37 +00005551
Chris Lattner6c266db2003-10-07 22:54:13 +00005552 const PointerType *PTy = cast<PointerType>(Callee->getType());
5553 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
5554 if (FTy->isVarArg()) {
5555 // See if we can optimize any arguments passed through the varargs area of
5556 // the call.
5557 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
5558 E = CS.arg_end(); I != E; ++I)
5559 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
5560 // If this cast does not effect the value passed through the varargs
5561 // area, we can eliminate the use of the cast.
5562 Value *Op = CI->getOperand(0);
5563 if (CI->getType()->isLosslesslyConvertibleTo(Op->getType())) {
5564 *I = Op;
5565 Changed = true;
5566 }
5567 }
5568 }
Misha Brukmanfd939082005-04-21 23:48:37 +00005569
Chris Lattner6c266db2003-10-07 22:54:13 +00005570 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +00005571}
5572
Chris Lattner9fe38862003-06-19 17:00:31 +00005573// transformConstExprCastCall - If the callee is a constexpr cast of a function,
5574// attempt to move the cast to the arguments of the call/invoke.
5575//
5576bool InstCombiner::transformConstExprCastCall(CallSite CS) {
5577 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
5578 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Chris Lattner9db07b92004-07-18 18:59:44 +00005579 if (CE->getOpcode() != Instruction::Cast || !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +00005580 return false;
Reid Spencer8863f182004-07-18 00:38:32 +00005581 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +00005582 Instruction *Caller = CS.getInstruction();
5583
5584 // Okay, this is a cast from a function to a different type. Unless doing so
5585 // would cause a type conversion of one of our arguments, change this call to
5586 // be a direct call with arguments casted to the appropriate types.
5587 //
5588 const FunctionType *FT = Callee->getFunctionType();
5589 const Type *OldRetTy = Caller->getType();
5590
Chris Lattnerf78616b2004-01-14 06:06:08 +00005591 // Check to see if we are changing the return type...
5592 if (OldRetTy != FT->getReturnType()) {
5593 if (Callee->isExternal() &&
5594 !OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()) &&
5595 !Caller->use_empty())
5596 return false; // Cannot transform this return value...
5597
5598 // If the callsite is an invoke instruction, and the return value is used by
5599 // a PHI node in a successor, we cannot change the return type of the call
5600 // because there is no place to put the cast instruction (without breaking
5601 // the critical edge). Bail out in this case.
5602 if (!Caller->use_empty())
5603 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
5604 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
5605 UI != E; ++UI)
5606 if (PHINode *PN = dyn_cast<PHINode>(*UI))
5607 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00005608 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +00005609 return false;
5610 }
Chris Lattner9fe38862003-06-19 17:00:31 +00005611
5612 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
5613 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +00005614
Chris Lattner9fe38862003-06-19 17:00:31 +00005615 CallSite::arg_iterator AI = CS.arg_begin();
5616 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
5617 const Type *ParamTy = FT->getParamType(i);
5618 bool isConvertible = (*AI)->getType()->isLosslesslyConvertibleTo(ParamTy);
Misha Brukmanfd939082005-04-21 23:48:37 +00005619 if (Callee->isExternal() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +00005620 }
5621
5622 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
5623 Callee->isExternal())
5624 return false; // Do not delete arguments unless we have a function body...
5625
5626 // Okay, we decided that this is a safe thing to do: go ahead and start
5627 // inserting cast instructions as necessary...
5628 std::vector<Value*> Args;
5629 Args.reserve(NumActualArgs);
5630
5631 AI = CS.arg_begin();
5632 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
5633 const Type *ParamTy = FT->getParamType(i);
5634 if ((*AI)->getType() == ParamTy) {
5635 Args.push_back(*AI);
5636 } else {
Chris Lattner0c199a72004-04-08 04:43:23 +00005637 Args.push_back(InsertNewInstBefore(new CastInst(*AI, ParamTy, "tmp"),
5638 *Caller));
Chris Lattner9fe38862003-06-19 17:00:31 +00005639 }
5640 }
5641
5642 // If the function takes more arguments than the call was taking, add them
5643 // now...
5644 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
5645 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
5646
5647 // If we are removing arguments to the function, emit an obnoxious warning...
5648 if (FT->getNumParams() < NumActualArgs)
5649 if (!FT->isVarArg()) {
5650 std::cerr << "WARNING: While resolving call to function '"
5651 << Callee->getName() << "' arguments were dropped!\n";
5652 } else {
5653 // Add all of the arguments in their promoted form to the arg list...
5654 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
5655 const Type *PTy = getPromotedType((*AI)->getType());
5656 if (PTy != (*AI)->getType()) {
5657 // Must promote to pass through va_arg area!
5658 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
5659 InsertNewInstBefore(Cast, *Caller);
5660 Args.push_back(Cast);
5661 } else {
5662 Args.push_back(*AI);
5663 }
5664 }
5665 }
5666
5667 if (FT->getReturnType() == Type::VoidTy)
5668 Caller->setName(""); // Void type should not have a name...
5669
5670 Instruction *NC;
5671 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00005672 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattner9fe38862003-06-19 17:00:31 +00005673 Args, Caller->getName(), Caller);
Chris Lattnere4370262005-05-14 12:25:32 +00005674 cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
Chris Lattner9fe38862003-06-19 17:00:31 +00005675 } else {
5676 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
Chris Lattnera9e92112005-05-06 06:48:21 +00005677 if (cast<CallInst>(Caller)->isTailCall())
5678 cast<CallInst>(NC)->setTailCall();
Chris Lattnere4370262005-05-14 12:25:32 +00005679 cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Chris Lattner9fe38862003-06-19 17:00:31 +00005680 }
5681
5682 // Insert a cast of the return type as necessary...
5683 Value *NV = NC;
5684 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
5685 if (NV->getType() != Type::VoidTy) {
5686 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +00005687
5688 // If this is an invoke instruction, we should insert it after the first
5689 // non-phi, instruction in the normal successor block.
5690 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
5691 BasicBlock::iterator I = II->getNormalDest()->begin();
5692 while (isa<PHINode>(I)) ++I;
5693 InsertNewInstBefore(NC, *I);
5694 } else {
5695 // Otherwise, it's a call, just insert cast right after the call instr
5696 InsertNewInstBefore(NC, *Caller);
5697 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00005698 AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00005699 } else {
Chris Lattnerc30bda72004-10-17 21:22:38 +00005700 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +00005701 }
5702 }
5703
5704 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
5705 Caller->replaceAllUsesWith(NV);
5706 Caller->getParent()->getInstList().erase(Caller);
5707 removeFromWorkList(Caller);
5708 return true;
5709}
5710
5711
Chris Lattnerbac32862004-11-14 19:13:23 +00005712// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
5713// operator and they all are only used by the PHI, PHI together their
5714// inputs, and do the operation once, to the result of the PHI.
5715Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
5716 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
5717
5718 // Scan the instruction, looking for input operations that can be folded away.
5719 // If all input operands to the phi are the same instruction (e.g. a cast from
5720 // the same type or "+42") we can pull the operation through the PHI, reducing
5721 // code size and simplifying code.
5722 Constant *ConstantOp = 0;
5723 const Type *CastSrcTy = 0;
5724 if (isa<CastInst>(FirstInst)) {
5725 CastSrcTy = FirstInst->getOperand(0)->getType();
5726 } else if (isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst)) {
5727 // Can fold binop or shift if the RHS is a constant.
5728 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
5729 if (ConstantOp == 0) return 0;
5730 } else {
5731 return 0; // Cannot fold this operation.
5732 }
5733
5734 // Check to see if all arguments are the same operation.
5735 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
5736 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
5737 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
5738 if (!I->hasOneUse() || I->getOpcode() != FirstInst->getOpcode())
5739 return 0;
5740 if (CastSrcTy) {
5741 if (I->getOperand(0)->getType() != CastSrcTy)
5742 return 0; // Cast operation must match.
5743 } else if (I->getOperand(1) != ConstantOp) {
5744 return 0;
5745 }
5746 }
5747
5748 // Okay, they are all the same operation. Create a new PHI node of the
5749 // correct type, and PHI together all of the LHS's of the instructions.
5750 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
5751 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +00005752 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +00005753
5754 Value *InVal = FirstInst->getOperand(0);
5755 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00005756
5757 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +00005758 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
5759 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
5760 if (NewInVal != InVal)
5761 InVal = 0;
5762 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
5763 }
5764
5765 Value *PhiVal;
5766 if (InVal) {
5767 // The new PHI unions all of the same values together. This is really
5768 // common, so we handle it intelligently here for compile-time speed.
5769 PhiVal = InVal;
5770 delete NewPN;
5771 } else {
5772 InsertNewInstBefore(NewPN, PN);
5773 PhiVal = NewPN;
5774 }
Misha Brukmanfd939082005-04-21 23:48:37 +00005775
Chris Lattnerbac32862004-11-14 19:13:23 +00005776 // Insert and return the new operation.
5777 if (isa<CastInst>(FirstInst))
Chris Lattnerb5893442004-11-14 19:29:34 +00005778 return new CastInst(PhiVal, PN.getType());
Chris Lattnerbac32862004-11-14 19:13:23 +00005779 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattnerb5893442004-11-14 19:29:34 +00005780 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattnerbac32862004-11-14 19:13:23 +00005781 else
5782 return new ShiftInst(cast<ShiftInst>(FirstInst)->getOpcode(),
Chris Lattnerb5893442004-11-14 19:29:34 +00005783 PhiVal, ConstantOp);
Chris Lattnerbac32862004-11-14 19:13:23 +00005784}
Chris Lattnera1be5662002-05-02 17:06:02 +00005785
Chris Lattnera3fd1c52005-01-17 05:10:15 +00005786/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
5787/// that is dead.
5788static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
5789 if (PN->use_empty()) return true;
5790 if (!PN->hasOneUse()) return false;
5791
5792 // Remember this node, and if we find the cycle, return.
5793 if (!PotentiallyDeadPHIs.insert(PN).second)
5794 return true;
5795
5796 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
5797 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +00005798
Chris Lattnera3fd1c52005-01-17 05:10:15 +00005799 return false;
5800}
5801
Chris Lattner473945d2002-05-06 18:06:38 +00005802// PHINode simplification
5803//
Chris Lattner7e708292002-06-25 16:13:24 +00005804Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Chris Lattner68ee7362005-08-05 01:04:30 +00005805 if (Value *V = PN.hasConstantValue())
5806 return ReplaceInstUsesWith(PN, V);
Chris Lattner7059f2e2004-02-16 05:07:08 +00005807
5808 // If the only user of this instruction is a cast instruction, and all of the
5809 // incoming values are constants, change this PHI to merge together the casted
5810 // constants.
5811 if (PN.hasOneUse())
5812 if (CastInst *CI = dyn_cast<CastInst>(PN.use_back()))
5813 if (CI->getType() != PN.getType()) { // noop casts will be folded
5814 bool AllConstant = true;
5815 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
5816 if (!isa<Constant>(PN.getIncomingValue(i))) {
5817 AllConstant = false;
5818 break;
5819 }
5820 if (AllConstant) {
5821 // Make a new PHI with all casted values.
5822 PHINode *New = new PHINode(CI->getType(), PN.getName(), &PN);
5823 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
5824 Constant *OldArg = cast<Constant>(PN.getIncomingValue(i));
5825 New->addIncoming(ConstantExpr::getCast(OldArg, New->getType()),
5826 PN.getIncomingBlock(i));
5827 }
5828
5829 // Update the cast instruction.
5830 CI->setOperand(0, New);
5831 WorkList.push_back(CI); // revisit the cast instruction to fold.
5832 WorkList.push_back(New); // Make sure to revisit the new Phi
5833 return &PN; // PN is now dead!
5834 }
5835 }
Chris Lattnerbac32862004-11-14 19:13:23 +00005836
5837 // If all PHI operands are the same operation, pull them through the PHI,
5838 // reducing code size.
5839 if (isa<Instruction>(PN.getIncomingValue(0)) &&
5840 PN.getIncomingValue(0)->hasOneUse())
5841 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
5842 return Result;
5843
Chris Lattnera3fd1c52005-01-17 05:10:15 +00005844 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
5845 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
5846 // PHI)... break the cycle.
5847 if (PN.hasOneUse())
5848 if (PHINode *PU = dyn_cast<PHINode>(PN.use_back())) {
5849 std::set<PHINode*> PotentiallyDeadPHIs;
5850 PotentiallyDeadPHIs.insert(&PN);
5851 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
5852 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
5853 }
Misha Brukmanfd939082005-04-21 23:48:37 +00005854
Chris Lattner60921c92003-12-19 05:58:40 +00005855 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +00005856}
5857
Chris Lattner28977af2004-04-05 01:30:19 +00005858static Value *InsertSignExtendToPtrTy(Value *V, const Type *DTy,
5859 Instruction *InsertPoint,
5860 InstCombiner *IC) {
5861 unsigned PS = IC->getTargetData().getPointerSize();
5862 const Type *VTy = V->getType();
Chris Lattner28977af2004-04-05 01:30:19 +00005863 if (!VTy->isSigned() && VTy->getPrimitiveSize() < PS)
5864 // We must insert a cast to ensure we sign-extend.
5865 V = IC->InsertNewInstBefore(new CastInst(V, VTy->getSignedVersion(),
5866 V->getName()), *InsertPoint);
5867 return IC->InsertNewInstBefore(new CastInst(V, DTy, V->getName()),
5868 *InsertPoint);
5869}
5870
Chris Lattnera1be5662002-05-02 17:06:02 +00005871
Chris Lattner7e708292002-06-25 16:13:24 +00005872Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +00005873 Value *PtrOp = GEP.getOperand(0);
Chris Lattnerc54e2b82003-05-22 19:07:21 +00005874 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner7e708292002-06-25 16:13:24 +00005875 // If so, eliminate the noop.
Chris Lattnerc6bd1952004-02-22 05:25:17 +00005876 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +00005877 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +00005878
Chris Lattnere87597f2004-10-16 18:11:37 +00005879 if (isa<UndefValue>(GEP.getOperand(0)))
5880 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
5881
Chris Lattnerc6bd1952004-02-22 05:25:17 +00005882 bool HasZeroPointerIndex = false;
5883 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
5884 HasZeroPointerIndex = C->isNullValue();
5885
5886 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +00005887 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +00005888
Chris Lattner28977af2004-04-05 01:30:19 +00005889 // Eliminate unneeded casts for indices.
5890 bool MadeChange = false;
Chris Lattnercb69a4e2004-04-07 18:38:20 +00005891 gep_type_iterator GTI = gep_type_begin(GEP);
5892 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
5893 if (isa<SequentialType>(*GTI)) {
5894 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
5895 Value *Src = CI->getOperand(0);
5896 const Type *SrcTy = Src->getType();
5897 const Type *DestTy = CI->getType();
5898 if (Src->getType()->isInteger()) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00005899 if (SrcTy->getPrimitiveSizeInBits() ==
5900 DestTy->getPrimitiveSizeInBits()) {
Chris Lattnercb69a4e2004-04-07 18:38:20 +00005901 // We can always eliminate a cast from ulong or long to the other.
5902 // We can always eliminate a cast from uint to int or the other on
5903 // 32-bit pointer platforms.
Chris Lattner484d3cf2005-04-24 06:59:08 +00005904 if (DestTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()){
Chris Lattnercb69a4e2004-04-07 18:38:20 +00005905 MadeChange = true;
5906 GEP.setOperand(i, Src);
5907 }
5908 } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
5909 SrcTy->getPrimitiveSize() == 4) {
5910 // We can always eliminate a cast from int to [u]long. We can
5911 // eliminate a cast from uint to [u]long iff the target is a 32-bit
5912 // pointer target.
Misha Brukmanfd939082005-04-21 23:48:37 +00005913 if (SrcTy->isSigned() ||
Chris Lattner484d3cf2005-04-24 06:59:08 +00005914 SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
Chris Lattnercb69a4e2004-04-07 18:38:20 +00005915 MadeChange = true;
5916 GEP.setOperand(i, Src);
5917 }
Chris Lattner28977af2004-04-05 01:30:19 +00005918 }
5919 }
5920 }
Chris Lattnercb69a4e2004-04-07 18:38:20 +00005921 // If we are using a wider index than needed for this platform, shrink it
5922 // to what we need. If the incoming value needs a cast instruction,
5923 // insert it. This explicit cast can make subsequent optimizations more
5924 // obvious.
5925 Value *Op = GEP.getOperand(i);
5926 if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
Chris Lattner4f1134e2004-04-17 18:16:10 +00005927 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner67769e52004-07-20 01:48:15 +00005928 GEP.setOperand(i, ConstantExpr::getCast(C,
5929 TD->getIntPtrType()->getSignedVersion()));
Chris Lattner4f1134e2004-04-17 18:16:10 +00005930 MadeChange = true;
5931 } else {
Chris Lattnercb69a4e2004-04-07 18:38:20 +00005932 Op = InsertNewInstBefore(new CastInst(Op, TD->getIntPtrType(),
5933 Op->getName()), GEP);
5934 GEP.setOperand(i, Op);
5935 MadeChange = true;
5936 }
Chris Lattner67769e52004-07-20 01:48:15 +00005937
5938 // If this is a constant idx, make sure to canonicalize it to be a signed
5939 // operand, otherwise CSE and other optimizations are pessimized.
5940 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op)) {
5941 GEP.setOperand(i, ConstantExpr::getCast(CUI,
5942 CUI->getType()->getSignedVersion()));
5943 MadeChange = true;
5944 }
Chris Lattner28977af2004-04-05 01:30:19 +00005945 }
5946 if (MadeChange) return &GEP;
5947
Chris Lattner90ac28c2002-08-02 19:29:35 +00005948 // Combine Indices - If the source pointer to this getelementptr instruction
5949 // is a getelementptr instruction, combine the indices of the two
5950 // getelementptr instructions into a single instruction.
5951 //
Chris Lattnerebd985c2004-03-25 22:59:29 +00005952 std::vector<Value*> SrcGEPOperands;
Chris Lattner574da9b2005-01-13 20:14:25 +00005953 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattnerebd985c2004-03-25 22:59:29 +00005954 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
Chris Lattnerebd985c2004-03-25 22:59:29 +00005955
5956 if (!SrcGEPOperands.empty()) {
Chris Lattner620ce142004-05-07 22:09:22 +00005957 // Note that if our source is a gep chain itself that we wait for that
5958 // chain to be resolved before we perform this transformation. This
5959 // avoids us creating a TON of code in some cases.
5960 //
5961 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
5962 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
5963 return 0; // Wait until our source is folded to completion.
5964
Chris Lattner90ac28c2002-08-02 19:29:35 +00005965 std::vector<Value *> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +00005966
5967 // Find out whether the last index in the source GEP is a sequential idx.
5968 bool EndsWithSequential = false;
5969 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
5970 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +00005971 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +00005972
Chris Lattner90ac28c2002-08-02 19:29:35 +00005973 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +00005974 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +00005975 // Replace: gep (gep %P, long B), long A, ...
5976 // With: T = long A+B; gep %P, T, ...
5977 //
Chris Lattner620ce142004-05-07 22:09:22 +00005978 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner28977af2004-04-05 01:30:19 +00005979 if (SO1 == Constant::getNullValue(SO1->getType())) {
5980 Sum = GO1;
5981 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
5982 Sum = SO1;
5983 } else {
5984 // If they aren't the same type, convert both to an integer of the
5985 // target's pointer size.
5986 if (SO1->getType() != GO1->getType()) {
5987 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
5988 SO1 = ConstantExpr::getCast(SO1C, GO1->getType());
5989 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
5990 GO1 = ConstantExpr::getCast(GO1C, SO1->getType());
5991 } else {
5992 unsigned PS = TD->getPointerSize();
Chris Lattner28977af2004-04-05 01:30:19 +00005993 if (SO1->getType()->getPrimitiveSize() == PS) {
5994 // Convert GO1 to SO1's type.
5995 GO1 = InsertSignExtendToPtrTy(GO1, SO1->getType(), &GEP, this);
5996
5997 } else if (GO1->getType()->getPrimitiveSize() == PS) {
5998 // Convert SO1 to GO1's type.
5999 SO1 = InsertSignExtendToPtrTy(SO1, GO1->getType(), &GEP, this);
6000 } else {
6001 const Type *PT = TD->getIntPtrType();
6002 SO1 = InsertSignExtendToPtrTy(SO1, PT, &GEP, this);
6003 GO1 = InsertSignExtendToPtrTy(GO1, PT, &GEP, this);
6004 }
6005 }
6006 }
Chris Lattner620ce142004-05-07 22:09:22 +00006007 if (isa<Constant>(SO1) && isa<Constant>(GO1))
6008 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
6009 else {
Chris Lattner48595f12004-06-10 02:07:29 +00006010 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
6011 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner620ce142004-05-07 22:09:22 +00006012 }
Chris Lattner28977af2004-04-05 01:30:19 +00006013 }
Chris Lattner620ce142004-05-07 22:09:22 +00006014
6015 // Recycle the GEP we already have if possible.
6016 if (SrcGEPOperands.size() == 2) {
6017 GEP.setOperand(0, SrcGEPOperands[0]);
6018 GEP.setOperand(1, Sum);
6019 return &GEP;
6020 } else {
6021 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
6022 SrcGEPOperands.end()-1);
6023 Indices.push_back(Sum);
6024 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
6025 }
Misha Brukmanfd939082005-04-21 23:48:37 +00006026 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +00006027 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanfd939082005-04-21 23:48:37 +00006028 SrcGEPOperands.size() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +00006029 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerebd985c2004-03-25 22:59:29 +00006030 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
6031 SrcGEPOperands.end());
Chris Lattner90ac28c2002-08-02 19:29:35 +00006032 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
6033 }
6034
6035 if (!Indices.empty())
Chris Lattnerebd985c2004-03-25 22:59:29 +00006036 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
Chris Lattner9b761232002-08-17 22:21:59 +00006037
Chris Lattner620ce142004-05-07 22:09:22 +00006038 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattner9b761232002-08-17 22:21:59 +00006039 // GEP of global variable. If all of the indices for this GEP are
6040 // constants, we can promote this to a constexpr instead of an instruction.
6041
6042 // Scan for nonconstants...
6043 std::vector<Constant*> Indices;
6044 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
6045 for (; I != E && isa<Constant>(*I); ++I)
6046 Indices.push_back(cast<Constant>(*I));
6047
6048 if (I == E) { // If they are all constants...
Chris Lattner9db07b92004-07-18 18:59:44 +00006049 Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
Chris Lattner9b761232002-08-17 22:21:59 +00006050
6051 // Replace all uses of the GEP with the new constexpr...
6052 return ReplaceInstUsesWith(GEP, CE);
6053 }
Chris Lattnereed48272005-09-13 00:40:14 +00006054 } else if (Value *X = isCast(PtrOp)) { // Is the operand a cast?
6055 if (!isa<PointerType>(X->getType())) {
6056 // Not interesting. Source pointer must be a cast from pointer.
6057 } else if (HasZeroPointerIndex) {
6058 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
6059 // into : GEP [10 x ubyte]* X, long 0, ...
6060 //
6061 // This occurs when the program declares an array extern like "int X[];"
6062 //
6063 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
6064 const PointerType *XTy = cast<PointerType>(X->getType());
6065 if (const ArrayType *XATy =
6066 dyn_cast<ArrayType>(XTy->getElementType()))
6067 if (const ArrayType *CATy =
6068 dyn_cast<ArrayType>(CPTy->getElementType()))
6069 if (CATy->getElementType() == XATy->getElementType()) {
6070 // At this point, we know that the cast source type is a pointer
6071 // to an array of the same type as the destination pointer
6072 // array. Because the array type is never stepped over (there
6073 // is a leading zero) we can fold the cast into this GEP.
6074 GEP.setOperand(0, X);
6075 return &GEP;
6076 }
6077 } else if (GEP.getNumOperands() == 2) {
6078 // Transform things like:
Chris Lattner7835cdd2005-09-13 18:36:04 +00006079 // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
6080 // into: %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
Chris Lattnereed48272005-09-13 00:40:14 +00006081 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
6082 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
6083 if (isa<ArrayType>(SrcElTy) &&
6084 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
6085 TD->getTypeSize(ResElTy)) {
6086 Value *V = InsertNewInstBefore(
6087 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
6088 GEP.getOperand(1), GEP.getName()), GEP);
6089 return new CastInst(V, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +00006090 }
Chris Lattner7835cdd2005-09-13 18:36:04 +00006091
6092 // Transform things like:
6093 // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
6094 // (where tmp = 8*tmp2) into:
6095 // getelementptr [100 x double]* %arr, int 0, int %tmp.2
6096
6097 if (isa<ArrayType>(SrcElTy) &&
6098 (ResElTy == Type::SByteTy || ResElTy == Type::UByteTy)) {
6099 uint64_t ArrayEltSize =
6100 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
6101
6102 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
6103 // allow either a mul, shift, or constant here.
6104 Value *NewIdx = 0;
6105 ConstantInt *Scale = 0;
6106 if (ArrayEltSize == 1) {
6107 NewIdx = GEP.getOperand(1);
6108 Scale = ConstantInt::get(NewIdx->getType(), 1);
6109 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattner6e2f8432005-09-14 17:32:56 +00006110 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +00006111 Scale = CI;
6112 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
6113 if (Inst->getOpcode() == Instruction::Shl &&
6114 isa<ConstantInt>(Inst->getOperand(1))) {
6115 unsigned ShAmt =cast<ConstantUInt>(Inst->getOperand(1))->getValue();
6116 if (Inst->getType()->isSigned())
6117 Scale = ConstantSInt::get(Inst->getType(), 1ULL << ShAmt);
6118 else
6119 Scale = ConstantUInt::get(Inst->getType(), 1ULL << ShAmt);
6120 NewIdx = Inst->getOperand(0);
6121 } else if (Inst->getOpcode() == Instruction::Mul &&
6122 isa<ConstantInt>(Inst->getOperand(1))) {
6123 Scale = cast<ConstantInt>(Inst->getOperand(1));
6124 NewIdx = Inst->getOperand(0);
6125 }
6126 }
6127
6128 // If the index will be to exactly the right offset with the scale taken
6129 // out, perform the transformation.
6130 if (Scale && Scale->getRawValue() % ArrayEltSize == 0) {
6131 if (ConstantSInt *C = dyn_cast<ConstantSInt>(Scale))
6132 Scale = ConstantSInt::get(C->getType(),
Chris Lattner6e2f8432005-09-14 17:32:56 +00006133 (int64_t)C->getRawValue() /
6134 (int64_t)ArrayEltSize);
Chris Lattner7835cdd2005-09-13 18:36:04 +00006135 else
6136 Scale = ConstantUInt::get(Scale->getType(),
6137 Scale->getRawValue() / ArrayEltSize);
6138 if (Scale->getRawValue() != 1) {
6139 Constant *C = ConstantExpr::getCast(Scale, NewIdx->getType());
6140 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
6141 NewIdx = InsertNewInstBefore(Sc, GEP);
6142 }
6143
6144 // Insert the new GEP instruction.
6145 Instruction *Idx =
6146 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
6147 NewIdx, GEP.getName());
6148 Idx = InsertNewInstBefore(Idx, GEP);
6149 return new CastInst(Idx, GEP.getType());
6150 }
6151 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +00006152 }
Chris Lattner8a2a3112001-12-14 16:52:21 +00006153 }
6154
Chris Lattner8a2a3112001-12-14 16:52:21 +00006155 return 0;
6156}
6157
Chris Lattner0864acf2002-11-04 16:18:53 +00006158Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
6159 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
6160 if (AI.isArrayAllocation()) // Check C != 1
6161 if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
6162 const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
Chris Lattner0006bd72002-11-09 00:49:43 +00006163 AllocationInst *New = 0;
Chris Lattner0864acf2002-11-04 16:18:53 +00006164
6165 // Create and insert the replacement instruction...
6166 if (isa<MallocInst>(AI))
Nate Begeman14b05292005-11-05 09:21:28 +00006167 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +00006168 else {
6169 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman14b05292005-11-05 09:21:28 +00006170 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +00006171 }
Chris Lattner7c881df2004-03-19 06:08:10 +00006172
6173 InsertNewInstBefore(New, AI);
Misha Brukmanfd939082005-04-21 23:48:37 +00006174
Chris Lattner0864acf2002-11-04 16:18:53 +00006175 // Scan to the end of the allocation instructions, to skip over a block of
6176 // allocas if possible...
6177 //
6178 BasicBlock::iterator It = New;
6179 while (isa<AllocationInst>(*It)) ++It;
6180
6181 // Now that I is pointing to the first non-allocation-inst in the block,
6182 // insert our getelementptr instruction...
6183 //
Chris Lattner693787a2005-05-04 19:10:26 +00006184 Value *NullIdx = Constant::getNullValue(Type::IntTy);
6185 Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
6186 New->getName()+".sub", It);
Chris Lattner0864acf2002-11-04 16:18:53 +00006187
6188 // Now make everything use the getelementptr instead of the original
6189 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +00006190 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +00006191 } else if (isa<UndefValue>(AI.getArraySize())) {
6192 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +00006193 }
Chris Lattner7c881df2004-03-19 06:08:10 +00006194
6195 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
6196 // Note that we only do this for alloca's, because malloc should allocate and
6197 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanfd939082005-04-21 23:48:37 +00006198 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Chris Lattnercf27afb2004-07-02 22:55:47 +00006199 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattner7c881df2004-03-19 06:08:10 +00006200 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
6201
Chris Lattner0864acf2002-11-04 16:18:53 +00006202 return 0;
6203}
6204
Chris Lattner67b1e1b2003-12-07 01:24:23 +00006205Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
6206 Value *Op = FI.getOperand(0);
6207
6208 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
6209 if (CastInst *CI = dyn_cast<CastInst>(Op))
6210 if (isa<PointerType>(CI->getOperand(0)->getType())) {
6211 FI.setOperand(0, CI->getOperand(0));
6212 return &FI;
6213 }
6214
Chris Lattner17be6352004-10-18 02:59:09 +00006215 // free undef -> unreachable.
6216 if (isa<UndefValue>(Op)) {
6217 // Insert a new store to null because we cannot modify the CFG here.
6218 new StoreInst(ConstantBool::True,
6219 UndefValue::get(PointerType::get(Type::BoolTy)), &FI);
6220 return EraseInstFromFunction(FI);
6221 }
6222
Chris Lattner6160e852004-02-28 04:57:37 +00006223 // If we have 'free null' delete the instruction. This can happen in stl code
6224 // when lots of inlining happens.
Chris Lattner17be6352004-10-18 02:59:09 +00006225 if (isa<ConstantPointerNull>(Op))
Chris Lattner7bcc0e72004-02-28 05:22:00 +00006226 return EraseInstFromFunction(FI);
Chris Lattner6160e852004-02-28 04:57:37 +00006227
Chris Lattner67b1e1b2003-12-07 01:24:23 +00006228 return 0;
6229}
6230
6231
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00006232/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Chris Lattnerb89e0712004-07-13 01:49:43 +00006233static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
6234 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +00006235 Value *CastOp = CI->getOperand(0);
Chris Lattnerb89e0712004-07-13 01:49:43 +00006236
6237 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +00006238 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattnerb89e0712004-07-13 01:49:43 +00006239 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +00006240
Chris Lattnera1c35382006-04-02 05:37:12 +00006241 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
6242 isa<PackedType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +00006243 // If the source is an array, the code below will not succeed. Check to
6244 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
6245 // constants.
6246 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
6247 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
6248 if (ASrcTy->getNumElements() != 0) {
6249 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
6250 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
6251 SrcTy = cast<PointerType>(CastOp->getType());
6252 SrcPTy = SrcTy->getElementType();
6253 }
6254
Chris Lattnera1c35382006-04-02 05:37:12 +00006255 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
6256 isa<PackedType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +00006257 // Do not allow turning this into a load of an integer, which is then
6258 // casted to a pointer, this pessimizes pointer analysis a lot.
6259 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Misha Brukmanfd939082005-04-21 23:48:37 +00006260 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattnerf9527852005-01-31 04:50:46 +00006261 IC.getTargetData().getTypeSize(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +00006262
Chris Lattnerf9527852005-01-31 04:50:46 +00006263 // Okay, we are casting from one integer or pointer type to another of
6264 // the same size. Instead of casting the pointer before the load, cast
6265 // the result of the loaded value.
6266 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
6267 CI->getName(),
6268 LI.isVolatile()),LI);
6269 // Now cast the result of the load.
6270 return new CastInst(NewLoad, LI.getType());
6271 }
Chris Lattnerb89e0712004-07-13 01:49:43 +00006272 }
6273 }
6274 return 0;
6275}
6276
Chris Lattnerc10aced2004-09-19 18:43:46 +00006277/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattner8a375202004-09-19 19:18:10 +00006278/// from this value cannot trap. If it is not obviously safe to load from the
6279/// specified pointer, we do a quick local scan of the basic block containing
6280/// ScanFrom, to determine if the address is already accessed.
6281static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
6282 // If it is an alloca or global variable, it is always safe to load from.
6283 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
6284
6285 // Otherwise, be a little bit agressive by scanning the local block where we
6286 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00006287 // from/to. If so, the previous load or store would have already trapped,
6288 // so there is no harm doing an extra load (also, CSE will later eliminate
6289 // the load entirely).
Chris Lattner8a375202004-09-19 19:18:10 +00006290 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
6291
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00006292 while (BBI != E) {
Chris Lattner8a375202004-09-19 19:18:10 +00006293 --BBI;
6294
6295 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
6296 if (LI->getOperand(0) == V) return true;
6297 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
6298 if (SI->getOperand(1) == V) return true;
Misha Brukmanfd939082005-04-21 23:48:37 +00006299
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00006300 }
Chris Lattner8a375202004-09-19 19:18:10 +00006301 return false;
Chris Lattnerc10aced2004-09-19 18:43:46 +00006302}
6303
Chris Lattner833b8a42003-06-26 05:06:25 +00006304Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
6305 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +00006306
Chris Lattner37366c12005-05-01 04:24:53 +00006307 // load (cast X) --> cast (load X) iff safe
6308 if (CastInst *CI = dyn_cast<CastInst>(Op))
6309 if (Instruction *Res = InstCombineLoadCast(*this, LI))
6310 return Res;
6311
6312 // None of the following transforms are legal for volatile loads.
6313 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +00006314
Chris Lattner62f254d2005-09-12 22:00:15 +00006315 if (&LI.getParent()->front() != &LI) {
6316 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattner9c1f0fd2005-09-12 22:21:03 +00006317 // If the instruction immediately before this is a store to the same
6318 // address, do a simple form of store->load forwarding.
Chris Lattner62f254d2005-09-12 22:00:15 +00006319 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
6320 if (SI->getOperand(1) == LI.getOperand(0))
6321 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattner9c1f0fd2005-09-12 22:21:03 +00006322 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
6323 if (LIB->getOperand(0) == LI.getOperand(0))
6324 return ReplaceInstUsesWith(LI, LIB);
Chris Lattner62f254d2005-09-12 22:00:15 +00006325 }
Chris Lattner37366c12005-05-01 04:24:53 +00006326
6327 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
6328 if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
6329 isa<UndefValue>(GEPI->getOperand(0))) {
6330 // Insert a new store to null instruction before the load to indicate
6331 // that this code is not reachable. We do this instead of inserting
6332 // an unreachable instruction directly because we cannot modify the
6333 // CFG.
6334 new StoreInst(UndefValue::get(LI.getType()),
6335 Constant::getNullValue(Op->getType()), &LI);
6336 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
6337 }
6338
Chris Lattnere87597f2004-10-16 18:11:37 +00006339 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner37366c12005-05-01 04:24:53 +00006340 // load null/undef -> undef
6341 if ((C->isNullValue() || isa<UndefValue>(C))) {
Chris Lattner17be6352004-10-18 02:59:09 +00006342 // Insert a new store to null instruction before the load to indicate that
6343 // this code is not reachable. We do this instead of inserting an
6344 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattner37366c12005-05-01 04:24:53 +00006345 new StoreInst(UndefValue::get(LI.getType()),
6346 Constant::getNullValue(Op->getType()), &LI);
Chris Lattnere87597f2004-10-16 18:11:37 +00006347 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner17be6352004-10-18 02:59:09 +00006348 }
Chris Lattner833b8a42003-06-26 05:06:25 +00006349
Chris Lattnere87597f2004-10-16 18:11:37 +00006350 // Instcombine load (constant global) into the value loaded.
6351 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
6352 if (GV->isConstant() && !GV->isExternal())
6353 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +00006354
Chris Lattnere87597f2004-10-16 18:11:37 +00006355 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
6356 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
6357 if (CE->getOpcode() == Instruction::GetElementPtr) {
6358 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
6359 if (GV->isConstant() && !GV->isExternal())
Chris Lattner363f2a22005-09-26 05:28:06 +00006360 if (Constant *V =
6361 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattnere87597f2004-10-16 18:11:37 +00006362 return ReplaceInstUsesWith(LI, V);
Chris Lattner37366c12005-05-01 04:24:53 +00006363 if (CE->getOperand(0)->isNullValue()) {
6364 // Insert a new store to null instruction before the load to indicate
6365 // that this code is not reachable. We do this instead of inserting
6366 // an unreachable instruction directly because we cannot modify the
6367 // CFG.
6368 new StoreInst(UndefValue::get(LI.getType()),
6369 Constant::getNullValue(Op->getType()), &LI);
6370 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
6371 }
6372
Chris Lattnere87597f2004-10-16 18:11:37 +00006373 } else if (CE->getOpcode() == Instruction::Cast) {
6374 if (Instruction *Res = InstCombineLoadCast(*this, LI))
6375 return Res;
6376 }
6377 }
Chris Lattnerf499eac2004-04-08 20:39:49 +00006378
Chris Lattner37366c12005-05-01 04:24:53 +00006379 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +00006380 // Change select and PHI nodes to select values instead of addresses: this
6381 // helps alias analysis out a lot, allows many others simplifications, and
6382 // exposes redundancy in the code.
6383 //
6384 // Note that we cannot do the transformation unless we know that the
6385 // introduced loads cannot trap! Something like this is valid as long as
6386 // the condition is always false: load (select bool %C, int* null, int* %G),
6387 // but it would not be valid if we transformed it to load from null
6388 // unconditionally.
6389 //
6390 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
6391 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +00006392 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
6393 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerc10aced2004-09-19 18:43:46 +00006394 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner79f0c8e2004-09-20 10:15:10 +00006395 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +00006396 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner79f0c8e2004-09-20 10:15:10 +00006397 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +00006398 return new SelectInst(SI->getCondition(), V1, V2);
6399 }
6400
Chris Lattner684fe212004-09-23 15:46:00 +00006401 // load (select (cond, null, P)) -> load P
6402 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
6403 if (C->isNullValue()) {
6404 LI.setOperand(0, SI->getOperand(2));
6405 return &LI;
6406 }
6407
6408 // load (select (cond, P, null)) -> load P
6409 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
6410 if (C->isNullValue()) {
6411 LI.setOperand(0, SI->getOperand(1));
6412 return &LI;
6413 }
6414
Chris Lattnerc10aced2004-09-19 18:43:46 +00006415 } else if (PHINode *PN = dyn_cast<PHINode>(Op)) {
6416 // load (phi (&V1, &V2, &V3)) --> phi(load &V1, load &V2, load &V3)
Chris Lattner79f0c8e2004-09-20 10:15:10 +00006417 bool Safe = PN->getParent() == LI.getParent();
6418
6419 // Scan all of the instructions between the PHI and the load to make
6420 // sure there are no instructions that might possibly alter the value
6421 // loaded from the PHI.
6422 if (Safe) {
6423 BasicBlock::iterator I = &LI;
6424 for (--I; !isa<PHINode>(I); --I)
6425 if (isa<StoreInst>(I) || isa<CallInst>(I)) {
6426 Safe = false;
6427 break;
6428 }
6429 }
6430
6431 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e && Safe; ++i)
Chris Lattner8a375202004-09-19 19:18:10 +00006432 if (!isSafeToLoadUnconditionally(PN->getIncomingValue(i),
Chris Lattner79f0c8e2004-09-20 10:15:10 +00006433 PN->getIncomingBlock(i)->getTerminator()))
Chris Lattnerc10aced2004-09-19 18:43:46 +00006434 Safe = false;
Chris Lattner79f0c8e2004-09-20 10:15:10 +00006435
Chris Lattnerc10aced2004-09-19 18:43:46 +00006436 if (Safe) {
6437 // Create the PHI.
6438 PHINode *NewPN = new PHINode(LI.getType(), PN->getName());
6439 InsertNewInstBefore(NewPN, *PN);
6440 std::map<BasicBlock*,Value*> LoadMap; // Don't insert duplicate loads
6441
6442 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
6443 BasicBlock *BB = PN->getIncomingBlock(i);
6444 Value *&TheLoad = LoadMap[BB];
6445 if (TheLoad == 0) {
6446 Value *InVal = PN->getIncomingValue(i);
6447 TheLoad = InsertNewInstBefore(new LoadInst(InVal,
6448 InVal->getName()+".val"),
6449 *BB->getTerminator());
6450 }
6451 NewPN->addIncoming(TheLoad, BB);
6452 }
6453 return ReplaceInstUsesWith(LI, NewPN);
6454 }
6455 }
6456 }
Chris Lattner833b8a42003-06-26 05:06:25 +00006457 return 0;
6458}
6459
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00006460/// InstCombineStoreToCast - Fold 'store V, (cast P)' -> store (cast V), P'
6461/// when possible.
6462static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
6463 User *CI = cast<User>(SI.getOperand(1));
6464 Value *CastOp = CI->getOperand(0);
6465
6466 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
6467 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
6468 const Type *SrcPTy = SrcTy->getElementType();
6469
6470 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
6471 // If the source is an array, the code below will not succeed. Check to
6472 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
6473 // constants.
6474 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
6475 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
6476 if (ASrcTy->getNumElements() != 0) {
6477 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
6478 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
6479 SrcTy = cast<PointerType>(CastOp->getType());
6480 SrcPTy = SrcTy->getElementType();
6481 }
6482
6483 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
Misha Brukmanfd939082005-04-21 23:48:37 +00006484 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00006485 IC.getTargetData().getTypeSize(DestPTy)) {
6486
6487 // Okay, we are casting from one integer or pointer type to another of
6488 // the same size. Instead of casting the pointer before the store, cast
6489 // the value to be stored.
6490 Value *NewCast;
6491 if (Constant *C = dyn_cast<Constant>(SI.getOperand(0)))
6492 NewCast = ConstantExpr::getCast(C, SrcPTy);
6493 else
6494 NewCast = IC.InsertNewInstBefore(new CastInst(SI.getOperand(0),
6495 SrcPTy,
6496 SI.getOperand(0)->getName()+".c"), SI);
6497
6498 return new StoreInst(NewCast, CastOp);
6499 }
6500 }
6501 }
6502 return 0;
6503}
6504
Chris Lattner2f503e62005-01-31 05:36:43 +00006505Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
6506 Value *Val = SI.getOperand(0);
6507 Value *Ptr = SI.getOperand(1);
6508
6509 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner9ca96412006-02-08 03:25:32 +00006510 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +00006511 ++NumCombined;
6512 return 0;
6513 }
6514
Chris Lattner9ca96412006-02-08 03:25:32 +00006515 // Do really simple DSE, to catch cases where there are several consequtive
6516 // stores to the same location, separated by a few arithmetic operations. This
6517 // situation often occurs with bitfield accesses.
6518 BasicBlock::iterator BBI = &SI;
6519 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
6520 --ScanInsts) {
6521 --BBI;
6522
6523 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
6524 // Prev store isn't volatile, and stores to the same location?
6525 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
6526 ++NumDeadStore;
6527 ++BBI;
6528 EraseInstFromFunction(*PrevSI);
6529 continue;
6530 }
6531 break;
6532 }
6533
6534 // Don't skip over loads or things that can modify memory.
6535 if (BBI->mayWriteToMemory() || isa<LoadInst>(BBI))
6536 break;
6537 }
6538
6539
6540 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +00006541
6542 // store X, null -> turns into 'unreachable' in SimplifyCFG
6543 if (isa<ConstantPointerNull>(Ptr)) {
6544 if (!isa<UndefValue>(Val)) {
6545 SI.setOperand(0, UndefValue::get(Val->getType()));
6546 if (Instruction *U = dyn_cast<Instruction>(Val))
6547 WorkList.push_back(U); // Dropped a use.
6548 ++NumCombined;
6549 }
6550 return 0; // Do not modify these!
6551 }
6552
6553 // store undef, Ptr -> noop
6554 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +00006555 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +00006556 ++NumCombined;
6557 return 0;
6558 }
6559
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00006560 // If the pointer destination is a cast, see if we can fold the cast into the
6561 // source instead.
6562 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
6563 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
6564 return Res;
6565 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
6566 if (CE->getOpcode() == Instruction::Cast)
6567 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
6568 return Res;
6569
Chris Lattner408902b2005-09-12 23:23:25 +00006570
6571 // If this store is the last instruction in the basic block, and if the block
6572 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner9ca96412006-02-08 03:25:32 +00006573 BBI = &SI; ++BBI;
Chris Lattner408902b2005-09-12 23:23:25 +00006574 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
6575 if (BI->isUnconditional()) {
6576 // Check to see if the successor block has exactly two incoming edges. If
6577 // so, see if the other predecessor contains a store to the same location.
6578 // if so, insert a PHI node (if needed) and move the stores down.
6579 BasicBlock *Dest = BI->getSuccessor(0);
6580
6581 pred_iterator PI = pred_begin(Dest);
6582 BasicBlock *Other = 0;
6583 if (*PI != BI->getParent())
6584 Other = *PI;
6585 ++PI;
6586 if (PI != pred_end(Dest)) {
6587 if (*PI != BI->getParent())
6588 if (Other)
6589 Other = 0;
6590 else
6591 Other = *PI;
6592 if (++PI != pred_end(Dest))
6593 Other = 0;
6594 }
6595 if (Other) { // If only one other pred...
6596 BBI = Other->getTerminator();
6597 // Make sure this other block ends in an unconditional branch and that
6598 // there is an instruction before the branch.
6599 if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
6600 BBI != Other->begin()) {
6601 --BBI;
6602 StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
6603
6604 // If this instruction is a store to the same location.
6605 if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
6606 // Okay, we know we can perform this transformation. Insert a PHI
6607 // node now if we need it.
6608 Value *MergedVal = OtherStore->getOperand(0);
6609 if (MergedVal != SI.getOperand(0)) {
6610 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
6611 PN->reserveOperandSpace(2);
6612 PN->addIncoming(SI.getOperand(0), SI.getParent());
6613 PN->addIncoming(OtherStore->getOperand(0), Other);
6614 MergedVal = InsertNewInstBefore(PN, Dest->front());
6615 }
6616
6617 // Advance to a place where it is safe to insert the new store and
6618 // insert it.
6619 BBI = Dest->begin();
6620 while (isa<PHINode>(BBI)) ++BBI;
6621 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
6622 OtherStore->isVolatile()), *BBI);
6623
6624 // Nuke the old stores.
Chris Lattner9ca96412006-02-08 03:25:32 +00006625 EraseInstFromFunction(SI);
6626 EraseInstFromFunction(*OtherStore);
Chris Lattner408902b2005-09-12 23:23:25 +00006627 ++NumCombined;
6628 return 0;
6629 }
6630 }
6631 }
6632 }
6633
Chris Lattner2f503e62005-01-31 05:36:43 +00006634 return 0;
6635}
6636
6637
Chris Lattnerc4d10eb2003-06-04 04:46:00 +00006638Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
6639 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +00006640 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00006641 BasicBlock *TrueDest;
6642 BasicBlock *FalseDest;
6643 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
6644 !isa<Constant>(X)) {
6645 // Swap Destinations and condition...
6646 BI.setCondition(X);
6647 BI.setSuccessor(0, FalseDest);
6648 BI.setSuccessor(1, TrueDest);
6649 return &BI;
6650 }
6651
6652 // Cannonicalize setne -> seteq
6653 Instruction::BinaryOps Op; Value *Y;
6654 if (match(&BI, m_Br(m_SetCond(Op, m_Value(X), m_Value(Y)),
6655 TrueDest, FalseDest)))
6656 if ((Op == Instruction::SetNE || Op == Instruction::SetLE ||
6657 Op == Instruction::SetGE) && BI.getCondition()->hasOneUse()) {
6658 SetCondInst *I = cast<SetCondInst>(BI.getCondition());
6659 std::string Name = I->getName(); I->setName("");
6660 Instruction::BinaryOps NewOpcode = SetCondInst::getInverseCondition(Op);
6661 Value *NewSCC = BinaryOperator::create(NewOpcode, X, Y, Name, I);
Chris Lattner40f5d702003-06-04 05:10:11 +00006662 // Swap Destinations and condition...
Chris Lattneracd1f0f2004-07-30 07:50:03 +00006663 BI.setCondition(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +00006664 BI.setSuccessor(0, FalseDest);
6665 BI.setSuccessor(1, TrueDest);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00006666 removeFromWorkList(I);
6667 I->getParent()->getInstList().erase(I);
6668 WorkList.push_back(cast<Instruction>(NewSCC));
Chris Lattner40f5d702003-06-04 05:10:11 +00006669 return &BI;
6670 }
Misha Brukmanfd939082005-04-21 23:48:37 +00006671
Chris Lattnerc4d10eb2003-06-04 04:46:00 +00006672 return 0;
6673}
Chris Lattner0864acf2002-11-04 16:18:53 +00006674
Chris Lattner46238a62004-07-03 00:26:11 +00006675Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
6676 Value *Cond = SI.getCondition();
6677 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
6678 if (I->getOpcode() == Instruction::Add)
6679 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
6680 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
6681 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattnere87597f2004-10-16 18:11:37 +00006682 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +00006683 AddRHS));
6684 SI.setOperand(0, I->getOperand(0));
6685 WorkList.push_back(I);
6686 return &SI;
6687 }
6688 }
6689 return 0;
6690}
6691
Chris Lattner220b0cf2006-03-05 00:22:33 +00006692/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
6693/// is to leave as a vector operation.
6694static bool CheapToScalarize(Value *V, bool isConstant) {
6695 if (isa<ConstantAggregateZero>(V))
6696 return true;
6697 if (ConstantPacked *C = dyn_cast<ConstantPacked>(V)) {
6698 if (isConstant) return true;
6699 // If all elts are the same, we can extract.
6700 Constant *Op0 = C->getOperand(0);
6701 for (unsigned i = 1; i < C->getNumOperands(); ++i)
6702 if (C->getOperand(i) != Op0)
6703 return false;
6704 return true;
6705 }
6706 Instruction *I = dyn_cast<Instruction>(V);
6707 if (!I) return false;
6708
6709 // Insert element gets simplified to the inserted element or is deleted if
6710 // this is constant idx extract element and its a constant idx insertelt.
6711 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
6712 isa<ConstantInt>(I->getOperand(2)))
6713 return true;
6714 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
6715 return true;
6716 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
6717 if (BO->hasOneUse() &&
6718 (CheapToScalarize(BO->getOperand(0), isConstant) ||
6719 CheapToScalarize(BO->getOperand(1), isConstant)))
6720 return true;
6721
6722 return false;
6723}
6724
Chris Lattner6e6b0da2006-03-31 23:01:56 +00006725/// FindScalarElement - Given a vector and an element number, see if the scalar
6726/// value is already around as a register, for example if it were inserted then
6727/// extracted from the vector.
6728static Value *FindScalarElement(Value *V, unsigned EltNo) {
6729 assert(isa<PackedType>(V->getType()) && "Not looking at a vector?");
6730 const PackedType *PTy = cast<PackedType>(V->getType());
6731 if (EltNo >= PTy->getNumElements()) // Out of range access.
6732 return UndefValue::get(PTy->getElementType());
6733
6734 if (isa<UndefValue>(V))
6735 return UndefValue::get(PTy->getElementType());
6736 else if (isa<ConstantAggregateZero>(V))
6737 return Constant::getNullValue(PTy->getElementType());
6738 else if (ConstantPacked *CP = dyn_cast<ConstantPacked>(V))
6739 return CP->getOperand(EltNo);
6740 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
6741 // If this is an insert to a variable element, we don't know what it is.
6742 if (!isa<ConstantUInt>(III->getOperand(2))) return 0;
6743 unsigned IIElt = cast<ConstantUInt>(III->getOperand(2))->getValue();
6744
6745 // If this is an insert to the element we are looking for, return the
6746 // inserted value.
6747 if (EltNo == IIElt) return III->getOperand(1);
6748
6749 // Otherwise, the insertelement doesn't modify the value, recurse on its
6750 // vector input.
6751 return FindScalarElement(III->getOperand(0), EltNo);
6752 }
6753
6754 // Otherwise, we don't know.
6755 return 0;
6756}
6757
Robert Bocchino1d7456d2006-01-13 22:48:06 +00006758Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Chris Lattner6e6b0da2006-03-31 23:01:56 +00006759
Chris Lattner1f13c882006-03-31 18:25:14 +00006760 // If packed val is undef, replace extract with scalar undef.
6761 if (isa<UndefValue>(EI.getOperand(0)))
6762 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
6763
6764 // If packed val is constant 0, replace extract with scalar 0.
6765 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
6766 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
6767
Robert Bocchino1d7456d2006-01-13 22:48:06 +00006768 if (ConstantPacked *C = dyn_cast<ConstantPacked>(EI.getOperand(0))) {
6769 // If packed val is constant with uniform operands, replace EI
6770 // with that operand
Chris Lattner220b0cf2006-03-05 00:22:33 +00006771 Constant *op0 = C->getOperand(0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +00006772 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +00006773 if (C->getOperand(i) != op0) {
6774 op0 = 0;
6775 break;
6776 }
6777 if (op0)
6778 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +00006779 }
Chris Lattner220b0cf2006-03-05 00:22:33 +00006780
Chris Lattner6e6b0da2006-03-31 23:01:56 +00006781 // If extracting a specified index from the vector, see if we can recursively
6782 // find a previously computed scalar that was inserted into the vector.
6783 if (ConstantUInt *IdxC = dyn_cast<ConstantUInt>(EI.getOperand(1)))
6784 if (Value *Elt = FindScalarElement(EI.getOperand(0), IdxC->getValue()))
6785 return ReplaceInstUsesWith(EI, Elt);
6786
Robert Bocchino1d7456d2006-01-13 22:48:06 +00006787 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0)))
6788 if (I->hasOneUse()) {
6789 // Push extractelement into predecessor operation if legal and
6790 // profitable to do so
6791 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +00006792 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
6793 if (CheapToScalarize(BO, isConstantElt)) {
6794 ExtractElementInst *newEI0 =
6795 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
6796 EI.getName()+".lhs");
6797 ExtractElementInst *newEI1 =
6798 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
6799 EI.getName()+".rhs");
6800 InsertNewInstBefore(newEI0, EI);
6801 InsertNewInstBefore(newEI1, EI);
6802 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
6803 }
6804 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Robert Bocchino1d7456d2006-01-13 22:48:06 +00006805 Value *Ptr = InsertCastBefore(I->getOperand(0),
6806 PointerType::get(EI.getType()), EI);
6807 GetElementPtrInst *GEP =
6808 new GetElementPtrInst(Ptr, EI.getOperand(1),
6809 I->getName() + ".gep");
6810 InsertNewInstBefore(GEP, EI);
6811 return new LoadInst(GEP);
Chris Lattner220b0cf2006-03-05 00:22:33 +00006812 } else if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
6813 // Extracting the inserted element?
6814 if (IE->getOperand(2) == EI.getOperand(1))
6815 return ReplaceInstUsesWith(EI, IE->getOperand(1));
6816 // If the inserted and extracted elements are constants, they must not
Chris Lattnerdf084ff2006-03-30 22:02:40 +00006817 // be the same value, extract from the pre-inserted value instead.
6818 if (isa<Constant>(IE->getOperand(2)) &&
6819 isa<Constant>(EI.getOperand(1))) {
6820 AddUsesToWorkList(EI);
6821 EI.setOperand(0, IE->getOperand(0));
6822 return &EI;
6823 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +00006824 }
6825 }
6826 return 0;
6827}
6828
6829
Chris Lattner62b14df2002-09-02 04:59:56 +00006830void InstCombiner::removeFromWorkList(Instruction *I) {
6831 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
6832 WorkList.end());
6833}
6834
Chris Lattnerea1c4542004-12-08 23:43:58 +00006835
6836/// TryToSinkInstruction - Try to move the specified instruction from its
6837/// current block into the beginning of DestBlock, which can only happen if it's
6838/// safe to move the instruction past all of the instructions between it and the
6839/// end of its block.
6840static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
6841 assert(I->hasOneUse() && "Invariants didn't hold!");
6842
Chris Lattner108e9022005-10-27 17:13:11 +00006843 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
6844 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
Misha Brukmanfd939082005-04-21 23:48:37 +00006845
Chris Lattnerea1c4542004-12-08 23:43:58 +00006846 // Do not sink alloca instructions out of the entry block.
6847 if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
6848 return false;
6849
Chris Lattner96a52a62004-12-09 07:14:34 +00006850 // We can only sink load instructions if there is nothing between the load and
6851 // the end of block that could change the value.
6852 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattner96a52a62004-12-09 07:14:34 +00006853 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
6854 Scan != E; ++Scan)
6855 if (Scan->mayWriteToMemory())
6856 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +00006857 }
Chris Lattnerea1c4542004-12-08 23:43:58 +00006858
6859 BasicBlock::iterator InsertPos = DestBlock->begin();
6860 while (isa<PHINode>(InsertPos)) ++InsertPos;
6861
Chris Lattner4bc5f802005-08-08 19:11:57 +00006862 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +00006863 ++NumSunkInst;
6864 return true;
6865}
6866
Chris Lattner7e708292002-06-25 16:13:24 +00006867bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerdd841ae2002-04-18 17:39:14 +00006868 bool Changed = false;
Chris Lattnerbc61e662003-11-02 05:57:39 +00006869 TD = &getAnalysis<TargetData>();
Chris Lattner8a2a3112001-12-14 16:52:21 +00006870
Chris Lattnerb3d59702005-07-07 20:40:38 +00006871 {
6872 // Populate the worklist with the reachable instructions.
6873 std::set<BasicBlock*> Visited;
6874 for (df_ext_iterator<BasicBlock*> BB = df_ext_begin(&F.front(), Visited),
6875 E = df_ext_end(&F.front(), Visited); BB != E; ++BB)
6876 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
6877 WorkList.push_back(I);
Jeff Cohen00b168892005-07-27 06:12:32 +00006878
Chris Lattnerb3d59702005-07-07 20:40:38 +00006879 // Do a quick scan over the function. If we find any blocks that are
6880 // unreachable, remove any instructions inside of them. This prevents
6881 // the instcombine code from having to deal with some bad special cases.
6882 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
6883 if (!Visited.count(BB)) {
6884 Instruction *Term = BB->getTerminator();
6885 while (Term != BB->begin()) { // Remove instrs bottom-up
6886 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +00006887
Chris Lattnerb3d59702005-07-07 20:40:38 +00006888 DEBUG(std::cerr << "IC: DCE: " << *I);
6889 ++NumDeadInst;
6890
6891 if (!I->use_empty())
6892 I->replaceAllUsesWith(UndefValue::get(I->getType()));
6893 I->eraseFromParent();
6894 }
6895 }
6896 }
Chris Lattner8a2a3112001-12-14 16:52:21 +00006897
6898 while (!WorkList.empty()) {
6899 Instruction *I = WorkList.back(); // Get an instruction from the worklist
6900 WorkList.pop_back();
6901
Misha Brukmana3bbcb52002-10-29 23:06:16 +00006902 // Check to see if we can DCE or ConstantPropagate the instruction...
Chris Lattner62b14df2002-09-02 04:59:56 +00006903 // Check to see if we can DIE the instruction...
6904 if (isInstructionTriviallyDead(I)) {
6905 // Add operands to the worklist...
Chris Lattner4bb7c022003-10-06 17:11:01 +00006906 if (I->getNumOperands() < 4)
Chris Lattner7bcc0e72004-02-28 05:22:00 +00006907 AddUsesToWorkList(*I);
Chris Lattner62b14df2002-09-02 04:59:56 +00006908 ++NumDeadInst;
Chris Lattner4bb7c022003-10-06 17:11:01 +00006909
Chris Lattnerad5fec12005-01-28 19:32:01 +00006910 DEBUG(std::cerr << "IC: DCE: " << *I);
6911
6912 I->eraseFromParent();
Chris Lattner4bb7c022003-10-06 17:11:01 +00006913 removeFromWorkList(I);
6914 continue;
6915 }
Chris Lattner62b14df2002-09-02 04:59:56 +00006916
Misha Brukmana3bbcb52002-10-29 23:06:16 +00006917 // Instruction isn't dead, see if we can constant propagate it...
Chris Lattner62b14df2002-09-02 04:59:56 +00006918 if (Constant *C = ConstantFoldInstruction(I)) {
Alkis Evlogimenos54a96a22004-12-08 23:10:30 +00006919 Value* Ptr = I->getOperand(0);
Chris Lattner061718c2004-10-16 19:44:59 +00006920 if (isa<GetElementPtrInst>(I) &&
Alkis Evlogimenos54a96a22004-12-08 23:10:30 +00006921 cast<Constant>(Ptr)->isNullValue() &&
6922 !isa<ConstantPointerNull>(C) &&
6923 cast<PointerType>(Ptr->getType())->getElementType()->isSized()) {
Chris Lattner061718c2004-10-16 19:44:59 +00006924 // If this is a constant expr gep that is effectively computing an
6925 // "offsetof", fold it into 'cast int X to T*' instead of 'gep 0, 0, 12'
6926 bool isFoldableGEP = true;
6927 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i)
6928 if (!isa<ConstantInt>(I->getOperand(i)))
6929 isFoldableGEP = false;
6930 if (isFoldableGEP) {
Alkis Evlogimenos54a96a22004-12-08 23:10:30 +00006931 uint64_t Offset = TD->getIndexedOffset(Ptr->getType(),
Chris Lattner061718c2004-10-16 19:44:59 +00006932 std::vector<Value*>(I->op_begin()+1, I->op_end()));
6933 C = ConstantUInt::get(Type::ULongTy, Offset);
Chris Lattner6e758ae2004-10-16 19:46:33 +00006934 C = ConstantExpr::getCast(C, TD->getIntPtrType());
Chris Lattner061718c2004-10-16 19:44:59 +00006935 C = ConstantExpr::getCast(C, I->getType());
6936 }
6937 }
6938
Chris Lattnerad5fec12005-01-28 19:32:01 +00006939 DEBUG(std::cerr << "IC: ConstFold to: " << *C << " from: " << *I);
6940
Chris Lattner62b14df2002-09-02 04:59:56 +00006941 // Add operands to the worklist...
Chris Lattner7bcc0e72004-02-28 05:22:00 +00006942 AddUsesToWorkList(*I);
Chris Lattnerc736d562002-12-05 22:41:53 +00006943 ReplaceInstUsesWith(*I, C);
6944
Chris Lattner62b14df2002-09-02 04:59:56 +00006945 ++NumConstProp;
Chris Lattner4bb7c022003-10-06 17:11:01 +00006946 I->getParent()->getInstList().erase(I);
Chris Lattner60610002003-10-07 15:17:02 +00006947 removeFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +00006948 continue;
Chris Lattner62b14df2002-09-02 04:59:56 +00006949 }
Chris Lattner4bb7c022003-10-06 17:11:01 +00006950
Chris Lattnerea1c4542004-12-08 23:43:58 +00006951 // See if we can trivially sink this instruction to a successor basic block.
6952 if (I->hasOneUse()) {
6953 BasicBlock *BB = I->getParent();
6954 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
6955 if (UserParent != BB) {
6956 bool UserIsSuccessor = false;
6957 // See if the user is one of our successors.
6958 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
6959 if (*SI == UserParent) {
6960 UserIsSuccessor = true;
6961 break;
6962 }
6963
6964 // If the user is one of our immediate successors, and if that successor
6965 // only has us as a predecessors (we'd have to split the critical edge
6966 // otherwise), we can keep going.
6967 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
6968 next(pred_begin(UserParent)) == pred_end(UserParent))
6969 // Okay, the CFG is simple enough, try to sink this instruction.
6970 Changed |= TryToSinkInstruction(I, UserParent);
6971 }
6972 }
6973
Chris Lattner8a2a3112001-12-14 16:52:21 +00006974 // Now that we have an instruction, try combining it to simplify it...
Chris Lattner90ac28c2002-08-02 19:29:35 +00006975 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +00006976 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00006977 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +00006978 if (Result != I) {
Chris Lattner0cea42a2004-03-13 23:54:27 +00006979 DEBUG(std::cerr << "IC: Old = " << *I
6980 << " New = " << *Result);
6981
Chris Lattnerf523d062004-06-09 05:08:07 +00006982 // Everything uses the new instruction now.
6983 I->replaceAllUsesWith(Result);
6984
6985 // Push the new instruction and any users onto the worklist.
6986 WorkList.push_back(Result);
6987 AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +00006988
6989 // Move the name to the new instruction first...
6990 std::string OldName = I->getName(); I->setName("");
Chris Lattnerd558dc32003-10-07 22:58:41 +00006991 Result->setName(OldName);
Chris Lattner4bb7c022003-10-06 17:11:01 +00006992
6993 // Insert the new instruction into the basic block...
6994 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +00006995 BasicBlock::iterator InsertPos = I;
6996
6997 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
6998 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
6999 ++InsertPos;
7000
7001 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +00007002
Chris Lattner00d51312004-05-01 23:27:23 +00007003 // Make sure that we reprocess all operands now that we reduced their
7004 // use counts.
Chris Lattner216d4d82004-05-01 23:19:52 +00007005 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
7006 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
7007 WorkList.push_back(OpI);
7008
Chris Lattnerf523d062004-06-09 05:08:07 +00007009 // Instructions can end up on the worklist more than once. Make sure
7010 // we do not process an instruction that has been deleted.
7011 removeFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +00007012
7013 // Erase the old instruction.
7014 InstParent->getInstList().erase(I);
Chris Lattner7e708292002-06-25 16:13:24 +00007015 } else {
Chris Lattner0cea42a2004-03-13 23:54:27 +00007016 DEBUG(std::cerr << "IC: MOD = " << *I);
7017
Chris Lattner90ac28c2002-08-02 19:29:35 +00007018 // If the instruction was modified, it's possible that it is now dead.
7019 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +00007020 if (isInstructionTriviallyDead(I)) {
7021 // Make sure we process all operands now that we are reducing their
7022 // use counts.
7023 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
7024 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
7025 WorkList.push_back(OpI);
Misha Brukmanfd939082005-04-21 23:48:37 +00007026
Chris Lattner00d51312004-05-01 23:27:23 +00007027 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchino1d7456d2006-01-13 22:48:06 +00007028 // occurrences of this instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +00007029 removeFromWorkList(I);
Chris Lattner2f503e62005-01-31 05:36:43 +00007030 I->eraseFromParent();
Chris Lattnerf523d062004-06-09 05:08:07 +00007031 } else {
7032 WorkList.push_back(Result);
7033 AddUsersToWorkList(*Result);
Chris Lattner90ac28c2002-08-02 19:29:35 +00007034 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +00007035 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00007036 Changed = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +00007037 }
7038 }
7039
Chris Lattnerdd841ae2002-04-18 17:39:14 +00007040 return Changed;
Chris Lattnerbd0ef772002-02-26 21:46:54 +00007041}
7042
Brian Gaeke96d4bf72004-07-27 17:43:21 +00007043FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +00007044 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +00007045}
Brian Gaeked0fde302003-11-11 22:41:34 +00007046