blob: d3a625b8bc113cd2f527b56f9cd5eb13ede0b7f2 [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 Lattnera4f0b3a2006-08-27 12:54:02 +000051#include "llvm/Support/Compiler.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 Lattnerf4b54612006-06-28 22:08:15 +000066 class VISIBILITY_HIDDEN InstCombiner
67 : public FunctionPass,
68 public InstVisitor<InstCombiner, Instruction*> {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000069 // Worklist of all of the instructions that need to be simplified.
70 std::vector<Instruction*> WorkList;
Chris Lattnerbc61e662003-11-02 05:57:39 +000071 TargetData *TD;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000072
Chris Lattner7bcc0e72004-02-28 05:22:00 +000073 /// AddUsersToWorkList - When an instruction is simplified, add all users of
74 /// the instruction to the work lists because they might get more simplified
75 /// now.
76 ///
Chris Lattner6dce1a72006-02-07 06:56:34 +000077 void AddUsersToWorkList(Value &I) {
Chris Lattner7e708292002-06-25 16:13:24 +000078 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattnerdd841ae2002-04-18 17:39:14 +000079 UI != UE; ++UI)
80 WorkList.push_back(cast<Instruction>(*UI));
81 }
82
Chris Lattner7bcc0e72004-02-28 05:22:00 +000083 /// AddUsesToWorkList - When an instruction is simplified, add operands to
84 /// the work lists because they might get more simplified now.
85 ///
86 void AddUsesToWorkList(Instruction &I) {
87 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
88 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
89 WorkList.push_back(Op);
90 }
Chris Lattner867b99f2006-10-05 06:55:50 +000091
92 /// AddSoonDeadInstToWorklist - The specified instruction is about to become
93 /// dead. Add all of its operands to the worklist, turning them into
94 /// undef's to reduce the number of uses of those instructions.
95 ///
96 /// Return the specified operand before it is turned into an undef.
97 ///
98 Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
99 Value *R = I.getOperand(op);
100
101 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
102 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i))) {
103 WorkList.push_back(Op);
104 // Set the operand to undef to drop the use.
105 I.setOperand(i, UndefValue::get(Op->getType()));
106 }
107
108 return R;
109 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000110
Chris Lattner62b14df2002-09-02 04:59:56 +0000111 // removeFromWorkList - remove all instances of I from the worklist.
112 void removeFromWorkList(Instruction *I);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000113 public:
Chris Lattner7e708292002-06-25 16:13:24 +0000114 virtual bool runOnFunction(Function &F);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000115
Chris Lattner97e52e42002-04-28 21:27:06 +0000116 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerbc61e662003-11-02 05:57:39 +0000117 AU.addRequired<TargetData>();
Owen Andersond1b78a12006-07-10 19:03:49 +0000118 AU.addPreservedID(LCSSAID);
Chris Lattnercb2610e2002-10-21 20:00:28 +0000119 AU.setPreservesCFG();
Chris Lattner97e52e42002-04-28 21:27:06 +0000120 }
121
Chris Lattner28977af2004-04-05 01:30:19 +0000122 TargetData &getTargetData() const { return *TD; }
123
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000124 // Visitation implementation - Implement instruction combining for different
125 // instruction types. The semantics are as follows:
126 // Return Value:
127 // null - No change was made
Chris Lattner233f7dc2002-08-12 21:17:25 +0000128 // I - Change was made, I is still valid, I may be dead though
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000129 // otherwise - Change was made, replace I with returned instruction
Misha Brukmanfd939082005-04-21 23:48:37 +0000130 //
Chris Lattner7e708292002-06-25 16:13:24 +0000131 Instruction *visitAdd(BinaryOperator &I);
132 Instruction *visitSub(BinaryOperator &I);
133 Instruction *visitMul(BinaryOperator &I);
Reid Spencer0a783f72006-11-02 01:53:59 +0000134 Instruction *visitURem(BinaryOperator &I);
135 Instruction *visitSRem(BinaryOperator &I);
136 Instruction *visitFRem(BinaryOperator &I);
137 Instruction *commonRemTransforms(BinaryOperator &I);
138 Instruction *commonIRemTransforms(BinaryOperator &I);
Reid Spencer1628cec2006-10-26 06:15:43 +0000139 Instruction *commonDivTransforms(BinaryOperator &I);
140 Instruction *commonIDivTransforms(BinaryOperator &I);
141 Instruction *visitUDiv(BinaryOperator &I);
142 Instruction *visitSDiv(BinaryOperator &I);
143 Instruction *visitFDiv(BinaryOperator &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000144 Instruction *visitAnd(BinaryOperator &I);
145 Instruction *visitOr (BinaryOperator &I);
146 Instruction *visitXor(BinaryOperator &I);
Chris Lattner484d3cf2005-04-24 06:59:08 +0000147 Instruction *visitSetCondInst(SetCondInst &I);
148 Instruction *visitSetCondInstWithCastAndCast(SetCondInst &SCI);
149
Chris Lattner574da9b2005-01-13 20:14:25 +0000150 Instruction *FoldGEPSetCC(User *GEPLHS, Value *RHS,
151 Instruction::BinaryOps Cond, Instruction &I);
Chris Lattnerea340052003-03-10 19:16:08 +0000152 Instruction *visitShiftInst(ShiftInst &I);
Reid Spencerb83eb642006-10-20 07:07:24 +0000153 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Chris Lattner4d5542c2006-01-06 07:12:35 +0000154 ShiftInst &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000155 Instruction *visitCastInst(CastInst &CI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +0000156 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
157 Instruction *FI);
Chris Lattner3d69f462004-03-12 05:52:32 +0000158 Instruction *visitSelectInst(SelectInst &CI);
Chris Lattner9fe38862003-06-19 17:00:31 +0000159 Instruction *visitCallInst(CallInst &CI);
160 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner7e708292002-06-25 16:13:24 +0000161 Instruction *visitPHINode(PHINode &PN);
162 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner0864acf2002-11-04 16:18:53 +0000163 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner67b1e1b2003-12-07 01:24:23 +0000164 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner833b8a42003-06-26 05:06:25 +0000165 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner2f503e62005-01-31 05:36:43 +0000166 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattnerc4d10eb2003-06-04 04:46:00 +0000167 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner46238a62004-07-03 00:26:11 +0000168 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattnerefb47352006-04-15 01:39:45 +0000169 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchino1d7456d2006-01-13 22:48:06 +0000170 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +0000171 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000172
173 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner7e708292002-06-25 16:13:24 +0000174 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner8b170942002-08-09 23:47:40 +0000175
Chris Lattner9fe38862003-06-19 17:00:31 +0000176 private:
Chris Lattnera44d8a22003-10-07 22:32:43 +0000177 Instruction *visitCallSite(CallSite CS);
Chris Lattner9fe38862003-06-19 17:00:31 +0000178 bool transformConstExprCastCall(CallSite CS);
179
Chris Lattner28977af2004-04-05 01:30:19 +0000180 public:
Chris Lattner8b170942002-08-09 23:47:40 +0000181 // InsertNewInstBefore - insert an instruction New before instruction Old
182 // in the program. Add the new instruction to the worklist.
183 //
Chris Lattner955f3312004-09-28 21:48:02 +0000184 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattnere6f9a912002-08-23 18:32:43 +0000185 assert(New && New->getParent() == 0 &&
186 "New instruction already inserted into a basic block!");
Chris Lattner8b170942002-08-09 23:47:40 +0000187 BasicBlock *BB = Old.getParent();
188 BB->getInstList().insert(&Old, New); // Insert inst
189 WorkList.push_back(New); // Add to worklist
Chris Lattner4cb170c2004-02-23 06:38:22 +0000190 return New;
Chris Lattner8b170942002-08-09 23:47:40 +0000191 }
192
Chris Lattner0c967662004-09-24 15:21:34 +0000193 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
194 /// This also adds the cast to the worklist. Finally, this returns the
195 /// cast.
196 Value *InsertCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
197 if (V->getType() == Ty) return V;
Misha Brukmanfd939082005-04-21 23:48:37 +0000198
Chris Lattnere2ed0572006-04-06 19:19:17 +0000199 if (Constant *CV = dyn_cast<Constant>(V))
200 return ConstantExpr::getCast(CV, Ty);
201
Chris Lattner0c967662004-09-24 15:21:34 +0000202 Instruction *C = new CastInst(V, Ty, V->getName(), &Pos);
203 WorkList.push_back(C);
204 return C;
205 }
206
Chris Lattner8b170942002-08-09 23:47:40 +0000207 // ReplaceInstUsesWith - This method is to be used when an instruction is
208 // found to be dead, replacable with another preexisting expression. Here
209 // we add all uses of I to the worklist, replace all uses of I with the new
210 // value, then return I, so that the inst combiner will know that I was
211 // modified.
212 //
213 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000214 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner15a76c02004-04-05 02:10:19 +0000215 if (&I != V) {
216 I.replaceAllUsesWith(V);
217 return &I;
218 } else {
219 // If we are replacing the instruction with itself, this must be in a
220 // segment of unreachable code, so just clobber the instruction.
Chris Lattner17be6352004-10-18 02:59:09 +0000221 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +0000222 return &I;
223 }
Chris Lattner8b170942002-08-09 23:47:40 +0000224 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000225
Chris Lattner6dce1a72006-02-07 06:56:34 +0000226 // UpdateValueUsesWith - This method is to be used when an value is
227 // found to be replacable with another preexisting expression or was
228 // updated. Here we add all uses of I to the worklist, replace all uses of
229 // I with the new value (unless the instruction was just updated), then
230 // return true, so that the inst combiner will know that I was modified.
231 //
232 bool UpdateValueUsesWith(Value *Old, Value *New) {
233 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
234 if (Old != New)
235 Old->replaceAllUsesWith(New);
236 if (Instruction *I = dyn_cast<Instruction>(Old))
237 WorkList.push_back(I);
Chris Lattnerf8c36f52006-02-12 08:02:11 +0000238 if (Instruction *I = dyn_cast<Instruction>(New))
239 WorkList.push_back(I);
Chris Lattner6dce1a72006-02-07 06:56:34 +0000240 return true;
241 }
242
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000243 // EraseInstFromFunction - When dealing with an instruction that has side
244 // effects or produces a void value, we can't rely on DCE to delete the
245 // instruction. Instead, visit methods should return the value returned by
246 // this function.
247 Instruction *EraseInstFromFunction(Instruction &I) {
248 assert(I.use_empty() && "Cannot erase instruction that is used!");
249 AddUsesToWorkList(I);
250 removeFromWorkList(&I);
Chris Lattner954f66a2004-11-18 21:41:39 +0000251 I.eraseFromParent();
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000252 return 0; // Don't do anything with FI
253 }
254
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000255 private:
Chris Lattner24c8e382003-07-24 17:35:25 +0000256 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
257 /// InsertBefore instruction. This is specialized a bit to avoid inserting
258 /// casts that are known to not do anything...
259 ///
260 Value *InsertOperandCastBefore(Value *V, const Type *DestTy,
261 Instruction *InsertBefore);
262
Chris Lattnerc8802d22003-03-11 00:12:48 +0000263 // SimplifyCommutative - This performs a few simplifications for commutative
Chris Lattner4e998b22004-09-29 05:07:12 +0000264 // operators.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000265 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000266
Chris Lattner255d8912006-02-11 09:31:47 +0000267 bool SimplifyDemandedBits(Value *V, uint64_t Mask,
268 uint64_t &KnownZero, uint64_t &KnownOne,
269 unsigned Depth = 0);
Chris Lattner4e998b22004-09-29 05:07:12 +0000270
Chris Lattner867b99f2006-10-05 06:55:50 +0000271 Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
272 uint64_t &UndefElts, unsigned Depth = 0);
273
Chris Lattner4e998b22004-09-29 05:07:12 +0000274 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
275 // PHI node as operand #0, see if we can fold the instruction into the PHI
276 // (which is only possible if all operands to the PHI are constants).
277 Instruction *FoldOpIntoPhi(Instruction &I);
278
Chris Lattnerbac32862004-11-14 19:13:23 +0000279 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
280 // operator and they all are only used by the PHI, PHI together their
281 // inputs, and do the operation once, to the result of the PHI.
282 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
Chris Lattner7da52b22006-11-01 04:51:18 +0000283 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
284
285
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000286 Instruction *OptAndOp(Instruction *Op, ConstantIntegral *OpRHS,
287 ConstantIntegral *AndRHS, BinaryOperator &TheAnd);
Chris Lattnerc8e77562005-09-18 04:24:45 +0000288
289 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantIntegral *Mask,
290 bool isSub, Instruction &I);
Chris Lattnera96879a2004-09-29 17:40:11 +0000291 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
292 bool Inside, Instruction &IB);
Chris Lattnerb3f83972005-10-24 06:03:58 +0000293 Instruction *PromoteCastOfAllocation(CastInst &CI, AllocationInst &AI);
Chris Lattnerafe91a52006-06-15 19:07:26 +0000294 Instruction *MatchBSwap(BinaryOperator &I);
295
Chris Lattner70074e02006-05-13 02:06:03 +0000296 Value *EvaluateInDifferentType(Value *V, const Type *Ty);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000297 };
Chris Lattnerf6293092002-07-23 18:06:35 +0000298
Chris Lattner7f8897f2006-08-27 22:42:52 +0000299 RegisterPass<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000300}
301
Chris Lattner4f98c562003-03-10 21:43:22 +0000302// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattnere87597f2004-10-16 18:11:37 +0000303// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattner4f98c562003-03-10 21:43:22 +0000304static unsigned getComplexity(Value *V) {
305 if (isa<Instruction>(V)) {
306 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattnere87597f2004-10-16 18:11:37 +0000307 return 3;
308 return 4;
Chris Lattner4f98c562003-03-10 21:43:22 +0000309 }
Chris Lattnere87597f2004-10-16 18:11:37 +0000310 if (isa<Argument>(V)) return 3;
311 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattner4f98c562003-03-10 21:43:22 +0000312}
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000313
Chris Lattnerc8802d22003-03-11 00:12:48 +0000314// isOnlyUse - Return true if this instruction will be deleted if we stop using
315// it.
316static bool isOnlyUse(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000317 return V->hasOneUse() || isa<Constant>(V);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000318}
319
Chris Lattner4cb170c2004-02-23 06:38:22 +0000320// getPromotedType - Return the specified type promoted as it would be to pass
321// though a va_arg area...
322static const Type *getPromotedType(const Type *Ty) {
Chris Lattner5dd04022004-06-17 18:16:02 +0000323 switch (Ty->getTypeID()) {
Chris Lattner4cb170c2004-02-23 06:38:22 +0000324 case Type::SByteTyID:
325 case Type::ShortTyID: return Type::IntTy;
326 case Type::UByteTyID:
327 case Type::UShortTyID: return Type::UIntTy;
328 case Type::FloatTyID: return Type::DoubleTy;
329 default: return Ty;
330 }
331}
332
Chris Lattnereed48272005-09-13 00:40:14 +0000333/// isCast - If the specified operand is a CastInst or a constant expr cast,
334/// return the operand value, otherwise return null.
335static Value *isCast(Value *V) {
336 if (CastInst *I = dyn_cast<CastInst>(V))
337 return I->getOperand(0);
338 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
339 if (CE->getOpcode() == Instruction::Cast)
340 return CE->getOperand(0);
341 return 0;
342}
343
Chris Lattner33a61132006-05-06 09:00:16 +0000344enum CastType {
345 Noop = 0,
346 Truncate = 1,
347 Signext = 2,
348 Zeroext = 3
349};
350
351/// getCastType - In the future, we will split the cast instruction into these
352/// various types. Until then, we have to do the analysis here.
353static CastType getCastType(const Type *Src, const Type *Dest) {
354 assert(Src->isIntegral() && Dest->isIntegral() &&
355 "Only works on integral types!");
356 unsigned SrcSize = Src->getPrimitiveSizeInBits();
357 unsigned DestSize = Dest->getPrimitiveSizeInBits();
358
359 if (SrcSize == DestSize) return Noop;
360 if (SrcSize > DestSize) return Truncate;
361 if (Src->isSigned()) return Signext;
362 return Zeroext;
363}
364
365
366// isEliminableCastOfCast - Return true if it is valid to eliminate the CI
367// instruction.
368//
369static bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
370 const Type *DstTy, TargetData *TD) {
371
372 // It is legal to eliminate the instruction if casting A->B->A if the sizes
373 // are identical and the bits don't get reinterpreted (for example
374 // int->float->int would not be allowed).
375 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
376 return true;
377
378 // If we are casting between pointer and integer types, treat pointers as
379 // integers of the appropriate size for the code below.
380 if (isa<PointerType>(SrcTy)) SrcTy = TD->getIntPtrType();
381 if (isa<PointerType>(MidTy)) MidTy = TD->getIntPtrType();
382 if (isa<PointerType>(DstTy)) DstTy = TD->getIntPtrType();
383
384 // Allow free casting and conversion of sizes as long as the sign doesn't
385 // change...
386 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
387 CastType FirstCast = getCastType(SrcTy, MidTy);
388 CastType SecondCast = getCastType(MidTy, DstTy);
389
390 // Capture the effect of these two casts. If the result is a legal cast,
391 // the CastType is stored here, otherwise a special code is used.
392 static const unsigned CastResult[] = {
393 // First cast is noop
394 0, 1, 2, 3,
395 // First cast is a truncate
396 1, 1, 4, 4, // trunc->extend is not safe to eliminate
397 // First cast is a sign ext
398 2, 5, 2, 4, // signext->zeroext never ok
399 // First cast is a zero ext
400 3, 5, 3, 3,
401 };
402
403 unsigned Result = CastResult[FirstCast*4+SecondCast];
404 switch (Result) {
405 default: assert(0 && "Illegal table value!");
406 case 0:
407 case 1:
408 case 2:
409 case 3:
410 // FIXME: in the future, when LLVM has explicit sign/zeroextends and
411 // truncates, we could eliminate more casts.
412 return (unsigned)getCastType(SrcTy, DstTy) == Result;
413 case 4:
414 return false; // Not possible to eliminate this here.
415 case 5:
416 // Sign or zero extend followed by truncate is always ok if the result
417 // is a truncate or noop.
418 CastType ResultCast = getCastType(SrcTy, DstTy);
419 if (ResultCast == Noop || ResultCast == Truncate)
420 return true;
421 // Otherwise we are still growing the value, we are only safe if the
422 // result will match the sign/zeroextendness of the result.
423 return ResultCast == FirstCast;
424 }
425 }
426
427 // If this is a cast from 'float -> double -> integer', cast from
428 // 'float -> integer' directly, as the value isn't changed by the
429 // float->double conversion.
430 if (SrcTy->isFloatingPoint() && MidTy->isFloatingPoint() &&
431 DstTy->isIntegral() &&
432 SrcTy->getPrimitiveSize() < MidTy->getPrimitiveSize())
433 return true;
434
435 // Packed type conversions don't modify bits.
436 if (isa<PackedType>(SrcTy) && isa<PackedType>(MidTy) &&isa<PackedType>(DstTy))
437 return true;
438
439 return false;
440}
441
442/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
443/// in any code being generated. It does not require codegen if V is simple
444/// enough or if the cast can be folded into other casts.
445static bool ValueRequiresCast(const Value *V, const Type *Ty, TargetData *TD) {
446 if (V->getType() == Ty || isa<Constant>(V)) return false;
447
448 // If this is a noop cast, it isn't real codegen.
449 if (V->getType()->isLosslesslyConvertibleTo(Ty))
450 return false;
451
Chris Lattner01575b72006-05-25 23:24:33 +0000452 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner33a61132006-05-06 09:00:16 +0000453 if (const CastInst *CI = dyn_cast<CastInst>(V))
454 if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty,
455 TD))
456 return false;
457 return true;
458}
459
460/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
461/// InsertBefore instruction. This is specialized a bit to avoid inserting
462/// casts that are known to not do anything...
463///
464Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
465 Instruction *InsertBefore) {
466 if (V->getType() == DestTy) return V;
467 if (Constant *C = dyn_cast<Constant>(V))
468 return ConstantExpr::getCast(C, DestTy);
469
Reid Spencer811b0cb2006-10-26 19:19:06 +0000470 return InsertCastBefore(V, DestTy, *InsertBefore);
Chris Lattner33a61132006-05-06 09:00:16 +0000471}
472
Chris Lattner4f98c562003-03-10 21:43:22 +0000473// SimplifyCommutative - This performs a few simplifications for commutative
474// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000475//
Chris Lattner4f98c562003-03-10 21:43:22 +0000476// 1. Order operands such that they are listed from right (least complex) to
477// left (most complex). This puts constants before unary operators before
478// binary operators.
479//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000480// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
481// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000482//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000483bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000484 bool Changed = false;
485 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
486 Changed = !I.swapOperands();
Misha Brukmanfd939082005-04-21 23:48:37 +0000487
Chris Lattner4f98c562003-03-10 21:43:22 +0000488 if (!I.isAssociative()) return Changed;
489 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000490 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
491 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
492 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner2a9c8472003-05-27 16:40:51 +0000493 Constant *Folded = ConstantExpr::get(I.getOpcode(),
494 cast<Constant>(I.getOperand(1)),
495 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000496 I.setOperand(0, Op->getOperand(0));
497 I.setOperand(1, Folded);
498 return true;
499 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
500 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
501 isOnlyUse(Op) && isOnlyUse(Op1)) {
502 Constant *C1 = cast<Constant>(Op->getOperand(1));
503 Constant *C2 = cast<Constant>(Op1->getOperand(1));
504
505 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner2a9c8472003-05-27 16:40:51 +0000506 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000507 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
508 Op1->getOperand(0),
509 Op1->getName(), &I);
510 WorkList.push_back(New);
511 I.setOperand(0, New);
512 I.setOperand(1, Folded);
513 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000514 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000515 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000516 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000517}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000518
Chris Lattner8d969642003-03-10 23:06:50 +0000519// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
520// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000521//
Chris Lattner8d969642003-03-10 23:06:50 +0000522static inline Value *dyn_castNegVal(Value *V) {
523 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000524 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000525
Chris Lattner0ce85802004-12-14 20:08:06 +0000526 // Constants can be considered to be negated values if they can be folded.
527 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
528 return ConstantExpr::getNeg(C);
Chris Lattner8d969642003-03-10 23:06:50 +0000529 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000530}
531
Chris Lattner8d969642003-03-10 23:06:50 +0000532static inline Value *dyn_castNotVal(Value *V) {
533 if (BinaryOperator::isNot(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000534 return BinaryOperator::getNotArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000535
536 // Constants can be considered to be not'ed values...
Chris Lattner3f2ec392003-04-30 22:34:06 +0000537 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
Chris Lattner448c3232004-06-10 02:12:35 +0000538 return ConstantExpr::getNot(C);
Chris Lattner8d969642003-03-10 23:06:50 +0000539 return 0;
540}
541
Chris Lattnerc8802d22003-03-11 00:12:48 +0000542// dyn_castFoldableMul - If this value is a multiply that can be folded into
543// other computations (because it has a constant operand), return the
Chris Lattner50af16a2004-11-13 19:50:12 +0000544// non-constant operand of the multiply, and set CST to point to the multiplier.
545// Otherwise, return null.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000546//
Chris Lattner50af16a2004-11-13 19:50:12 +0000547static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000548 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner50af16a2004-11-13 19:50:12 +0000549 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000550 if (I->getOpcode() == Instruction::Mul)
Chris Lattner50e60c72004-11-15 05:54:07 +0000551 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000552 return I->getOperand(0);
Chris Lattner50af16a2004-11-13 19:50:12 +0000553 if (I->getOpcode() == Instruction::Shl)
Chris Lattner50e60c72004-11-15 05:54:07 +0000554 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000555 // The multiplier is really 1 << CST.
556 Constant *One = ConstantInt::get(V->getType(), 1);
557 CST = cast<ConstantInt>(ConstantExpr::getShl(One, CST));
558 return I->getOperand(0);
559 }
560 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000561 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000562}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000563
Chris Lattner574da9b2005-01-13 20:14:25 +0000564/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
565/// expression, return it.
566static User *dyn_castGetElementPtr(Value *V) {
567 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
568 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
569 if (CE->getOpcode() == Instruction::GetElementPtr)
570 return cast<User>(V);
571 return false;
572}
573
Chris Lattner955f3312004-09-28 21:48:02 +0000574// AddOne, SubOne - Add or subtract a constant one from an integer constant...
Chris Lattnera96879a2004-09-29 17:40:11 +0000575static ConstantInt *AddOne(ConstantInt *C) {
576 return cast<ConstantInt>(ConstantExpr::getAdd(C,
577 ConstantInt::get(C->getType(), 1)));
Chris Lattner955f3312004-09-28 21:48:02 +0000578}
Chris Lattnera96879a2004-09-29 17:40:11 +0000579static ConstantInt *SubOne(ConstantInt *C) {
580 return cast<ConstantInt>(ConstantExpr::getSub(C,
581 ConstantInt::get(C->getType(), 1)));
Chris Lattner955f3312004-09-28 21:48:02 +0000582}
583
Chris Lattner255d8912006-02-11 09:31:47 +0000584/// GetConstantInType - Return a ConstantInt with the specified type and value.
585///
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000586static ConstantIntegral *GetConstantInType(const Type *Ty, uint64_t Val) {
Reid Spencerb83eb642006-10-20 07:07:24 +0000587 if (Ty->isUnsigned())
588 return ConstantInt::get(Ty, Val);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000589 else if (Ty->getTypeID() == Type::BoolTyID)
590 return ConstantBool::get(Val);
Chris Lattner255d8912006-02-11 09:31:47 +0000591 int64_t SVal = Val;
592 SVal <<= 64-Ty->getPrimitiveSizeInBits();
593 SVal >>= 64-Ty->getPrimitiveSizeInBits();
Reid Spencerb83eb642006-10-20 07:07:24 +0000594 return ConstantInt::get(Ty, SVal);
Chris Lattner255d8912006-02-11 09:31:47 +0000595}
596
597
Chris Lattner68d5ff22006-02-09 07:38:58 +0000598/// ComputeMaskedBits - Determine which of the bits specified in Mask are
599/// known to be either zero or one and return them in the KnownZero/KnownOne
600/// bitsets. This code only analyzes bits in Mask, in order to short-circuit
601/// processing.
602static void ComputeMaskedBits(Value *V, uint64_t Mask, uint64_t &KnownZero,
603 uint64_t &KnownOne, unsigned Depth = 0) {
Chris Lattner5931c542005-09-24 23:43:33 +0000604 // Note, we cannot consider 'undef' to be "IsZero" here. The problem is that
605 // we cannot optimize based on the assumption that it is zero without changing
Chris Lattner3bedbd92006-02-07 07:27:52 +0000606 // it to be an explicit zero. If we don't change it to zero, other code could
Chris Lattner5931c542005-09-24 23:43:33 +0000607 // optimized based on the contradictory assumption that it is non-zero.
608 // Because instcombine aggressively folds operations with undef args anyway,
609 // this won't lose us code quality.
Chris Lattner68d5ff22006-02-09 07:38:58 +0000610 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V)) {
611 // We know all of the bits for a constant!
Chris Lattner255d8912006-02-11 09:31:47 +0000612 KnownOne = CI->getZExtValue() & Mask;
Chris Lattner68d5ff22006-02-09 07:38:58 +0000613 KnownZero = ~KnownOne & Mask;
614 return;
615 }
616
617 KnownZero = KnownOne = 0; // Don't know anything.
Chris Lattner74c51a02006-02-07 08:05:22 +0000618 if (Depth == 6 || Mask == 0)
Chris Lattner68d5ff22006-02-09 07:38:58 +0000619 return; // Limit search depth.
620
621 uint64_t KnownZero2, KnownOne2;
Chris Lattner255d8912006-02-11 09:31:47 +0000622 Instruction *I = dyn_cast<Instruction>(V);
623 if (!I) return;
624
Chris Lattnere3158302006-05-04 17:33:35 +0000625 Mask &= V->getType()->getIntegralTypeMask();
626
Chris Lattner255d8912006-02-11 09:31:47 +0000627 switch (I->getOpcode()) {
628 case Instruction::And:
629 // If either the LHS or the RHS are Zero, the result is zero.
630 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
631 Mask &= ~KnownZero;
632 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
633 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
634 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
635
636 // Output known-1 bits are only known if set in both the LHS & RHS.
637 KnownOne &= KnownOne2;
638 // Output known-0 are known to be clear if zero in either the LHS | RHS.
639 KnownZero |= KnownZero2;
640 return;
641 case Instruction::Or:
642 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
643 Mask &= ~KnownOne;
644 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
645 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
646 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
647
648 // Output known-0 bits are only known if clear in both the LHS & RHS.
649 KnownZero &= KnownZero2;
650 // Output known-1 are known to be set if set in either the LHS | RHS.
651 KnownOne |= KnownOne2;
652 return;
653 case Instruction::Xor: {
654 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
655 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
656 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
657 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
658
659 // Output known-0 bits are known if clear or set in both the LHS & RHS.
660 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
661 // Output known-1 are known to be set if set in only one of the LHS, RHS.
662 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
663 KnownZero = KnownZeroOut;
664 return;
665 }
666 case Instruction::Select:
667 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
668 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
669 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
670 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
671
672 // Only known if known in both the LHS and RHS.
673 KnownOne &= KnownOne2;
674 KnownZero &= KnownZero2;
675 return;
676 case Instruction::Cast: {
677 const Type *SrcTy = I->getOperand(0)->getType();
678 if (!SrcTy->isIntegral()) return;
679
680 // If this is an integer truncate or noop, just look in the input.
681 if (SrcTy->getPrimitiveSizeInBits() >=
682 I->getType()->getPrimitiveSizeInBits()) {
683 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
Chris Lattner68d5ff22006-02-09 07:38:58 +0000684 return;
685 }
Chris Lattner68d5ff22006-02-09 07:38:58 +0000686
Chris Lattner255d8912006-02-11 09:31:47 +0000687 // Sign or Zero extension. Compute the bits in the result that are not
688 // present in the input.
689 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
690 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
Chris Lattner60de63d2005-10-09 06:36:35 +0000691
Chris Lattner255d8912006-02-11 09:31:47 +0000692 // Handle zero extension.
693 if (!SrcTy->isSigned()) {
694 Mask &= SrcTy->getIntegralTypeMask();
695 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
696 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
697 // The top bits are known to be zero.
698 KnownZero |= NewBits;
699 } else {
700 // Sign extension.
701 Mask &= SrcTy->getIntegralTypeMask();
702 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
703 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner74c51a02006-02-07 08:05:22 +0000704
Chris Lattner255d8912006-02-11 09:31:47 +0000705 // If the sign bit of the input is known set or clear, then we know the
706 // top bits of the result.
707 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
708 if (KnownZero & InSignBit) { // Input sign bit known zero
Chris Lattner68d5ff22006-02-09 07:38:58 +0000709 KnownZero |= NewBits;
Chris Lattner255d8912006-02-11 09:31:47 +0000710 KnownOne &= ~NewBits;
711 } else if (KnownOne & InSignBit) { // Input sign bit known set
712 KnownOne |= NewBits;
713 KnownZero &= ~NewBits;
714 } else { // Input sign bit unknown
715 KnownZero &= ~NewBits;
716 KnownOne &= ~NewBits;
717 }
718 }
719 return;
720 }
721 case Instruction::Shl:
722 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
Reid Spencerb83eb642006-10-20 07:07:24 +0000723 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
724 uint64_t ShiftAmt = SA->getZExtValue();
725 Mask >>= ShiftAmt;
Chris Lattner255d8912006-02-11 09:31:47 +0000726 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
727 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Reid Spencerb83eb642006-10-20 07:07:24 +0000728 KnownZero <<= ShiftAmt;
729 KnownOne <<= ShiftAmt;
730 KnownZero |= (1ULL << ShiftAmt)-1; // low bits known zero.
Chris Lattner255d8912006-02-11 09:31:47 +0000731 return;
732 }
733 break;
734 case Instruction::Shr:
735 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
Reid Spencerb83eb642006-10-20 07:07:24 +0000736 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Chris Lattner255d8912006-02-11 09:31:47 +0000737 // Compute the new bits that are at the top now.
Reid Spencerb83eb642006-10-20 07:07:24 +0000738 uint64_t ShiftAmt = SA->getZExtValue();
739 uint64_t HighBits = (1ULL << ShiftAmt)-1;
740 HighBits <<= I->getType()->getPrimitiveSizeInBits()-ShiftAmt;
Chris Lattner255d8912006-02-11 09:31:47 +0000741
742 if (I->getType()->isUnsigned()) { // Unsigned shift right.
Reid Spencerb83eb642006-10-20 07:07:24 +0000743 Mask <<= ShiftAmt;
Chris Lattner255d8912006-02-11 09:31:47 +0000744 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
745 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
Reid Spencerb83eb642006-10-20 07:07:24 +0000746 KnownZero >>= ShiftAmt;
747 KnownOne >>= ShiftAmt;
Chris Lattner255d8912006-02-11 09:31:47 +0000748 KnownZero |= HighBits; // high bits known zero.
Chris Lattner68d5ff22006-02-09 07:38:58 +0000749 } else {
Reid Spencerb83eb642006-10-20 07:07:24 +0000750 Mask <<= ShiftAmt;
Chris Lattner255d8912006-02-11 09:31:47 +0000751 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
752 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
Reid Spencerb83eb642006-10-20 07:07:24 +0000753 KnownZero >>= ShiftAmt;
754 KnownOne >>= ShiftAmt;
Chris Lattner255d8912006-02-11 09:31:47 +0000755
756 // Handle the sign bits.
757 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
Reid Spencerb83eb642006-10-20 07:07:24 +0000758 SignBit >>= ShiftAmt; // Adjust to where it is now in the mask.
Chris Lattner255d8912006-02-11 09:31:47 +0000759
760 if (KnownZero & SignBit) { // New bits are known zero.
761 KnownZero |= HighBits;
762 } else if (KnownOne & SignBit) { // New bits are known one.
763 KnownOne |= HighBits;
Chris Lattner68d5ff22006-02-09 07:38:58 +0000764 }
765 }
766 return;
Chris Lattner60de63d2005-10-09 06:36:35 +0000767 }
Chris Lattner255d8912006-02-11 09:31:47 +0000768 break;
Chris Lattner5931c542005-09-24 23:43:33 +0000769 }
Chris Lattner74c51a02006-02-07 08:05:22 +0000770}
771
772/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
773/// this predicate to simplify operations downstream. Mask is known to be zero
774/// for bits that V cannot have.
775static bool MaskedValueIsZero(Value *V, uint64_t Mask, unsigned Depth = 0) {
Chris Lattner68d5ff22006-02-09 07:38:58 +0000776 uint64_t KnownZero, KnownOne;
777 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
778 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
779 return (KnownZero & Mask) == Mask;
Chris Lattner5931c542005-09-24 23:43:33 +0000780}
781
Chris Lattner255d8912006-02-11 09:31:47 +0000782/// ShrinkDemandedConstant - Check to see if the specified operand of the
783/// specified instruction is a constant integer. If so, check to see if there
784/// are any bits set in the constant that are not demanded. If so, shrink the
785/// constant and return true.
786static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
787 uint64_t Demanded) {
788 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
789 if (!OpC) return false;
790
791 // If there are no bits set that aren't demanded, nothing to do.
792 if ((~Demanded & OpC->getZExtValue()) == 0)
793 return false;
794
795 // This is producing any bits that are not needed, shrink the RHS.
796 uint64_t Val = Demanded & OpC->getZExtValue();
797 I->setOperand(OpNo, GetConstantInType(OpC->getType(), Val));
798 return true;
799}
800
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000801// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
802// set of known zero and one bits, compute the maximum and minimum values that
803// could have the specified known zero and known one bits, returning them in
804// min/max.
805static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
806 uint64_t KnownZero,
807 uint64_t KnownOne,
808 int64_t &Min, int64_t &Max) {
809 uint64_t TypeBits = Ty->getIntegralTypeMask();
810 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
811
812 uint64_t SignBit = 1ULL << (Ty->getPrimitiveSizeInBits()-1);
813
814 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
815 // bit if it is unknown.
816 Min = KnownOne;
817 Max = KnownOne|UnknownBits;
818
819 if (SignBit & UnknownBits) { // Sign bit is unknown
820 Min |= SignBit;
821 Max &= ~SignBit;
822 }
823
824 // Sign extend the min/max values.
825 int ShAmt = 64-Ty->getPrimitiveSizeInBits();
826 Min = (Min << ShAmt) >> ShAmt;
827 Max = (Max << ShAmt) >> ShAmt;
828}
829
830// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
831// a set of known zero and one bits, compute the maximum and minimum values that
832// could have the specified known zero and known one bits, returning them in
833// min/max.
834static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
835 uint64_t KnownZero,
836 uint64_t KnownOne,
837 uint64_t &Min,
838 uint64_t &Max) {
839 uint64_t TypeBits = Ty->getIntegralTypeMask();
840 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
841
842 // The minimum value is when the unknown bits are all zeros.
843 Min = KnownOne;
844 // The maximum value is when the unknown bits are all ones.
845 Max = KnownOne|UnknownBits;
846}
Chris Lattner255d8912006-02-11 09:31:47 +0000847
848
849/// SimplifyDemandedBits - Look at V. At this point, we know that only the
850/// DemandedMask bits of the result of V are ever used downstream. If we can
851/// use this information to simplify V, do so and return true. Otherwise,
852/// analyze the expression and return a mask of KnownOne and KnownZero bits for
853/// the expression (used to simplify the caller). The KnownZero/One bits may
854/// only be accurate for those bits in the DemandedMask.
855bool InstCombiner::SimplifyDemandedBits(Value *V, uint64_t DemandedMask,
856 uint64_t &KnownZero, uint64_t &KnownOne,
Chris Lattner6dce1a72006-02-07 06:56:34 +0000857 unsigned Depth) {
Chris Lattner255d8912006-02-11 09:31:47 +0000858 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V)) {
859 // We know all of the bits for a constant!
860 KnownOne = CI->getZExtValue() & DemandedMask;
861 KnownZero = ~KnownOne & DemandedMask;
862 return false;
863 }
864
865 KnownZero = KnownOne = 0;
Chris Lattner6dce1a72006-02-07 06:56:34 +0000866 if (!V->hasOneUse()) { // Other users may use these bits.
Chris Lattner255d8912006-02-11 09:31:47 +0000867 if (Depth != 0) { // Not at the root.
868 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
869 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
Chris Lattner6dce1a72006-02-07 06:56:34 +0000870 return false;
Chris Lattner255d8912006-02-11 09:31:47 +0000871 }
Chris Lattner6dce1a72006-02-07 06:56:34 +0000872 // If this is the root being simplified, allow it to have multiple uses,
Chris Lattner255d8912006-02-11 09:31:47 +0000873 // just set the DemandedMask to all bits.
874 DemandedMask = V->getType()->getIntegralTypeMask();
875 } else if (DemandedMask == 0) { // Not demanding any bits from V.
Chris Lattner74c51a02006-02-07 08:05:22 +0000876 if (V != UndefValue::get(V->getType()))
877 return UpdateValueUsesWith(V, UndefValue::get(V->getType()));
878 return false;
Chris Lattner6dce1a72006-02-07 06:56:34 +0000879 } else if (Depth == 6) { // Limit search depth.
880 return false;
881 }
882
883 Instruction *I = dyn_cast<Instruction>(V);
884 if (!I) return false; // Only analyze instructions.
885
Chris Lattnere3158302006-05-04 17:33:35 +0000886 DemandedMask &= V->getType()->getIntegralTypeMask();
887
Chris Lattner255d8912006-02-11 09:31:47 +0000888 uint64_t KnownZero2, KnownOne2;
Chris Lattner6dce1a72006-02-07 06:56:34 +0000889 switch (I->getOpcode()) {
890 default: break;
891 case Instruction::And:
Chris Lattner255d8912006-02-11 09:31:47 +0000892 // If either the LHS or the RHS are Zero, the result is zero.
893 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
894 KnownZero, KnownOne, Depth+1))
895 return true;
896 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
897
898 // If something is known zero on the RHS, the bits aren't demanded on the
899 // LHS.
900 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownZero,
901 KnownZero2, KnownOne2, Depth+1))
902 return true;
903 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
904
905 // If all of the demanded bits are known one on one side, return the other.
906 // These bits cannot contribute to the result of the 'and'.
907 if ((DemandedMask & ~KnownZero2 & KnownOne) == (DemandedMask & ~KnownZero2))
908 return UpdateValueUsesWith(I, I->getOperand(0));
909 if ((DemandedMask & ~KnownZero & KnownOne2) == (DemandedMask & ~KnownZero))
910 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattnerf8c36f52006-02-12 08:02:11 +0000911
912 // If all of the demanded bits in the inputs are known zeros, return zero.
913 if ((DemandedMask & (KnownZero|KnownZero2)) == DemandedMask)
914 return UpdateValueUsesWith(I, Constant::getNullValue(I->getType()));
915
Chris Lattner255d8912006-02-11 09:31:47 +0000916 // If the RHS is a constant, see if we can simplify it.
Chris Lattnerf8c36f52006-02-12 08:02:11 +0000917 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~KnownZero2))
Chris Lattner255d8912006-02-11 09:31:47 +0000918 return UpdateValueUsesWith(I, I);
919
920 // Output known-1 bits are only known if set in both the LHS & RHS.
921 KnownOne &= KnownOne2;
922 // Output known-0 are known to be clear if zero in either the LHS | RHS.
923 KnownZero |= KnownZero2;
924 break;
925 case Instruction::Or:
926 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
927 KnownZero, KnownOne, Depth+1))
928 return true;
929 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
930 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownOne,
931 KnownZero2, KnownOne2, Depth+1))
932 return true;
933 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
934
935 // If all of the demanded bits are known zero on one side, return the other.
936 // These bits cannot contribute to the result of the 'or'.
Jeff Cohenbce48052006-02-18 03:20:33 +0000937 if ((DemandedMask & ~KnownOne2 & KnownZero) == (DemandedMask & ~KnownOne2))
Chris Lattner255d8912006-02-11 09:31:47 +0000938 return UpdateValueUsesWith(I, I->getOperand(0));
Jeff Cohenbce48052006-02-18 03:20:33 +0000939 if ((DemandedMask & ~KnownOne & KnownZero2) == (DemandedMask & ~KnownOne))
Chris Lattner255d8912006-02-11 09:31:47 +0000940 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattnerf8c36f52006-02-12 08:02:11 +0000941
942 // If all of the potentially set bits on one side are known to be set on
943 // the other side, just use the 'other' side.
944 if ((DemandedMask & (~KnownZero) & KnownOne2) ==
945 (DemandedMask & (~KnownZero)))
946 return UpdateValueUsesWith(I, I->getOperand(0));
Nate Begeman368e18d2006-02-16 21:11:51 +0000947 if ((DemandedMask & (~KnownZero2) & KnownOne) ==
948 (DemandedMask & (~KnownZero2)))
949 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner255d8912006-02-11 09:31:47 +0000950
951 // If the RHS is a constant, see if we can simplify it.
952 if (ShrinkDemandedConstant(I, 1, DemandedMask))
953 return UpdateValueUsesWith(I, I);
954
955 // Output known-0 bits are only known if clear in both the LHS & RHS.
956 KnownZero &= KnownZero2;
957 // Output known-1 are known to be set if set in either the LHS | RHS.
958 KnownOne |= KnownOne2;
959 break;
960 case Instruction::Xor: {
961 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
962 KnownZero, KnownOne, Depth+1))
963 return true;
964 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
965 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
966 KnownZero2, KnownOne2, Depth+1))
967 return true;
968 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
969
970 // If all of the demanded bits are known zero on one side, return the other.
971 // These bits cannot contribute to the result of the 'xor'.
972 if ((DemandedMask & KnownZero) == DemandedMask)
973 return UpdateValueUsesWith(I, I->getOperand(0));
974 if ((DemandedMask & KnownZero2) == DemandedMask)
975 return UpdateValueUsesWith(I, I->getOperand(1));
976
977 // Output known-0 bits are known if clear or set in both the LHS & RHS.
978 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
979 // Output known-1 are known to be set if set in only one of the LHS, RHS.
980 uint64_t KnownOneOut = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
981
982 // If all of the unknown bits are known to be zero on one side or the other
983 // (but not both) turn this into an *inclusive* or.
Chris Lattnerf8c36f52006-02-12 08:02:11 +0000984 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattner255d8912006-02-11 09:31:47 +0000985 if (uint64_t UnknownBits = DemandedMask & ~(KnownZeroOut|KnownOneOut)) {
986 if ((UnknownBits & (KnownZero|KnownZero2)) == UnknownBits) {
987 Instruction *Or =
988 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
989 I->getName());
990 InsertNewInstBefore(Or, *I);
991 return UpdateValueUsesWith(I, Or);
Chris Lattner6dce1a72006-02-07 06:56:34 +0000992 }
993 }
Chris Lattner255d8912006-02-11 09:31:47 +0000994
Chris Lattnerf8c36f52006-02-12 08:02:11 +0000995 // If all of the demanded bits on one side are known, and all of the set
996 // bits on that side are also known to be set on the other side, turn this
997 // into an AND, as we know the bits will be cleared.
998 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
999 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask) { // all known
1000 if ((KnownOne & KnownOne2) == KnownOne) {
1001 Constant *AndC = GetConstantInType(I->getType(),
1002 ~KnownOne & DemandedMask);
1003 Instruction *And =
1004 BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
1005 InsertNewInstBefore(And, *I);
1006 return UpdateValueUsesWith(I, And);
1007 }
1008 }
1009
Chris Lattner255d8912006-02-11 09:31:47 +00001010 // If the RHS is a constant, see if we can simplify it.
1011 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1012 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1013 return UpdateValueUsesWith(I, I);
1014
1015 KnownZero = KnownZeroOut;
1016 KnownOne = KnownOneOut;
1017 break;
1018 }
1019 case Instruction::Select:
1020 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
1021 KnownZero, KnownOne, Depth+1))
1022 return true;
1023 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1024 KnownZero2, KnownOne2, Depth+1))
1025 return true;
1026 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1027 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1028
1029 // If the operands are constants, see if we can simplify them.
1030 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1031 return UpdateValueUsesWith(I, I);
1032 if (ShrinkDemandedConstant(I, 2, DemandedMask))
1033 return UpdateValueUsesWith(I, I);
1034
1035 // Only known if known in both the LHS and RHS.
1036 KnownOne &= KnownOne2;
1037 KnownZero &= KnownZero2;
1038 break;
Chris Lattner6dce1a72006-02-07 06:56:34 +00001039 case Instruction::Cast: {
1040 const Type *SrcTy = I->getOperand(0)->getType();
Chris Lattner255d8912006-02-11 09:31:47 +00001041 if (!SrcTy->isIntegral()) return false;
Chris Lattner6dce1a72006-02-07 06:56:34 +00001042
Chris Lattner255d8912006-02-11 09:31:47 +00001043 // If this is an integer truncate or noop, just look in the input.
1044 if (SrcTy->getPrimitiveSizeInBits() >=
1045 I->getType()->getPrimitiveSizeInBits()) {
Chris Lattnerf6bd07c2006-09-16 03:14:10 +00001046 // Cast to bool is a comparison against 0, which demands all bits. We
1047 // can't propagate anything useful up.
1048 if (I->getType() == Type::BoolTy)
1049 break;
1050
Chris Lattner255d8912006-02-11 09:31:47 +00001051 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1052 KnownZero, KnownOne, Depth+1))
1053 return true;
1054 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1055 break;
1056 }
1057
1058 // Sign or Zero extension. Compute the bits in the result that are not
1059 // present in the input.
1060 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
1061 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
1062
1063 // Handle zero extension.
1064 if (!SrcTy->isSigned()) {
1065 DemandedMask &= SrcTy->getIntegralTypeMask();
1066 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1067 KnownZero, KnownOne, Depth+1))
1068 return true;
1069 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1070 // The top bits are known to be zero.
1071 KnownZero |= NewBits;
1072 } else {
1073 // Sign extension.
Chris Lattnerf345fe42006-02-13 22:41:07 +00001074 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
1075 int64_t InputDemandedBits = DemandedMask & SrcTy->getIntegralTypeMask();
1076
1077 // If any of the sign extended bits are demanded, we know that the sign
1078 // bit is demanded.
1079 if (NewBits & DemandedMask)
1080 InputDemandedBits |= InSignBit;
1081
1082 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
Chris Lattner255d8912006-02-11 09:31:47 +00001083 KnownZero, KnownOne, Depth+1))
1084 return true;
1085 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1086
1087 // If the sign bit of the input is known set or clear, then we know the
1088 // top bits of the result.
Chris Lattner6dce1a72006-02-07 06:56:34 +00001089
Chris Lattner255d8912006-02-11 09:31:47 +00001090 // If the input sign bit is known zero, or if the NewBits are not demanded
1091 // convert this into a zero extension.
1092 if ((KnownZero & InSignBit) || (NewBits & ~DemandedMask) == NewBits) {
Chris Lattner6dce1a72006-02-07 06:56:34 +00001093 // Convert to unsigned first.
Reid Spencer811b0cb2006-10-26 19:19:06 +00001094 Value *NewVal =
1095 InsertCastBefore(I->getOperand(0), SrcTy->getUnsignedVersion(), *I);
Chris Lattner255d8912006-02-11 09:31:47 +00001096 // Then cast that to the destination type.
Chris Lattnerd89d8882006-02-07 19:07:40 +00001097 NewVal = new CastInst(NewVal, I->getType(), I->getName());
Reid Spencer811b0cb2006-10-26 19:19:06 +00001098 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
Chris Lattner6dce1a72006-02-07 06:56:34 +00001099 return UpdateValueUsesWith(I, NewVal);
Chris Lattner255d8912006-02-11 09:31:47 +00001100 } else if (KnownOne & InSignBit) { // Input sign bit known set
1101 KnownOne |= NewBits;
1102 KnownZero &= ~NewBits;
1103 } else { // Input sign bit unknown
1104 KnownZero &= ~NewBits;
1105 KnownOne &= ~NewBits;
Chris Lattner6dce1a72006-02-07 06:56:34 +00001106 }
Chris Lattner6dce1a72006-02-07 06:56:34 +00001107 }
Chris Lattner255d8912006-02-11 09:31:47 +00001108 break;
Chris Lattner6dce1a72006-02-07 06:56:34 +00001109 }
Chris Lattner6dce1a72006-02-07 06:56:34 +00001110 case Instruction::Shl:
Reid Spencerb83eb642006-10-20 07:07:24 +00001111 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1112 uint64_t ShiftAmt = SA->getZExtValue();
1113 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask >> ShiftAmt,
Chris Lattner255d8912006-02-11 09:31:47 +00001114 KnownZero, KnownOne, Depth+1))
1115 return true;
1116 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Reid Spencerb83eb642006-10-20 07:07:24 +00001117 KnownZero <<= ShiftAmt;
1118 KnownOne <<= ShiftAmt;
1119 KnownZero |= (1ULL << ShiftAmt) - 1; // low bits known zero.
Chris Lattner255d8912006-02-11 09:31:47 +00001120 }
Chris Lattner6dce1a72006-02-07 06:56:34 +00001121 break;
1122 case Instruction::Shr:
Chris Lattnerb7363792006-09-18 04:31:40 +00001123 // If this is an arithmetic shift right and only the low-bit is set, we can
1124 // always convert this into a logical shr, even if the shift amount is
1125 // variable. The low bit of the shift cannot be an input sign bit unless
1126 // the shift amount is >= the size of the datatype, which is undefined.
1127 if (DemandedMask == 1 && I->getType()->isSigned()) {
1128 // Convert the input to unsigned.
Reid Spencer811b0cb2006-10-26 19:19:06 +00001129 Value *NewVal = InsertCastBefore(I->getOperand(0),
1130 I->getType()->getUnsignedVersion(), *I);
Chris Lattnerb7363792006-09-18 04:31:40 +00001131 // Perform the unsigned shift right.
1132 NewVal = new ShiftInst(Instruction::Shr, NewVal, I->getOperand(1),
1133 I->getName());
Reid Spencer811b0cb2006-10-26 19:19:06 +00001134 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
Chris Lattnerb7363792006-09-18 04:31:40 +00001135 // Then cast that to the destination type.
1136 NewVal = new CastInst(NewVal, I->getType(), I->getName());
Reid Spencer811b0cb2006-10-26 19:19:06 +00001137 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
Chris Lattnerb7363792006-09-18 04:31:40 +00001138 return UpdateValueUsesWith(I, NewVal);
1139 }
1140
Reid Spencerb83eb642006-10-20 07:07:24 +00001141 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1142 unsigned ShiftAmt = SA->getZExtValue();
Chris Lattner255d8912006-02-11 09:31:47 +00001143
1144 // Compute the new bits that are at the top now.
Reid Spencerb83eb642006-10-20 07:07:24 +00001145 uint64_t HighBits = (1ULL << ShiftAmt)-1;
1146 HighBits <<= I->getType()->getPrimitiveSizeInBits() - ShiftAmt;
Chris Lattnerc15637b2006-02-13 06:09:08 +00001147 uint64_t TypeMask = I->getType()->getIntegralTypeMask();
Chris Lattner255d8912006-02-11 09:31:47 +00001148 if (I->getType()->isUnsigned()) { // Unsigned shift right.
Chris Lattnerc15637b2006-02-13 06:09:08 +00001149 if (SimplifyDemandedBits(I->getOperand(0),
Reid Spencerb83eb642006-10-20 07:07:24 +00001150 (DemandedMask << ShiftAmt) & TypeMask,
Chris Lattner255d8912006-02-11 09:31:47 +00001151 KnownZero, KnownOne, Depth+1))
1152 return true;
1153 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattnerc15637b2006-02-13 06:09:08 +00001154 KnownZero &= TypeMask;
1155 KnownOne &= TypeMask;
Reid Spencerb83eb642006-10-20 07:07:24 +00001156 KnownZero >>= ShiftAmt;
1157 KnownOne >>= ShiftAmt;
Chris Lattner255d8912006-02-11 09:31:47 +00001158 KnownZero |= HighBits; // high bits known zero.
1159 } else { // Signed shift right.
Chris Lattnerc15637b2006-02-13 06:09:08 +00001160 if (SimplifyDemandedBits(I->getOperand(0),
Reid Spencerb83eb642006-10-20 07:07:24 +00001161 (DemandedMask << ShiftAmt) & TypeMask,
Chris Lattner255d8912006-02-11 09:31:47 +00001162 KnownZero, KnownOne, Depth+1))
1163 return true;
1164 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattnerc15637b2006-02-13 06:09:08 +00001165 KnownZero &= TypeMask;
1166 KnownOne &= TypeMask;
Reid Spencerb83eb642006-10-20 07:07:24 +00001167 KnownZero >>= ShiftAmt;
1168 KnownOne >>= ShiftAmt;
Chris Lattner255d8912006-02-11 09:31:47 +00001169
1170 // Handle the sign bits.
1171 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
Reid Spencerb83eb642006-10-20 07:07:24 +00001172 SignBit >>= ShiftAmt; // Adjust to where it is now in the mask.
Chris Lattner255d8912006-02-11 09:31:47 +00001173
1174 // If the input sign bit is known to be zero, or if none of the top bits
1175 // are demanded, turn this into an unsigned shift right.
1176 if ((KnownZero & SignBit) || (HighBits & ~DemandedMask) == HighBits) {
1177 // Convert the input to unsigned.
Reid Spencer811b0cb2006-10-26 19:19:06 +00001178 Value *NewVal = InsertCastBefore(I->getOperand(0),
1179 I->getType()->getUnsignedVersion(), *I);
Chris Lattner255d8912006-02-11 09:31:47 +00001180 // Perform the unsigned shift right.
1181 NewVal = new ShiftInst(Instruction::Shr, NewVal, SA, I->getName());
Reid Spencer811b0cb2006-10-26 19:19:06 +00001182 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
Chris Lattner255d8912006-02-11 09:31:47 +00001183 // Then cast that to the destination type.
1184 NewVal = new CastInst(NewVal, I->getType(), I->getName());
Reid Spencer811b0cb2006-10-26 19:19:06 +00001185 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
Chris Lattner255d8912006-02-11 09:31:47 +00001186 return UpdateValueUsesWith(I, NewVal);
1187 } else if (KnownOne & SignBit) { // New bits are known one.
1188 KnownOne |= HighBits;
1189 }
Chris Lattner6dce1a72006-02-07 06:56:34 +00001190 }
Chris Lattner255d8912006-02-11 09:31:47 +00001191 }
Chris Lattner6dce1a72006-02-07 06:56:34 +00001192 break;
1193 }
Chris Lattner255d8912006-02-11 09:31:47 +00001194
1195 // If the client is only demanding bits that we know, return the known
1196 // constant.
1197 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask)
1198 return UpdateValueUsesWith(I, GetConstantInType(I->getType(), KnownOne));
Chris Lattner6dce1a72006-02-07 06:56:34 +00001199 return false;
1200}
1201
Chris Lattner867b99f2006-10-05 06:55:50 +00001202
1203/// SimplifyDemandedVectorElts - The specified value producecs a vector with
1204/// 64 or fewer elements. DemandedElts contains the set of elements that are
1205/// actually used by the caller. This method analyzes which elements of the
1206/// operand are undef and returns that information in UndefElts.
1207///
1208/// If the information about demanded elements can be used to simplify the
1209/// operation, the operation is simplified, then the resultant value is
1210/// returned. This returns null if no change was made.
1211Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1212 uint64_t &UndefElts,
1213 unsigned Depth) {
1214 unsigned VWidth = cast<PackedType>(V->getType())->getNumElements();
1215 assert(VWidth <= 64 && "Vector too wide to analyze!");
1216 uint64_t EltMask = ~0ULL >> (64-VWidth);
1217 assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1218 "Invalid DemandedElts!");
1219
1220 if (isa<UndefValue>(V)) {
1221 // If the entire vector is undefined, just return this info.
1222 UndefElts = EltMask;
1223 return 0;
1224 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1225 UndefElts = EltMask;
1226 return UndefValue::get(V->getType());
1227 }
1228
1229 UndefElts = 0;
1230 if (ConstantPacked *CP = dyn_cast<ConstantPacked>(V)) {
1231 const Type *EltTy = cast<PackedType>(V->getType())->getElementType();
1232 Constant *Undef = UndefValue::get(EltTy);
1233
1234 std::vector<Constant*> Elts;
1235 for (unsigned i = 0; i != VWidth; ++i)
1236 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1237 Elts.push_back(Undef);
1238 UndefElts |= (1ULL << i);
1239 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1240 Elts.push_back(Undef);
1241 UndefElts |= (1ULL << i);
1242 } else { // Otherwise, defined.
1243 Elts.push_back(CP->getOperand(i));
1244 }
1245
1246 // If we changed the constant, return it.
1247 Constant *NewCP = ConstantPacked::get(Elts);
1248 return NewCP != CP ? NewCP : 0;
1249 } else if (isa<ConstantAggregateZero>(V)) {
1250 // Simplify the CAZ to a ConstantPacked where the non-demanded elements are
1251 // set to undef.
1252 const Type *EltTy = cast<PackedType>(V->getType())->getElementType();
1253 Constant *Zero = Constant::getNullValue(EltTy);
1254 Constant *Undef = UndefValue::get(EltTy);
1255 std::vector<Constant*> Elts;
1256 for (unsigned i = 0; i != VWidth; ++i)
1257 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1258 UndefElts = DemandedElts ^ EltMask;
1259 return ConstantPacked::get(Elts);
1260 }
1261
1262 if (!V->hasOneUse()) { // Other users may use these bits.
1263 if (Depth != 0) { // Not at the root.
1264 // TODO: Just compute the UndefElts information recursively.
1265 return false;
1266 }
1267 return false;
1268 } else if (Depth == 10) { // Limit search depth.
1269 return false;
1270 }
1271
1272 Instruction *I = dyn_cast<Instruction>(V);
1273 if (!I) return false; // Only analyze instructions.
1274
1275 bool MadeChange = false;
1276 uint64_t UndefElts2;
1277 Value *TmpV;
1278 switch (I->getOpcode()) {
1279 default: break;
1280
1281 case Instruction::InsertElement: {
1282 // If this is a variable index, we don't know which element it overwrites.
1283 // demand exactly the same input as we produce.
Reid Spencerb83eb642006-10-20 07:07:24 +00001284 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner867b99f2006-10-05 06:55:50 +00001285 if (Idx == 0) {
1286 // Note that we can't propagate undef elt info, because we don't know
1287 // which elt is getting updated.
1288 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1289 UndefElts2, Depth+1);
1290 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1291 break;
1292 }
1293
1294 // If this is inserting an element that isn't demanded, remove this
1295 // insertelement.
Reid Spencerb83eb642006-10-20 07:07:24 +00001296 unsigned IdxNo = Idx->getZExtValue();
Chris Lattner867b99f2006-10-05 06:55:50 +00001297 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1298 return AddSoonDeadInstToWorklist(*I, 0);
1299
1300 // Otherwise, the element inserted overwrites whatever was there, so the
1301 // input demanded set is simpler than the output set.
1302 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1303 DemandedElts & ~(1ULL << IdxNo),
1304 UndefElts, Depth+1);
1305 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1306
1307 // The inserted element is defined.
1308 UndefElts |= 1ULL << IdxNo;
1309 break;
1310 }
1311
1312 case Instruction::And:
1313 case Instruction::Or:
1314 case Instruction::Xor:
1315 case Instruction::Add:
1316 case Instruction::Sub:
1317 case Instruction::Mul:
1318 // div/rem demand all inputs, because they don't want divide by zero.
1319 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1320 UndefElts, Depth+1);
1321 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1322 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1323 UndefElts2, Depth+1);
1324 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1325
1326 // Output elements are undefined if both are undefined. Consider things
1327 // like undef&0. The result is known zero, not undef.
1328 UndefElts &= UndefElts2;
1329 break;
1330
1331 case Instruction::Call: {
1332 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1333 if (!II) break;
1334 switch (II->getIntrinsicID()) {
1335 default: break;
1336
1337 // Binary vector operations that work column-wise. A dest element is a
1338 // function of the corresponding input elements from the two inputs.
1339 case Intrinsic::x86_sse_sub_ss:
1340 case Intrinsic::x86_sse_mul_ss:
1341 case Intrinsic::x86_sse_min_ss:
1342 case Intrinsic::x86_sse_max_ss:
1343 case Intrinsic::x86_sse2_sub_sd:
1344 case Intrinsic::x86_sse2_mul_sd:
1345 case Intrinsic::x86_sse2_min_sd:
1346 case Intrinsic::x86_sse2_max_sd:
1347 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1348 UndefElts, Depth+1);
1349 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1350 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1351 UndefElts2, Depth+1);
1352 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1353
1354 // If only the low elt is demanded and this is a scalarizable intrinsic,
1355 // scalarize it now.
1356 if (DemandedElts == 1) {
1357 switch (II->getIntrinsicID()) {
1358 default: break;
1359 case Intrinsic::x86_sse_sub_ss:
1360 case Intrinsic::x86_sse_mul_ss:
1361 case Intrinsic::x86_sse2_sub_sd:
1362 case Intrinsic::x86_sse2_mul_sd:
1363 // TODO: Lower MIN/MAX/ABS/etc
1364 Value *LHS = II->getOperand(1);
1365 Value *RHS = II->getOperand(2);
1366 // Extract the element as scalars.
1367 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1368 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1369
1370 switch (II->getIntrinsicID()) {
1371 default: assert(0 && "Case stmts out of sync!");
1372 case Intrinsic::x86_sse_sub_ss:
1373 case Intrinsic::x86_sse2_sub_sd:
1374 TmpV = InsertNewInstBefore(BinaryOperator::createSub(LHS, RHS,
1375 II->getName()), *II);
1376 break;
1377 case Intrinsic::x86_sse_mul_ss:
1378 case Intrinsic::x86_sse2_mul_sd:
1379 TmpV = InsertNewInstBefore(BinaryOperator::createMul(LHS, RHS,
1380 II->getName()), *II);
1381 break;
1382 }
1383
1384 Instruction *New =
1385 new InsertElementInst(UndefValue::get(II->getType()), TmpV, 0U,
1386 II->getName());
1387 InsertNewInstBefore(New, *II);
1388 AddSoonDeadInstToWorklist(*II, 0);
1389 return New;
1390 }
1391 }
1392
1393 // Output elements are undefined if both are undefined. Consider things
1394 // like undef&0. The result is known zero, not undef.
1395 UndefElts &= UndefElts2;
1396 break;
1397 }
1398 break;
1399 }
1400 }
1401 return MadeChange ? I : 0;
1402}
1403
Chris Lattner955f3312004-09-28 21:48:02 +00001404// isTrueWhenEqual - Return true if the specified setcondinst instruction is
1405// true when both operands are equal...
1406//
1407static bool isTrueWhenEqual(Instruction &I) {
1408 return I.getOpcode() == Instruction::SetEQ ||
1409 I.getOpcode() == Instruction::SetGE ||
1410 I.getOpcode() == Instruction::SetLE;
1411}
Chris Lattner564a7272003-08-13 19:01:45 +00001412
1413/// AssociativeOpt - Perform an optimization on an associative operator. This
1414/// function is designed to check a chain of associative operators for a
1415/// potential to apply a certain optimization. Since the optimization may be
1416/// applicable if the expression was reassociated, this checks the chain, then
1417/// reassociates the expression as necessary to expose the optimization
1418/// opportunity. This makes use of a special Functor, which must define
1419/// 'shouldApply' and 'apply' methods.
1420///
1421template<typename Functor>
1422Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1423 unsigned Opcode = Root.getOpcode();
1424 Value *LHS = Root.getOperand(0);
1425
1426 // Quick check, see if the immediate LHS matches...
1427 if (F.shouldApply(LHS))
1428 return F.apply(Root);
1429
1430 // Otherwise, if the LHS is not of the same opcode as the root, return.
1431 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +00001432 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +00001433 // Should we apply this transform to the RHS?
1434 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1435
1436 // If not to the RHS, check to see if we should apply to the LHS...
1437 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1438 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1439 ShouldApply = true;
1440 }
1441
1442 // If the functor wants to apply the optimization to the RHS of LHSI,
1443 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1444 if (ShouldApply) {
1445 BasicBlock *BB = Root.getParent();
Misha Brukmanfd939082005-04-21 23:48:37 +00001446
Chris Lattner564a7272003-08-13 19:01:45 +00001447 // Now all of the instructions are in the current basic block, go ahead
1448 // and perform the reassociation.
1449 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1450
1451 // First move the selected RHS to the LHS of the root...
1452 Root.setOperand(0, LHSI->getOperand(1));
1453
1454 // Make what used to be the LHS of the root be the user of the root...
1455 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +00001456 if (&Root == TmpLHSI) {
Chris Lattner15a76c02004-04-05 02:10:19 +00001457 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1458 return 0;
1459 }
Chris Lattner65725312004-04-16 18:08:07 +00001460 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +00001461 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +00001462 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1463 BasicBlock::iterator ARI = &Root; ++ARI;
1464 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
1465 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +00001466
1467 // Now propagate the ExtraOperand down the chain of instructions until we
1468 // get to LHSI.
1469 while (TmpLHSI != LHSI) {
1470 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +00001471 // Move the instruction to immediately before the chain we are
1472 // constructing to avoid breaking dominance properties.
1473 NextLHSI->getParent()->getInstList().remove(NextLHSI);
1474 BB->getInstList().insert(ARI, NextLHSI);
1475 ARI = NextLHSI;
1476
Chris Lattner564a7272003-08-13 19:01:45 +00001477 Value *NextOp = NextLHSI->getOperand(1);
1478 NextLHSI->setOperand(1, ExtraOperand);
1479 TmpLHSI = NextLHSI;
1480 ExtraOperand = NextOp;
1481 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001482
Chris Lattner564a7272003-08-13 19:01:45 +00001483 // Now that the instructions are reassociated, have the functor perform
1484 // the transformation...
1485 return F.apply(Root);
1486 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001487
Chris Lattner564a7272003-08-13 19:01:45 +00001488 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1489 }
1490 return 0;
1491}
1492
1493
1494// AddRHS - Implements: X + X --> X << 1
1495struct AddRHS {
1496 Value *RHS;
1497 AddRHS(Value *rhs) : RHS(rhs) {}
1498 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1499 Instruction *apply(BinaryOperator &Add) const {
1500 return new ShiftInst(Instruction::Shl, Add.getOperand(0),
1501 ConstantInt::get(Type::UByteTy, 1));
1502 }
1503};
1504
1505// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1506// iff C1&C2 == 0
1507struct AddMaskingAnd {
1508 Constant *C2;
1509 AddMaskingAnd(Constant *c) : C2(c) {}
1510 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001511 ConstantInt *C1;
Misha Brukmanfd939082005-04-21 23:48:37 +00001512 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001513 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +00001514 }
1515 Instruction *apply(BinaryOperator &Add) const {
Chris Lattner48595f12004-06-10 02:07:29 +00001516 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +00001517 }
1518};
1519
Chris Lattner6e7ba452005-01-01 16:22:27 +00001520static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +00001521 InstCombiner *IC) {
Chris Lattner6e7ba452005-01-01 16:22:27 +00001522 if (isa<CastInst>(I)) {
1523 if (Constant *SOC = dyn_cast<Constant>(SO))
1524 return ConstantExpr::getCast(SOC, I.getType());
Misha Brukmanfd939082005-04-21 23:48:37 +00001525
Chris Lattner6e7ba452005-01-01 16:22:27 +00001526 return IC->InsertNewInstBefore(new CastInst(SO, I.getType(),
1527 SO->getName() + ".cast"), I);
1528 }
1529
Chris Lattner2eefe512004-04-09 19:05:30 +00001530 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +00001531 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1532 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +00001533
Chris Lattner2eefe512004-04-09 19:05:30 +00001534 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1535 if (ConstIsRHS)
Chris Lattner6e7ba452005-01-01 16:22:27 +00001536 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1537 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +00001538 }
1539
1540 Value *Op0 = SO, *Op1 = ConstOperand;
1541 if (!ConstIsRHS)
1542 std::swap(Op0, Op1);
1543 Instruction *New;
Chris Lattner6e7ba452005-01-01 16:22:27 +00001544 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1545 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1546 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
1547 New = new ShiftInst(SI->getOpcode(), Op0, Op1, SO->getName()+".sh");
Chris Lattner326c0f32004-04-10 19:15:56 +00001548 else {
Chris Lattner2eefe512004-04-09 19:05:30 +00001549 assert(0 && "Unknown binary instruction type!");
Chris Lattner326c0f32004-04-10 19:15:56 +00001550 abort();
1551 }
Chris Lattner6e7ba452005-01-01 16:22:27 +00001552 return IC->InsertNewInstBefore(New, I);
1553}
1554
1555// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1556// constant as the other operand, try to fold the binary operator into the
1557// select arguments. This also works for Cast instructions, which obviously do
1558// not have a second operand.
1559static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1560 InstCombiner *IC) {
1561 // Don't modify shared select instructions
1562 if (!SI->hasOneUse()) return 0;
1563 Value *TV = SI->getOperand(1);
1564 Value *FV = SI->getOperand(2);
1565
1566 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +00001567 // Bool selects with constant operands can be folded to logical ops.
1568 if (SI->getType() == Type::BoolTy) return 0;
1569
Chris Lattner6e7ba452005-01-01 16:22:27 +00001570 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1571 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1572
1573 return new SelectInst(SI->getCondition(), SelectTrueVal,
1574 SelectFalseVal);
1575 }
1576 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +00001577}
1578
Chris Lattner4e998b22004-09-29 05:07:12 +00001579
1580/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1581/// node as operand #0, see if we can fold the instruction into the PHI (which
1582/// is only possible if all operands to the PHI are constants).
1583Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1584 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00001585 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001586 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner4e998b22004-09-29 05:07:12 +00001587
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001588 // Check to see if all of the operands of the PHI are constants. If there is
1589 // one non-constant value, remember the BB it is. If there is more than one
1590 // bail out.
1591 BasicBlock *NonConstBB = 0;
1592 for (unsigned i = 0; i != NumPHIValues; ++i)
1593 if (!isa<Constant>(PN->getIncomingValue(i))) {
1594 if (NonConstBB) return 0; // More than one non-const value.
1595 NonConstBB = PN->getIncomingBlock(i);
1596
1597 // If the incoming non-constant value is in I's block, we have an infinite
1598 // loop.
1599 if (NonConstBB == I.getParent())
1600 return 0;
1601 }
1602
1603 // If there is exactly one non-constant value, we can insert a copy of the
1604 // operation in that block. However, if this is a critical edge, we would be
1605 // inserting the computation one some other paths (e.g. inside a loop). Only
1606 // do this if the pred block is unconditionally branching into the phi block.
1607 if (NonConstBB) {
1608 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1609 if (!BI || !BI->isUnconditional()) return 0;
1610 }
Chris Lattner4e998b22004-09-29 05:07:12 +00001611
1612 // Okay, we can do the transformation: create the new PHI node.
1613 PHINode *NewPN = new PHINode(I.getType(), I.getName());
1614 I.setName("");
Chris Lattner55517062005-01-29 00:39:08 +00001615 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner4e998b22004-09-29 05:07:12 +00001616 InsertNewInstBefore(NewPN, *PN);
1617
1618 // Next, add all of the operands to the PHI.
1619 if (I.getNumOperands() == 2) {
1620 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +00001621 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001622 Value *InV;
1623 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1624 InV = ConstantExpr::get(I.getOpcode(), InC, C);
1625 } else {
1626 assert(PN->getIncomingBlock(i) == NonConstBB);
1627 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1628 InV = BinaryOperator::create(BO->getOpcode(),
1629 PN->getIncomingValue(i), C, "phitmp",
1630 NonConstBB->getTerminator());
1631 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
1632 InV = new ShiftInst(SI->getOpcode(),
1633 PN->getIncomingValue(i), C, "phitmp",
1634 NonConstBB->getTerminator());
1635 else
1636 assert(0 && "Unknown binop!");
1637
1638 WorkList.push_back(cast<Instruction>(InV));
1639 }
1640 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00001641 }
1642 } else {
1643 assert(isa<CastInst>(I) && "Unary op should be a cast!");
1644 const Type *RetTy = I.getType();
Chris Lattnerbac32862004-11-14 19:13:23 +00001645 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001646 Value *InV;
1647 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1648 InV = ConstantExpr::getCast(InC, RetTy);
1649 } else {
1650 assert(PN->getIncomingBlock(i) == NonConstBB);
1651 InV = new CastInst(PN->getIncomingValue(i), I.getType(), "phitmp",
1652 NonConstBB->getTerminator());
1653 WorkList.push_back(cast<Instruction>(InV));
1654 }
1655 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00001656 }
1657 }
1658 return ReplaceInstUsesWith(I, NewPN);
1659}
1660
Chris Lattner7e708292002-06-25 16:13:24 +00001661Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00001662 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00001663 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +00001664
Chris Lattner66331a42004-04-10 22:01:55 +00001665 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattnere87597f2004-10-16 18:11:37 +00001666 // X + undef -> undef
1667 if (isa<UndefValue>(RHS))
1668 return ReplaceInstUsesWith(I, RHS);
1669
Chris Lattner66331a42004-04-10 22:01:55 +00001670 // X + 0 --> X
Chris Lattner5e678e02005-10-17 17:56:38 +00001671 if (!I.getType()->isFloatingPoint()) { // NOTE: -0 + +0 = +0.
1672 if (RHSC->isNullValue())
1673 return ReplaceInstUsesWith(I, LHS);
Chris Lattner8532cf62005-10-17 20:18:38 +00001674 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1675 if (CFP->isExactlyValue(-0.0))
1676 return ReplaceInstUsesWith(I, LHS);
Chris Lattner5e678e02005-10-17 17:56:38 +00001677 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001678
Chris Lattner66331a42004-04-10 22:01:55 +00001679 // X + (signbit) --> X ^ signbit
1680 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattner74c51a02006-02-07 08:05:22 +00001681 uint64_t Val = CI->getZExtValue();
Chris Lattner1a074fc2006-02-07 07:00:41 +00001682 if (Val == (1ULL << (CI->getType()->getPrimitiveSizeInBits()-1)))
Chris Lattner48595f12004-06-10 02:07:29 +00001683 return BinaryOperator::createXor(LHS, RHS);
Chris Lattner66331a42004-04-10 22:01:55 +00001684 }
Chris Lattner4e998b22004-09-29 05:07:12 +00001685
1686 if (isa<PHINode>(LHS))
1687 if (Instruction *NV = FoldOpIntoPhi(I))
1688 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +00001689
Chris Lattner4f637d42006-01-06 17:59:59 +00001690 ConstantInt *XorRHS = 0;
1691 Value *XorLHS = 0;
Chris Lattner5931c542005-09-24 23:43:33 +00001692 if (match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
1693 unsigned TySizeBits = I.getType()->getPrimitiveSizeInBits();
1694 int64_t RHSSExt = cast<ConstantInt>(RHSC)->getSExtValue();
1695 uint64_t RHSZExt = cast<ConstantInt>(RHSC)->getZExtValue();
1696
1697 uint64_t C0080Val = 1ULL << 31;
1698 int64_t CFF80Val = -C0080Val;
1699 unsigned Size = 32;
1700 do {
1701 if (TySizeBits > Size) {
1702 bool Found = false;
1703 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1704 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
1705 if (RHSSExt == CFF80Val) {
1706 if (XorRHS->getZExtValue() == C0080Val)
1707 Found = true;
1708 } else if (RHSZExt == C0080Val) {
1709 if (XorRHS->getSExtValue() == CFF80Val)
1710 Found = true;
1711 }
1712 if (Found) {
1713 // This is a sign extend if the top bits are known zero.
Chris Lattner68d5ff22006-02-09 07:38:58 +00001714 uint64_t Mask = ~0ULL;
Chris Lattner3bedbd92006-02-07 07:27:52 +00001715 Mask <<= 64-(TySizeBits-Size);
Chris Lattner68d5ff22006-02-09 07:38:58 +00001716 Mask &= XorLHS->getType()->getIntegralTypeMask();
Chris Lattner3bedbd92006-02-07 07:27:52 +00001717 if (!MaskedValueIsZero(XorLHS, Mask))
Chris Lattner5931c542005-09-24 23:43:33 +00001718 Size = 0; // Not a sign ext, but can't be any others either.
1719 goto FoundSExt;
1720 }
1721 }
1722 Size >>= 1;
1723 C0080Val >>= Size;
1724 CFF80Val >>= Size;
1725 } while (Size >= 8);
1726
1727FoundSExt:
1728 const Type *MiddleType = 0;
1729 switch (Size) {
1730 default: break;
1731 case 32: MiddleType = Type::IntTy; break;
1732 case 16: MiddleType = Type::ShortTy; break;
1733 case 8: MiddleType = Type::SByteTy; break;
1734 }
1735 if (MiddleType) {
1736 Instruction *NewTrunc = new CastInst(XorLHS, MiddleType, "sext");
1737 InsertNewInstBefore(NewTrunc, I);
1738 return new CastInst(NewTrunc, I.getType());
1739 }
1740 }
Chris Lattner66331a42004-04-10 22:01:55 +00001741 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00001742
Chris Lattner564a7272003-08-13 19:01:45 +00001743 // X + X --> X << 1
Robert Bocchino71698282004-07-27 21:02:21 +00001744 if (I.getType()->isInteger()) {
Chris Lattner564a7272003-08-13 19:01:45 +00001745 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +00001746
1747 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
1748 if (RHSI->getOpcode() == Instruction::Sub)
1749 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
1750 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
1751 }
1752 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
1753 if (LHSI->getOpcode() == Instruction::Sub)
1754 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
1755 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
1756 }
Robert Bocchino71698282004-07-27 21:02:21 +00001757 }
Chris Lattnere92d2f42003-08-13 04:18:28 +00001758
Chris Lattner5c4afb92002-05-08 22:46:53 +00001759 // -A + B --> B - A
Chris Lattner8d969642003-03-10 23:06:50 +00001760 if (Value *V = dyn_castNegVal(LHS))
Chris Lattner48595f12004-06-10 02:07:29 +00001761 return BinaryOperator::createSub(RHS, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00001762
1763 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +00001764 if (!isa<Constant>(RHS))
1765 if (Value *V = dyn_castNegVal(RHS))
Chris Lattner48595f12004-06-10 02:07:29 +00001766 return BinaryOperator::createSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001767
Misha Brukmanfd939082005-04-21 23:48:37 +00001768
Chris Lattner50af16a2004-11-13 19:50:12 +00001769 ConstantInt *C2;
1770 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
1771 if (X == RHS) // X*C + X --> X * (C+1)
1772 return BinaryOperator::createMul(RHS, AddOne(C2));
1773
1774 // X*C1 + X*C2 --> X * (C1+C2)
1775 ConstantInt *C1;
1776 if (X == dyn_castFoldableMul(RHS, C1))
1777 return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +00001778 }
1779
1780 // X + X*C --> X * (C+1)
Chris Lattner50af16a2004-11-13 19:50:12 +00001781 if (dyn_castFoldableMul(RHS, C2) == LHS)
1782 return BinaryOperator::createMul(LHS, AddOne(C2));
1783
Chris Lattnerad3448c2003-02-18 19:57:07 +00001784
Chris Lattner564a7272003-08-13 19:01:45 +00001785 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001786 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattner564a7272003-08-13 19:01:45 +00001787 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
Chris Lattnerc8802d22003-03-11 00:12:48 +00001788
Chris Lattner6b032052003-10-02 15:11:26 +00001789 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00001790 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001791 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
1792 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
1793 return BinaryOperator::createSub(C, X);
Chris Lattner6b032052003-10-02 15:11:26 +00001794 }
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001795
Chris Lattnerb99d6b12004-10-08 05:07:56 +00001796 // (X & FF00) + xx00 -> (X+xx00) & FF00
1797 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
1798 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
1799 if (Anded == CRHS) {
1800 // See if all bits from the first bit set in the Add RHS up are included
1801 // in the mask. First, get the rightmost bit.
Reid Spencerb83eb642006-10-20 07:07:24 +00001802 uint64_t AddRHSV = CRHS->getZExtValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00001803
1804 // Form a mask of all bits from the lowest bit added through the top.
1805 uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
Chris Lattner1a074fc2006-02-07 07:00:41 +00001806 AddRHSHighBits &= C2->getType()->getIntegralTypeMask();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00001807
1808 // See if the and mask includes all of these bits.
Reid Spencerb83eb642006-10-20 07:07:24 +00001809 uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getZExtValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00001810
Chris Lattnerb99d6b12004-10-08 05:07:56 +00001811 if (AddRHSHighBits == AddRHSHighBitsAnd) {
1812 // Okay, the xform is safe. Insert the new add pronto.
1813 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
1814 LHS->getName()), I);
1815 return BinaryOperator::createAnd(NewAdd, C2);
1816 }
1817 }
1818 }
1819
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001820 // Try to fold constant add into select arguments.
1821 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +00001822 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001823 return R;
Chris Lattner6b032052003-10-02 15:11:26 +00001824 }
1825
Reid Spencer1628cec2006-10-26 06:15:43 +00001826 // add (cast *A to intptrtype) B ->
1827 // cast (GEP (cast *A to sbyte*) B) ->
1828 // intptrtype
Andrew Lenharth16d79552006-09-19 18:24:51 +00001829 {
1830 CastInst* CI = dyn_cast<CastInst>(LHS);
1831 Value* Other = RHS;
1832 if (!CI) {
1833 CI = dyn_cast<CastInst>(RHS);
1834 Other = LHS;
1835 }
Andrew Lenharth45633262006-09-20 15:37:57 +00001836 if (CI && CI->getType()->isSized() &&
1837 (CI->getType()->getPrimitiveSize() ==
1838 TD->getIntPtrType()->getPrimitiveSize())
1839 && isa<PointerType>(CI->getOperand(0)->getType())) {
1840 Value* I2 = InsertCastBefore(CI->getOperand(0),
1841 PointerType::get(Type::SByteTy), I);
1842 I2 = InsertNewInstBefore(new GetElementPtrInst(I2, Other, "ctg2"), I);
1843 return new CastInst(I2, CI->getType());
Andrew Lenharth16d79552006-09-19 18:24:51 +00001844 }
1845 }
1846
Chris Lattner7e708292002-06-25 16:13:24 +00001847 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001848}
1849
Chris Lattner1ba5bcd2003-07-22 21:46:59 +00001850// isSignBit - Return true if the value represented by the constant only has the
1851// highest order bit set.
1852static bool isSignBit(ConstantInt *CI) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00001853 unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencerb83eb642006-10-20 07:07:24 +00001854 return (CI->getZExtValue() & (~0ULL >> (64-NumBits))) == (1ULL << (NumBits-1));
Chris Lattner1ba5bcd2003-07-22 21:46:59 +00001855}
1856
Chris Lattnerbfe492b2004-03-13 00:11:49 +00001857/// RemoveNoopCast - Strip off nonconverting casts from the value.
1858///
1859static Value *RemoveNoopCast(Value *V) {
1860 if (CastInst *CI = dyn_cast<CastInst>(V)) {
1861 const Type *CTy = CI->getType();
1862 const Type *OpTy = CI->getOperand(0)->getType();
1863 if (CTy->isInteger() && OpTy->isInteger()) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00001864 if (CTy->getPrimitiveSizeInBits() == OpTy->getPrimitiveSizeInBits())
Chris Lattnerbfe492b2004-03-13 00:11:49 +00001865 return RemoveNoopCast(CI->getOperand(0));
1866 } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
1867 return RemoveNoopCast(CI->getOperand(0));
1868 }
1869 return V;
1870}
1871
Chris Lattner7e708292002-06-25 16:13:24 +00001872Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00001873 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00001874
Chris Lattner233f7dc2002-08-12 21:17:25 +00001875 if (Op0 == Op1) // sub X, X -> 0
1876 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001877
Chris Lattner233f7dc2002-08-12 21:17:25 +00001878 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattner8d969642003-03-10 23:06:50 +00001879 if (Value *V = dyn_castNegVal(Op1))
Chris Lattner48595f12004-06-10 02:07:29 +00001880 return BinaryOperator::createAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00001881
Chris Lattnere87597f2004-10-16 18:11:37 +00001882 if (isa<UndefValue>(Op0))
1883 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
1884 if (isa<UndefValue>(Op1))
1885 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
1886
Chris Lattnerd65460f2003-11-05 01:06:05 +00001887 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
1888 // Replace (-1 - A) with (~A)...
Chris Lattnera2881962003-02-18 19:28:33 +00001889 if (C->isAllOnesValue())
1890 return BinaryOperator::createNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +00001891
Chris Lattnerd65460f2003-11-05 01:06:05 +00001892 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00001893 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001894 if (match(Op1, m_Not(m_Value(X))))
1895 return BinaryOperator::createAdd(X,
Chris Lattner48595f12004-06-10 02:07:29 +00001896 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
Chris Lattner9c290672004-03-12 23:53:13 +00001897 // -((uint)X >> 31) -> ((int)X >> 31)
1898 // -((int)X >> 31) -> ((uint)X >> 31)
Chris Lattnerbfe492b2004-03-13 00:11:49 +00001899 if (C->isNullValue()) {
1900 Value *NoopCastedRHS = RemoveNoopCast(Op1);
1901 if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
Chris Lattner9c290672004-03-12 23:53:13 +00001902 if (SI->getOpcode() == Instruction::Shr)
Reid Spencerb83eb642006-10-20 07:07:24 +00001903 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00001904 const Type *NewTy;
Chris Lattnerbfe492b2004-03-13 00:11:49 +00001905 if (SI->getType()->isSigned())
Chris Lattner5dd04022004-06-17 18:16:02 +00001906 NewTy = SI->getType()->getUnsignedVersion();
Chris Lattner9c290672004-03-12 23:53:13 +00001907 else
Chris Lattner5dd04022004-06-17 18:16:02 +00001908 NewTy = SI->getType()->getSignedVersion();
Chris Lattner9c290672004-03-12 23:53:13 +00001909 // Check to see if we are shifting out everything but the sign bit.
Reid Spencerb83eb642006-10-20 07:07:24 +00001910 if (CU->getZExtValue() ==
1911 SI->getType()->getPrimitiveSizeInBits()-1) {
Chris Lattner9c290672004-03-12 23:53:13 +00001912 // Ok, the transformation is safe. Insert a cast of the incoming
1913 // value, then the new shift, then the new cast.
Reid Spencer811b0cb2006-10-26 19:19:06 +00001914 Value *InV = InsertCastBefore(SI->getOperand(0), NewTy, I);
1915 Instruction *NewShift = new ShiftInst(Instruction::Shr, InV,
Chris Lattner9c290672004-03-12 23:53:13 +00001916 CU, SI->getName());
Chris Lattnerbfe492b2004-03-13 00:11:49 +00001917 if (NewShift->getType() == I.getType())
1918 return NewShift;
1919 else {
Reid Spencer811b0cb2006-10-26 19:19:06 +00001920 InsertNewInstBefore(NewShift, I);
Chris Lattnerbfe492b2004-03-13 00:11:49 +00001921 return new CastInst(NewShift, I.getType());
1922 }
Chris Lattner9c290672004-03-12 23:53:13 +00001923 }
1924 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00001925 }
Chris Lattner2eefe512004-04-09 19:05:30 +00001926
1927 // Try to fold constant sub into select arguments.
1928 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00001929 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00001930 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00001931
1932 if (isa<PHINode>(Op0))
1933 if (Instruction *NV = FoldOpIntoPhi(I))
1934 return NV;
Chris Lattnerd65460f2003-11-05 01:06:05 +00001935 }
1936
Chris Lattner43d84d62005-04-07 16:15:25 +00001937 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
1938 if (Op1I->getOpcode() == Instruction::Add &&
1939 !Op0->getType()->isFloatingPoint()) {
Chris Lattner08954a22005-04-07 16:28:01 +00001940 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Chris Lattner43d84d62005-04-07 16:15:25 +00001941 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00001942 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Chris Lattner43d84d62005-04-07 16:15:25 +00001943 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00001944 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
1945 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
1946 // C1-(X+C2) --> (C1-C2)-X
1947 return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
1948 Op1I->getOperand(0));
1949 }
Chris Lattner43d84d62005-04-07 16:15:25 +00001950 }
1951
Chris Lattnerfd059242003-10-15 16:48:29 +00001952 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00001953 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
1954 // is not used by anyone else...
1955 //
Chris Lattner0517e722004-02-02 20:09:56 +00001956 if (Op1I->getOpcode() == Instruction::Sub &&
1957 !Op1I->getType()->isFloatingPoint()) {
Chris Lattnera2881962003-02-18 19:28:33 +00001958 // Swap the two operands of the subexpr...
1959 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
1960 Op1I->setOperand(0, IIOp1);
1961 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00001962
Chris Lattnera2881962003-02-18 19:28:33 +00001963 // Create the new top level add instruction...
Chris Lattner48595f12004-06-10 02:07:29 +00001964 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00001965 }
1966
1967 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
1968 //
1969 if (Op1I->getOpcode() == Instruction::And &&
1970 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
1971 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
1972
Chris Lattnerf523d062004-06-09 05:08:07 +00001973 Value *NewNot =
1974 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattner48595f12004-06-10 02:07:29 +00001975 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00001976 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00001977
Reid Spencerac5209e2006-10-16 23:08:08 +00001978 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer1628cec2006-10-26 06:15:43 +00001979 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencerb83eb642006-10-20 07:07:24 +00001980 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Reid Spencer1628cec2006-10-26 06:15:43 +00001981 if (CSI->isNullValue())
Chris Lattner91ccc152004-10-06 15:08:25 +00001982 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Reid Spencer1628cec2006-10-26 06:15:43 +00001983 return BinaryOperator::createSDiv(Op1I->getOperand(0),
Chris Lattner91ccc152004-10-06 15:08:25 +00001984 ConstantExpr::getNeg(DivRHS));
1985
Chris Lattnerad3448c2003-02-18 19:57:07 +00001986 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00001987 ConstantInt *C2 = 0;
Chris Lattner50af16a2004-11-13 19:50:12 +00001988 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Misha Brukmanfd939082005-04-21 23:48:37 +00001989 Constant *CP1 =
Chris Lattner50af16a2004-11-13 19:50:12 +00001990 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
Chris Lattner48595f12004-06-10 02:07:29 +00001991 return BinaryOperator::createMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00001992 }
Chris Lattner40371712002-05-09 01:29:19 +00001993 }
Chris Lattner43d84d62005-04-07 16:15:25 +00001994 }
Chris Lattnera2881962003-02-18 19:28:33 +00001995
Chris Lattner7edc8c22005-04-07 17:14:51 +00001996 if (!Op0->getType()->isFloatingPoint())
1997 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
1998 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00001999 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2000 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2001 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2002 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner7edc8c22005-04-07 17:14:51 +00002003 } else if (Op0I->getOpcode() == Instruction::Sub) {
2004 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
2005 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00002006 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002007
Chris Lattner50af16a2004-11-13 19:50:12 +00002008 ConstantInt *C1;
2009 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2010 if (X == Op1) { // X*C - X --> X * (C-1)
2011 Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
2012 return BinaryOperator::createMul(Op1, CP1);
2013 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00002014
Chris Lattner50af16a2004-11-13 19:50:12 +00002015 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2016 if (X == dyn_castFoldableMul(Op1, C2))
2017 return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
2018 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002019 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002020}
2021
Chris Lattner4cb170c2004-02-23 06:38:22 +00002022/// isSignBitCheck - Given an exploded setcc instruction, return true if it is
2023/// really just returns true if the most significant (sign) bit is set.
2024static bool isSignBitCheck(unsigned Opcode, Value *LHS, ConstantInt *RHS) {
2025 if (RHS->getType()->isSigned()) {
2026 // True if source is LHS < 0 or LHS <= -1
2027 return Opcode == Instruction::SetLT && RHS->isNullValue() ||
2028 Opcode == Instruction::SetLE && RHS->isAllOnesValue();
2029 } else {
Reid Spencerb83eb642006-10-20 07:07:24 +00002030 ConstantInt *RHSC = cast<ConstantInt>(RHS);
Chris Lattner4cb170c2004-02-23 06:38:22 +00002031 // True if source is LHS > 127 or LHS >= 128, where the constants depend on
2032 // the size of the integer type.
2033 if (Opcode == Instruction::SetGE)
Reid Spencerb83eb642006-10-20 07:07:24 +00002034 return RHSC->getZExtValue() ==
Chris Lattner484d3cf2005-04-24 06:59:08 +00002035 1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1);
Chris Lattner4cb170c2004-02-23 06:38:22 +00002036 if (Opcode == Instruction::SetGT)
Reid Spencerb83eb642006-10-20 07:07:24 +00002037 return RHSC->getZExtValue() ==
Chris Lattner484d3cf2005-04-24 06:59:08 +00002038 (1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1))-1;
Chris Lattner4cb170c2004-02-23 06:38:22 +00002039 }
2040 return false;
2041}
2042
Chris Lattner7e708292002-06-25 16:13:24 +00002043Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002044 bool Changed = SimplifyCommutative(I);
Chris Lattnera2881962003-02-18 19:28:33 +00002045 Value *Op0 = I.getOperand(0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002046
Chris Lattnere87597f2004-10-16 18:11:37 +00002047 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2048 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2049
Chris Lattner233f7dc2002-08-12 21:17:25 +00002050 // Simplify mul instructions with a constant RHS...
Chris Lattnera2881962003-02-18 19:28:33 +00002051 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2052 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00002053
2054 // ((X << C1)*C2) == (X * (C2 << C1))
2055 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
2056 if (SI->getOpcode() == Instruction::Shl)
2057 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattner48595f12004-06-10 02:07:29 +00002058 return BinaryOperator::createMul(SI->getOperand(0),
2059 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00002060
Chris Lattner515c97c2003-09-11 22:24:54 +00002061 if (CI->isNullValue())
2062 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2063 if (CI->equalsInt(1)) // X * 1 == X
2064 return ReplaceInstUsesWith(I, Op0);
2065 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner0af1fab2003-06-25 17:09:20 +00002066 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00002067
Reid Spencerb83eb642006-10-20 07:07:24 +00002068 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getZExtValue();
Chris Lattnerbcd7db52005-08-02 19:16:58 +00002069 if (isPowerOf2_64(Val)) { // Replace X*(2^C) with X << C
2070 uint64_t C = Log2_64(Val);
Chris Lattnera2881962003-02-18 19:28:33 +00002071 return new ShiftInst(Instruction::Shl, Op0,
Reid Spencerb83eb642006-10-20 07:07:24 +00002072 ConstantInt::get(Type::UByteTy, C));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00002073 }
Robert Bocchino71698282004-07-27 21:02:21 +00002074 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattnera2881962003-02-18 19:28:33 +00002075 if (Op1F->isNullValue())
2076 return ReplaceInstUsesWith(I, Op1);
Chris Lattner6c1ce212002-04-29 22:24:47 +00002077
Chris Lattnera2881962003-02-18 19:28:33 +00002078 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2079 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2080 if (Op1F->getValue() == 1.0)
2081 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2082 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002083
2084 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2085 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2086 isa<ConstantInt>(Op0I->getOperand(1))) {
2087 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2088 Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
2089 Op1, "tmp");
2090 InsertNewInstBefore(Add, I);
2091 Value *C1C2 = ConstantExpr::getMul(Op1,
2092 cast<Constant>(Op0I->getOperand(1)));
2093 return BinaryOperator::createAdd(Add, C1C2);
2094
2095 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002096
2097 // Try to fold constant mul into select arguments.
2098 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002099 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002100 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002101
2102 if (isa<PHINode>(Op0))
2103 if (Instruction *NV = FoldOpIntoPhi(I))
2104 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002105 }
2106
Chris Lattnera4f445b2003-03-10 23:23:04 +00002107 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2108 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattner48595f12004-06-10 02:07:29 +00002109 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00002110
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002111 // If one of the operands of the multiply is a cast from a boolean value, then
2112 // we know the bool is either zero or one, so this is a 'masking' multiply.
2113 // See if we can simplify things based on how the boolean was originally
2114 // formed.
2115 CastInst *BoolCast = 0;
2116 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(0)))
2117 if (CI->getOperand(0)->getType() == Type::BoolTy)
2118 BoolCast = CI;
2119 if (!BoolCast)
2120 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(1)))
2121 if (CI->getOperand(0)->getType() == Type::BoolTy)
2122 BoolCast = CI;
2123 if (BoolCast) {
2124 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BoolCast->getOperand(0))) {
2125 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2126 const Type *SCOpTy = SCIOp0->getType();
2127
Chris Lattner4cb170c2004-02-23 06:38:22 +00002128 // If the setcc is true iff the sign bit of X is set, then convert this
2129 // multiply into a shift/and combination.
2130 if (isa<ConstantInt>(SCIOp1) &&
2131 isSignBitCheck(SCI->getOpcode(), SCIOp0, cast<ConstantInt>(SCIOp1))) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002132 // Shift the X value right to turn it into "all signbits".
Reid Spencerb83eb642006-10-20 07:07:24 +00002133 Constant *Amt = ConstantInt::get(Type::UByteTy,
Chris Lattner484d3cf2005-04-24 06:59:08 +00002134 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattner4cb170c2004-02-23 06:38:22 +00002135 if (SCIOp0->getType()->isUnsigned()) {
Chris Lattner5dd04022004-06-17 18:16:02 +00002136 const Type *NewTy = SCIOp0->getType()->getSignedVersion();
Reid Spencer811b0cb2006-10-26 19:19:06 +00002137 SCIOp0 = InsertCastBefore(SCIOp0, NewTy, I);
Chris Lattner4cb170c2004-02-23 06:38:22 +00002138 }
2139
2140 Value *V =
2141 InsertNewInstBefore(new ShiftInst(Instruction::Shr, SCIOp0, Amt,
2142 BoolCast->getOperand(0)->getName()+
2143 ".mask"), I);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002144
2145 // If the multiply type is not the same as the source type, sign extend
2146 // or truncate to the multiply type.
2147 if (I.getType() != V->getType())
Reid Spencer811b0cb2006-10-26 19:19:06 +00002148 V = InsertCastBefore(V, I.getType(), I);
Misha Brukmanfd939082005-04-21 23:48:37 +00002149
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002150 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattner48595f12004-06-10 02:07:29 +00002151 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002152 }
2153 }
2154 }
2155
Chris Lattner7e708292002-06-25 16:13:24 +00002156 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002157}
2158
Reid Spencer1628cec2006-10-26 06:15:43 +00002159/// This function implements the transforms on div instructions that work
2160/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2161/// used by the visitors to those instructions.
2162/// @brief Transforms common to all three div instructions
2163Instruction* InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002164 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00002165
Reid Spencer1628cec2006-10-26 06:15:43 +00002166 // undef / X -> 0
2167 if (isa<UndefValue>(Op0))
Chris Lattner857e8cd2004-12-12 21:48:58 +00002168 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Reid Spencer1628cec2006-10-26 06:15:43 +00002169
2170 // X / undef -> undef
Chris Lattner857e8cd2004-12-12 21:48:58 +00002171 if (isa<UndefValue>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00002172 return ReplaceInstUsesWith(I, Op1);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002173
Reid Spencer1628cec2006-10-26 06:15:43 +00002174 // Handle cases involving: div X, (select Cond, Y, Z)
Chris Lattner8e49e082006-09-09 20:26:32 +00002175 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2176 // div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in the
Reid Spencer1628cec2006-10-26 06:15:43 +00002177 // same basic block, then we replace the select with Y, and the condition
2178 // of the select with false (if the cond value is in the same BB). If the
Chris Lattner8e49e082006-09-09 20:26:32 +00002179 // select has uses other than the div, this allows them to be simplified
Reid Spencer1628cec2006-10-26 06:15:43 +00002180 // also. Note that div X, Y is just as good as div X, 0 (undef)
Chris Lattner8e49e082006-09-09 20:26:32 +00002181 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2182 if (ST->isNullValue()) {
2183 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2184 if (CondI && CondI->getParent() == I.getParent())
Chris Lattner47811b72006-09-28 23:35:22 +00002185 UpdateValueUsesWith(CondI, ConstantBool::getFalse());
Chris Lattner8e49e082006-09-09 20:26:32 +00002186 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2187 I.setOperand(1, SI->getOperand(2));
2188 else
2189 UpdateValueUsesWith(SI, SI->getOperand(2));
2190 return &I;
2191 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002192
Chris Lattner8e49e082006-09-09 20:26:32 +00002193 // Likewise for: div X, (Cond ? Y : 0) -> div X, Y
2194 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2195 if (ST->isNullValue()) {
2196 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2197 if (CondI && CondI->getParent() == I.getParent())
Chris Lattner47811b72006-09-28 23:35:22 +00002198 UpdateValueUsesWith(CondI, ConstantBool::getTrue());
Chris Lattner8e49e082006-09-09 20:26:32 +00002199 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2200 I.setOperand(1, SI->getOperand(1));
2201 else
2202 UpdateValueUsesWith(SI, SI->getOperand(1));
2203 return &I;
2204 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002205 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002206
Reid Spencer1628cec2006-10-26 06:15:43 +00002207 return 0;
2208}
Misha Brukmanfd939082005-04-21 23:48:37 +00002209
Reid Spencer1628cec2006-10-26 06:15:43 +00002210/// This function implements the transforms common to both integer division
2211/// instructions (udiv and sdiv). It is called by the visitors to those integer
2212/// division instructions.
2213/// @brief Common integer divide transforms
2214Instruction* InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2215 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2216
2217 if (Instruction *Common = commonDivTransforms(I))
2218 return Common;
2219
2220 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2221 // div X, 1 == X
2222 if (RHS->equalsInt(1))
2223 return ReplaceInstUsesWith(I, Op0);
2224
2225 // (X / C1) / C2 -> X / (C1*C2)
2226 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2227 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2228 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2229 return BinaryOperator::create(I.getOpcode(), LHS->getOperand(0),
2230 ConstantExpr::getMul(RHS, LHSRHS));
Chris Lattnerbf70b832005-04-08 04:03:26 +00002231 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002232
2233 if (!RHS->isNullValue()) { // avoid X udiv 0
2234 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2235 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2236 return R;
2237 if (isa<PHINode>(Op0))
2238 if (Instruction *NV = FoldOpIntoPhi(I))
2239 return NV;
2240 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002241 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002242
Chris Lattnera2881962003-02-18 19:28:33 +00002243 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00002244 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00002245 if (LHS->equalsInt(0))
2246 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2247
Reid Spencer1628cec2006-10-26 06:15:43 +00002248 return 0;
2249}
2250
2251Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2252 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2253
2254 // Handle the integer div common cases
2255 if (Instruction *Common = commonIDivTransforms(I))
2256 return Common;
2257
2258 // X udiv C^2 -> X >> C
2259 // Check to see if this is an unsigned division with an exact power of 2,
2260 // if so, convert to a right shift.
2261 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2262 if (uint64_t Val = C->getZExtValue()) // Don't break X / 0
2263 if (isPowerOf2_64(Val)) {
2264 uint64_t ShiftAmt = Log2_64(Val);
2265 Value* X = Op0;
2266 const Type* XTy = X->getType();
2267 bool isSigned = XTy->isSigned();
2268 if (isSigned)
2269 X = InsertCastBefore(X, XTy->getUnsignedVersion(), I);
2270 Instruction* Result =
2271 new ShiftInst(Instruction::Shr, X,
2272 ConstantInt::get(Type::UByteTy, ShiftAmt));
2273 if (!isSigned)
2274 return Result;
2275 InsertNewInstBefore(Result, I);
2276 return new CastInst(Result, XTy->getSignedVersion(), I.getName());
2277 }
2278 }
2279
2280 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
2281 if (ShiftInst *RHSI = dyn_cast<ShiftInst>(I.getOperand(1))) {
2282 if (RHSI->getOpcode() == Instruction::Shl &&
2283 isa<ConstantInt>(RHSI->getOperand(0))) {
2284 uint64_t C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
2285 if (isPowerOf2_64(C1)) {
2286 Value *N = RHSI->getOperand(1);
2287 const Type* NTy = N->getType();
2288 bool isSigned = NTy->isSigned();
2289 if (uint64_t C2 = Log2_64(C1)) {
2290 if (isSigned) {
2291 NTy = NTy->getUnsignedVersion();
2292 N = InsertCastBefore(N, NTy, I);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002293 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002294 Constant *C2V = ConstantInt::get(NTy, C2);
2295 N = InsertNewInstBefore(BinaryOperator::createAdd(N, C2V, "tmp"), I);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002296 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002297 Instruction* Result = new ShiftInst(Instruction::Shr, Op0, N);
2298 if (!isSigned)
2299 return Result;
2300 InsertNewInstBefore(Result, I);
2301 return new CastInst(Result, NTy->getSignedVersion(), I.getName());
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002302 }
2303 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00002304 }
2305
Reid Spencer1628cec2006-10-26 06:15:43 +00002306 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2307 // where C1&C2 are powers of two.
2308 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2309 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2310 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))
2311 if (!STO->isNullValue() && !STO->isNullValue()) {
2312 uint64_t TVA = STO->getZExtValue(), FVA = SFO->getZExtValue();
2313 if (isPowerOf2_64(TVA) && isPowerOf2_64(FVA)) {
2314 // Compute the shift amounts
2315 unsigned TSA = Log2_64(TVA), FSA = Log2_64(FVA);
2316 // Make sure we get the unsigned version of X
2317 Value* X = Op0;
2318 const Type* origXTy = X->getType();
2319 bool isSigned = origXTy->isSigned();
2320 if (isSigned)
2321 X = InsertCastBefore(X, X->getType()->getUnsignedVersion(), I);
2322 // Construct the "on true" case of the select
2323 Constant *TC = ConstantInt::get(Type::UByteTy, TSA);
2324 Instruction *TSI =
2325 new ShiftInst(Instruction::Shr, X, TC, SI->getName()+".t");
2326 TSI = InsertNewInstBefore(TSI, I);
2327
2328 // Construct the "on false" case of the select
2329 Constant *FC = ConstantInt::get(Type::UByteTy, FSA);
2330 Instruction *FSI =
2331 new ShiftInst(Instruction::Shr, X, FC, SI->getName()+".f");
2332 FSI = InsertNewInstBefore(FSI, I);
2333
2334 // construct the select instruction and return it.
2335 SelectInst* NewSI =
2336 new SelectInst(SI->getOperand(0), TSI, FSI, SI->getName());
2337 if (!isSigned)
2338 return NewSI;
2339 InsertNewInstBefore(NewSI, I);
2340 return new CastInst(NewSI, origXTy, NewSI->getName());
2341 }
2342 }
2343 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002344 return 0;
2345}
2346
Reid Spencer1628cec2006-10-26 06:15:43 +00002347Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2348 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2349
2350 // Handle the integer div common cases
2351 if (Instruction *Common = commonIDivTransforms(I))
2352 return Common;
2353
2354 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2355 // sdiv X, -1 == -X
2356 if (RHS->isAllOnesValue())
2357 return BinaryOperator::createNeg(Op0);
2358
2359 // -X/C -> X/-C
2360 if (Value *LHSNeg = dyn_castNegVal(Op0))
2361 return BinaryOperator::createSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2362 }
2363
2364 // If the sign bits of both operands are zero (i.e. we can prove they are
2365 // unsigned inputs), turn this into a udiv.
2366 if (I.getType()->isInteger()) {
2367 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2368 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2369 return BinaryOperator::createUDiv(Op0, Op1, I.getName());
2370 }
2371 }
2372
2373 return 0;
2374}
2375
2376Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2377 return commonDivTransforms(I);
2378}
Chris Lattner3f5b8772002-05-06 16:14:14 +00002379
Chris Lattnerdb3f8732006-03-02 06:50:58 +00002380/// GetFactor - If we can prove that the specified value is at least a multiple
2381/// of some factor, return that factor.
2382static Constant *GetFactor(Value *V) {
2383 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2384 return CI;
2385
2386 // Unless we can be tricky, we know this is a multiple of 1.
2387 Constant *Result = ConstantInt::get(V->getType(), 1);
2388
2389 Instruction *I = dyn_cast<Instruction>(V);
2390 if (!I) return Result;
2391
2392 if (I->getOpcode() == Instruction::Mul) {
2393 // Handle multiplies by a constant, etc.
2394 return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
2395 GetFactor(I->getOperand(1)));
2396 } else if (I->getOpcode() == Instruction::Shl) {
2397 // (X<<C) -> X * (1 << C)
2398 if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
2399 ShRHS = ConstantExpr::getShl(Result, ShRHS);
2400 return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
2401 }
2402 } else if (I->getOpcode() == Instruction::And) {
2403 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
2404 // X & 0xFFF0 is known to be a multiple of 16.
2405 unsigned Zeros = CountTrailingZeros_64(RHS->getZExtValue());
2406 if (Zeros != V->getType()->getPrimitiveSizeInBits())
2407 return ConstantExpr::getShl(Result,
Reid Spencerb83eb642006-10-20 07:07:24 +00002408 ConstantInt::get(Type::UByteTy, Zeros));
Chris Lattnerdb3f8732006-03-02 06:50:58 +00002409 }
2410 } else if (I->getOpcode() == Instruction::Cast) {
2411 Value *Op = I->getOperand(0);
2412 // Only handle int->int casts.
2413 if (!Op->getType()->isInteger()) return Result;
2414 return ConstantExpr::getCast(GetFactor(Op), V->getType());
2415 }
2416 return Result;
2417}
2418
Reid Spencer0a783f72006-11-02 01:53:59 +00002419/// This function implements the transforms on rem instructions that work
2420/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
2421/// is used by the visitors to those instructions.
2422/// @brief Transforms common to all three rem instructions
2423Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002424 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer0a783f72006-11-02 01:53:59 +00002425
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002426 // 0 % X == 0, we don't need to preserve faults!
2427 if (Constant *LHS = dyn_cast<Constant>(Op0))
2428 if (LHS->isNullValue())
2429 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2430
2431 if (isa<UndefValue>(Op0)) // undef % X -> 0
2432 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2433 if (isa<UndefValue>(Op1))
2434 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer0a783f72006-11-02 01:53:59 +00002435
2436 // Handle cases involving: rem X, (select Cond, Y, Z)
2437 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2438 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
2439 // the same basic block, then we replace the select with Y, and the
2440 // condition of the select with false (if the cond value is in the same
2441 // BB). If the select has uses other than the div, this allows them to be
2442 // simplified also.
2443 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2444 if (ST->isNullValue()) {
2445 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2446 if (CondI && CondI->getParent() == I.getParent())
2447 UpdateValueUsesWith(CondI, ConstantBool::getFalse());
2448 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2449 I.setOperand(1, SI->getOperand(2));
2450 else
2451 UpdateValueUsesWith(SI, SI->getOperand(2));
Chris Lattner5b73c082004-07-06 07:01:22 +00002452 return &I;
2453 }
Reid Spencer0a783f72006-11-02 01:53:59 +00002454 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2455 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2456 if (ST->isNullValue()) {
2457 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2458 if (CondI && CondI->getParent() == I.getParent())
2459 UpdateValueUsesWith(CondI, ConstantBool::getTrue());
2460 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2461 I.setOperand(1, SI->getOperand(1));
2462 else
2463 UpdateValueUsesWith(SI, SI->getOperand(1));
2464 return &I;
2465 }
Chris Lattner11a49f22005-11-05 07:28:37 +00002466 }
Chris Lattner5b73c082004-07-06 07:01:22 +00002467
Reid Spencer0a783f72006-11-02 01:53:59 +00002468 return 0;
2469}
2470
2471/// This function implements the transforms common to both integer remainder
2472/// instructions (urem and srem). It is called by the visitors to those integer
2473/// remainder instructions.
2474/// @brief Common integer remainder transforms
2475Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2476 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2477
2478 if (Instruction *common = commonRemTransforms(I))
2479 return common;
2480
Chris Lattner857e8cd2004-12-12 21:48:58 +00002481 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002482 // X % 0 == undef, we don't need to preserve faults!
2483 if (RHS->equalsInt(0))
2484 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2485
Chris Lattnera2881962003-02-18 19:28:33 +00002486 if (RHS->equalsInt(1)) // X % 1 == 0
2487 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2488
Chris Lattner97943922006-02-28 05:49:21 +00002489 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2490 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2491 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2492 return R;
2493 } else if (isa<PHINode>(Op0I)) {
2494 if (Instruction *NV = FoldOpIntoPhi(I))
2495 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00002496 }
Reid Spencer0a783f72006-11-02 01:53:59 +00002497 // (X * C1) % C2 --> 0 iff C1 % C2 == 0
2498 if (ConstantExpr::getSRem(GetFactor(Op0I), RHS)->isNullValue())
Chris Lattnerdb3f8732006-03-02 06:50:58 +00002499 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner97943922006-02-28 05:49:21 +00002500 }
Chris Lattnera2881962003-02-18 19:28:33 +00002501 }
2502
Reid Spencer0a783f72006-11-02 01:53:59 +00002503 return 0;
2504}
2505
2506Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2507 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2508
2509 if (Instruction *common = commonIRemTransforms(I))
2510 return common;
2511
2512 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2513 // X urem C^2 -> X and C
2514 // Check to see if this is an unsigned remainder with an exact power of 2,
2515 // if so, convert to a bitwise and.
2516 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
2517 if (isPowerOf2_64(C->getZExtValue()))
2518 return BinaryOperator::createAnd(Op0, SubOne(C));
2519 }
2520
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002521 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer0a783f72006-11-02 01:53:59 +00002522 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
2523 if (RHSI->getOpcode() == Instruction::Shl &&
2524 isa<ConstantInt>(RHSI->getOperand(0))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002525 unsigned C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002526 if (isPowerOf2_64(C1)) {
2527 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2528 Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
2529 "tmp"), I);
2530 return BinaryOperator::createAnd(Op0, Add);
2531 }
2532 }
Reid Spencer0a783f72006-11-02 01:53:59 +00002533 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002534
Reid Spencer0a783f72006-11-02 01:53:59 +00002535 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
2536 // where C1&C2 are powers of two.
2537 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2538 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2539 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2540 // STO == 0 and SFO == 0 handled above.
2541 if (isPowerOf2_64(STO->getZExtValue()) &&
2542 isPowerOf2_64(SFO->getZExtValue())) {
2543 Value *TrueAnd = InsertNewInstBefore(
2544 BinaryOperator::createAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
2545 Value *FalseAnd = InsertNewInstBefore(
2546 BinaryOperator::createAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
2547 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
2548 }
2549 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002550 }
2551
Chris Lattner3f5b8772002-05-06 16:14:14 +00002552 return 0;
2553}
2554
Reid Spencer0a783f72006-11-02 01:53:59 +00002555Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
2556 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2557
2558 if (Instruction *common = commonIRemTransforms(I))
2559 return common;
2560
2561 if (Value *RHSNeg = dyn_castNegVal(Op1))
2562 if (!isa<ConstantInt>(RHSNeg) ||
2563 cast<ConstantInt>(RHSNeg)->getSExtValue() > 0) {
2564 // X % -Y -> X % Y
2565 AddUsesToWorkList(I);
2566 I.setOperand(1, RHSNeg);
2567 return &I;
2568 }
2569
2570 // If the top bits of both operands are zero (i.e. we can prove they are
2571 // unsigned inputs), turn this into a urem.
2572 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2573 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2574 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
2575 return BinaryOperator::createURem(Op0, Op1, I.getName());
2576 }
2577
2578 return 0;
2579}
2580
2581Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
2582 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2583
2584 return commonRemTransforms(I);
2585}
2586
Chris Lattner8b170942002-08-09 23:47:40 +00002587// isMaxValueMinusOne - return true if this is Max-1
Chris Lattner233f7dc2002-08-12 21:17:25 +00002588static bool isMaxValueMinusOne(const ConstantInt *C) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002589 if (C->getType()->isUnsigned())
2590 return C->getZExtValue() == C->getType()->getIntegralTypeMask()-1;
Misha Brukmanfd939082005-04-21 23:48:37 +00002591
Chris Lattner8b170942002-08-09 23:47:40 +00002592 // Calculate 0111111111..11111
Chris Lattner484d3cf2005-04-24 06:59:08 +00002593 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner8b170942002-08-09 23:47:40 +00002594 int64_t Val = INT64_MAX; // All ones
2595 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
Reid Spencerb83eb642006-10-20 07:07:24 +00002596 return C->getSExtValue() == Val-1;
Chris Lattner8b170942002-08-09 23:47:40 +00002597}
2598
2599// isMinValuePlusOne - return true if this is Min+1
Chris Lattner233f7dc2002-08-12 21:17:25 +00002600static bool isMinValuePlusOne(const ConstantInt *C) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002601 if (C->getType()->isUnsigned())
2602 return C->getZExtValue() == 1;
Misha Brukmanfd939082005-04-21 23:48:37 +00002603
2604 // Calculate 1111111111000000000000
Chris Lattner484d3cf2005-04-24 06:59:08 +00002605 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner8b170942002-08-09 23:47:40 +00002606 int64_t Val = -1; // All ones
2607 Val <<= TypeBits-1; // Shift over to the right spot
Reid Spencerb83eb642006-10-20 07:07:24 +00002608 return C->getSExtValue() == Val+1;
Chris Lattner8b170942002-08-09 23:47:40 +00002609}
2610
Chris Lattner457dd822004-06-09 07:59:58 +00002611// isOneBitSet - Return true if there is exactly one bit set in the specified
2612// constant.
2613static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002614 uint64_t V = CI->getZExtValue();
Chris Lattner457dd822004-06-09 07:59:58 +00002615 return V && (V & (V-1)) == 0;
2616}
2617
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00002618#if 0 // Currently unused
2619// isLowOnes - Return true if the constant is of the form 0+1+.
2620static bool isLowOnes(const ConstantInt *CI) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002621 uint64_t V = CI->getZExtValue();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00002622
2623 // There won't be bits set in parts that the type doesn't contain.
Reid Spencerb83eb642006-10-20 07:07:24 +00002624 V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00002625
2626 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2627 return U && V && (U & V) == 0;
2628}
2629#endif
2630
2631// isHighOnes - Return true if the constant is of the form 1+0+.
2632// This is the same as lowones(~X).
2633static bool isHighOnes(const ConstantInt *CI) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002634 uint64_t V = ~CI->getZExtValue();
Chris Lattner2b83af22005-08-07 07:03:10 +00002635 if (~V == 0) return false; // 0's does not match "1+"
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00002636
2637 // There won't be bits set in parts that the type doesn't contain.
Reid Spencerb83eb642006-10-20 07:07:24 +00002638 V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00002639
2640 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2641 return U && V && (U & V) == 0;
2642}
2643
2644
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002645/// getSetCondCode - Encode a setcc opcode into a three bit mask. These bits
2646/// are carefully arranged to allow folding of expressions such as:
2647///
2648/// (A < B) | (A > B) --> (A != B)
2649///
2650/// Bit value '4' represents that the comparison is true if A > B, bit value '2'
2651/// represents that the comparison is true if A == B, and bit value '1' is true
2652/// if A < B.
2653///
2654static unsigned getSetCondCode(const SetCondInst *SCI) {
2655 switch (SCI->getOpcode()) {
2656 // False -> 0
2657 case Instruction::SetGT: return 1;
2658 case Instruction::SetEQ: return 2;
2659 case Instruction::SetGE: return 3;
2660 case Instruction::SetLT: return 4;
2661 case Instruction::SetNE: return 5;
2662 case Instruction::SetLE: return 6;
2663 // True -> 7
2664 default:
2665 assert(0 && "Invalid SetCC opcode!");
2666 return 0;
2667 }
2668}
2669
2670/// getSetCCValue - This is the complement of getSetCondCode, which turns an
2671/// opcode and two operands into either a constant true or false, or a brand new
2672/// SetCC instruction.
2673static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
2674 switch (Opcode) {
Chris Lattner47811b72006-09-28 23:35:22 +00002675 case 0: return ConstantBool::getFalse();
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002676 case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
2677 case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
2678 case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
2679 case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
2680 case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
2681 case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
Chris Lattner47811b72006-09-28 23:35:22 +00002682 case 7: return ConstantBool::getTrue();
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002683 default: assert(0 && "Illegal SetCCCode!"); return 0;
2684 }
2685}
2686
2687// FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
2688struct FoldSetCCLogical {
2689 InstCombiner &IC;
2690 Value *LHS, *RHS;
2691 FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
2692 : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
2693 bool shouldApply(Value *V) const {
2694 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
2695 return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
2696 SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
2697 return false;
2698 }
2699 Instruction *apply(BinaryOperator &Log) const {
2700 SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
2701 if (SCI->getOperand(0) != LHS) {
2702 assert(SCI->getOperand(1) == LHS);
2703 SCI->swapOperands(); // Swap the LHS and RHS of the SetCC
2704 }
2705
2706 unsigned LHSCode = getSetCondCode(SCI);
2707 unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
2708 unsigned Code;
2709 switch (Log.getOpcode()) {
2710 case Instruction::And: Code = LHSCode & RHSCode; break;
2711 case Instruction::Or: Code = LHSCode | RHSCode; break;
2712 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner021c1902003-09-22 20:33:34 +00002713 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002714 }
2715
2716 Value *RV = getSetCCValue(Code, LHS, RHS);
2717 if (Instruction *I = dyn_cast<Instruction>(RV))
2718 return I;
2719 // Otherwise, it's a constant boolean value...
2720 return IC.ReplaceInstUsesWith(Log, RV);
2721 }
2722};
2723
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002724// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
2725// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
2726// guaranteed to be either a shift instruction or a binary operator.
2727Instruction *InstCombiner::OptAndOp(Instruction *Op,
2728 ConstantIntegral *OpRHS,
2729 ConstantIntegral *AndRHS,
2730 BinaryOperator &TheAnd) {
2731 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00002732 Constant *Together = 0;
2733 if (!isa<ShiftInst>(Op))
Chris Lattner48595f12004-06-10 02:07:29 +00002734 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00002735
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002736 switch (Op->getOpcode()) {
2737 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00002738 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002739 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
2740 std::string OpName = Op->getName(); Op->setName("");
Chris Lattner48595f12004-06-10 02:07:29 +00002741 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002742 InsertNewInstBefore(And, TheAnd);
Chris Lattner48595f12004-06-10 02:07:29 +00002743 return BinaryOperator::createXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002744 }
2745 break;
2746 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00002747 if (Together == AndRHS) // (X | C) & C --> C
2748 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00002749
Chris Lattner6e7ba452005-01-01 16:22:27 +00002750 if (Op->hasOneUse() && Together != OpRHS) {
2751 // (X | C1) & C2 --> (X | (C1&C2)) & C2
2752 std::string Op0Name = Op->getName(); Op->setName("");
2753 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
2754 InsertNewInstBefore(Or, TheAnd);
2755 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002756 }
2757 break;
2758 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00002759 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002760 // Adding a one to a single bit bit-field should be turned into an XOR
2761 // of the bit. First thing to check is to see if this AND is with a
2762 // single bit constant.
Reid Spencerb83eb642006-10-20 07:07:24 +00002763 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getZExtValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002764
2765 // Clear bits that are not part of the constant.
Chris Lattner1a074fc2006-02-07 07:00:41 +00002766 AndRHSV &= AndRHS->getType()->getIntegralTypeMask();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002767
2768 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00002769 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002770 // Ok, at this point, we know that we are masking the result of the
2771 // ADD down to exactly one bit. If the constant we are adding has
2772 // no bits set below this bit, then we can eliminate the ADD.
Reid Spencerb83eb642006-10-20 07:07:24 +00002773 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getZExtValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00002774
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002775 // Check to see if any bits below the one bit set in AndRHSV are set.
2776 if ((AddRHS & (AndRHSV-1)) == 0) {
2777 // If not, the only thing that can effect the output of the AND is
2778 // the bit specified by AndRHSV. If that bit is set, the effect of
2779 // the XOR is to toggle the bit. If it is clear, then the ADD has
2780 // no effect.
2781 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
2782 TheAnd.setOperand(0, X);
2783 return &TheAnd;
2784 } else {
2785 std::string Name = Op->getName(); Op->setName("");
2786 // Pull the XOR out of the AND.
Chris Lattner48595f12004-06-10 02:07:29 +00002787 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002788 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner48595f12004-06-10 02:07:29 +00002789 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002790 }
2791 }
2792 }
2793 }
2794 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00002795
2796 case Instruction::Shl: {
2797 // We know that the AND will not produce any of the bits shifted in, so if
2798 // the anded constant includes them, clear them now!
2799 //
2800 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner0c967662004-09-24 15:21:34 +00002801 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
2802 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00002803
Chris Lattner0c967662004-09-24 15:21:34 +00002804 if (CI == ShlMask) { // Masking out bits that the shift already masks
2805 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
2806 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00002807 TheAnd.setOperand(1, CI);
2808 return &TheAnd;
2809 }
2810 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00002811 }
Chris Lattner62a355c2003-09-19 19:05:02 +00002812 case Instruction::Shr:
2813 // We know that the AND will not produce any of the bits shifted in, so if
2814 // the anded constant includes them, clear them now! This only applies to
2815 // unsigned shifts, because a signed shr may bring in set bits!
2816 //
2817 if (AndRHS->getType()->isUnsigned()) {
2818 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner0c967662004-09-24 15:21:34 +00002819 Constant *ShrMask = ConstantExpr::getShr(AllOne, OpRHS);
2820 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
2821
2822 if (CI == ShrMask) { // Masking out bits that the shift already masks.
2823 return ReplaceInstUsesWith(TheAnd, Op);
2824 } else if (CI != AndRHS) {
2825 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
Chris Lattner62a355c2003-09-19 19:05:02 +00002826 return &TheAnd;
2827 }
Chris Lattner0c967662004-09-24 15:21:34 +00002828 } else { // Signed shr.
2829 // See if this is shifting in some sign extension, then masking it out
2830 // with an and.
2831 if (Op->hasOneUse()) {
2832 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2833 Constant *ShrMask = ConstantExpr::getUShr(AllOne, OpRHS);
2834 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
Chris Lattner9b991822004-10-22 04:53:16 +00002835 if (CI == AndRHS) { // Masking out bits shifted in.
Chris Lattner0c967662004-09-24 15:21:34 +00002836 // Make the argument unsigned.
2837 Value *ShVal = Op->getOperand(0);
2838 ShVal = InsertCastBefore(ShVal,
2839 ShVal->getType()->getUnsignedVersion(),
2840 TheAnd);
2841 ShVal = InsertNewInstBefore(new ShiftInst(Instruction::Shr, ShVal,
2842 OpRHS, Op->getName()),
2843 TheAnd);
Chris Lattnerdc781222004-10-27 05:57:15 +00002844 Value *AndRHS2 = ConstantExpr::getCast(AndRHS, ShVal->getType());
2845 ShVal = InsertNewInstBefore(BinaryOperator::createAnd(ShVal, AndRHS2,
2846 TheAnd.getName()),
2847 TheAnd);
Chris Lattner0c967662004-09-24 15:21:34 +00002848 return new CastInst(ShVal, Op->getType());
2849 }
2850 }
Chris Lattner62a355c2003-09-19 19:05:02 +00002851 }
2852 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002853 }
2854 return 0;
2855}
2856
Chris Lattner8b170942002-08-09 23:47:40 +00002857
Chris Lattnera96879a2004-09-29 17:40:11 +00002858/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
2859/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
2860/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. IB is the location to
2861/// insert new instructions.
2862Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
2863 bool Inside, Instruction &IB) {
2864 assert(cast<ConstantBool>(ConstantExpr::getSetLE(Lo, Hi))->getValue() &&
2865 "Lo is not <= Hi in range emission code!");
2866 if (Inside) {
2867 if (Lo == Hi) // Trivially false.
2868 return new SetCondInst(Instruction::SetNE, V, V);
2869 if (cast<ConstantIntegral>(Lo)->isMinValue())
2870 return new SetCondInst(Instruction::SetLT, V, Hi);
Misha Brukmanfd939082005-04-21 23:48:37 +00002871
Chris Lattnera96879a2004-09-29 17:40:11 +00002872 Constant *AddCST = ConstantExpr::getNeg(Lo);
2873 Instruction *Add = BinaryOperator::createAdd(V, AddCST,V->getName()+".off");
2874 InsertNewInstBefore(Add, IB);
2875 // Convert to unsigned for the comparison.
2876 const Type *UnsType = Add->getType()->getUnsignedVersion();
2877 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
2878 AddCST = ConstantExpr::getAdd(AddCST, Hi);
2879 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2880 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
2881 }
2882
2883 if (Lo == Hi) // Trivially true.
2884 return new SetCondInst(Instruction::SetEQ, V, V);
2885
2886 Hi = SubOne(cast<ConstantInt>(Hi));
Reid Spencerb83eb642006-10-20 07:07:24 +00002887
2888 // V < 0 || V >= Hi ->'V > Hi-1'
2889 if (cast<ConstantIntegral>(Lo)->isMinValue())
Chris Lattnera96879a2004-09-29 17:40:11 +00002890 return new SetCondInst(Instruction::SetGT, V, Hi);
2891
2892 // Emit X-Lo > Hi-Lo-1
2893 Constant *AddCST = ConstantExpr::getNeg(Lo);
2894 Instruction *Add = BinaryOperator::createAdd(V, AddCST, V->getName()+".off");
2895 InsertNewInstBefore(Add, IB);
2896 // Convert to unsigned for the comparison.
2897 const Type *UnsType = Add->getType()->getUnsignedVersion();
2898 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
2899 AddCST = ConstantExpr::getAdd(AddCST, Hi);
2900 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2901 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
2902}
2903
Chris Lattner7203e152005-09-18 07:22:02 +00002904// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
2905// any number of 0s on either side. The 1s are allowed to wrap from LSB to
2906// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
2907// not, since all 1s are not contiguous.
2908static bool isRunOfOnes(ConstantIntegral *Val, unsigned &MB, unsigned &ME) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002909 uint64_t V = Val->getZExtValue();
Chris Lattner7203e152005-09-18 07:22:02 +00002910 if (!isShiftedMask_64(V)) return false;
2911
2912 // look for the first zero bit after the run of ones
2913 MB = 64-CountLeadingZeros_64((V - 1) ^ V);
2914 // look for the first non-zero bit
2915 ME = 64-CountLeadingZeros_64(V);
2916 return true;
2917}
2918
2919
2920
2921/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
2922/// where isSub determines whether the operator is a sub. If we can fold one of
2923/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00002924///
2925/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
2926/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
2927/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
2928///
2929/// return (A +/- B).
2930///
2931Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
2932 ConstantIntegral *Mask, bool isSub,
2933 Instruction &I) {
2934 Instruction *LHSI = dyn_cast<Instruction>(LHS);
2935 if (!LHSI || LHSI->getNumOperands() != 2 ||
2936 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
2937
2938 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
2939
2940 switch (LHSI->getOpcode()) {
2941 default: return 0;
2942 case Instruction::And:
Chris Lattner7203e152005-09-18 07:22:02 +00002943 if (ConstantExpr::getAnd(N, Mask) == Mask) {
2944 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Reid Spencerb83eb642006-10-20 07:07:24 +00002945 if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0)
Chris Lattner7203e152005-09-18 07:22:02 +00002946 break;
2947
2948 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
2949 // part, we don't need any explicit masks to take them out of A. If that
2950 // is all N is, ignore it.
2951 unsigned MB, ME;
2952 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Chris Lattner3bedbd92006-02-07 07:27:52 +00002953 uint64_t Mask = RHS->getType()->getIntegralTypeMask();
2954 Mask >>= 64-MB+1;
2955 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00002956 break;
2957 }
2958 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00002959 return 0;
2960 case Instruction::Or:
2961 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00002962 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Reid Spencerb83eb642006-10-20 07:07:24 +00002963 if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0 &&
Chris Lattner7203e152005-09-18 07:22:02 +00002964 ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattnerc8e77562005-09-18 04:24:45 +00002965 break;
2966 return 0;
2967 }
2968
2969 Instruction *New;
2970 if (isSub)
2971 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
2972 else
2973 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
2974 return InsertNewInstBefore(New, I);
2975}
2976
Chris Lattner7e708292002-06-25 16:13:24 +00002977Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002978 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002979 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002980
Chris Lattnere87597f2004-10-16 18:11:37 +00002981 if (isa<UndefValue>(Op1)) // X & undef -> 0
2982 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2983
Chris Lattner6e7ba452005-01-01 16:22:27 +00002984 // and X, X = X
2985 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00002986 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002987
Chris Lattnerf8c36f52006-02-12 08:02:11 +00002988 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00002989 // purpose is to compute bits we don't care about.
Chris Lattner255d8912006-02-11 09:31:47 +00002990 uint64_t KnownZero, KnownOne;
Chris Lattner98509ef2006-03-25 21:58:26 +00002991 if (!isa<PackedType>(I.getType()) &&
2992 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattner255d8912006-02-11 09:31:47 +00002993 KnownZero, KnownOne))
Chris Lattner9ca96412006-02-08 03:25:32 +00002994 return &I;
2995
Chris Lattner6e7ba452005-01-01 16:22:27 +00002996 if (ConstantIntegral *AndRHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner7560c3a2006-02-08 07:34:50 +00002997 uint64_t AndRHSMask = AndRHS->getZExtValue();
2998 uint64_t TypeMask = Op0->getType()->getIntegralTypeMask();
Chris Lattner7560c3a2006-02-08 07:34:50 +00002999 uint64_t NotAndRHS = AndRHSMask^TypeMask;
Chris Lattner6e7ba452005-01-01 16:22:27 +00003000
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003001 // Optimize a variety of ((val OP C1) & C2) combinations...
3002 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
3003 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003004 Value *Op0LHS = Op0I->getOperand(0);
3005 Value *Op0RHS = Op0I->getOperand(1);
3006 switch (Op0I->getOpcode()) {
3007 case Instruction::Xor:
3008 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00003009 // If the mask is only needed on one incoming arm, push it up.
3010 if (Op0I->hasOneUse()) {
3011 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3012 // Not masking anything out for the LHS, move to RHS.
3013 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
3014 Op0RHS->getName()+".masked");
3015 InsertNewInstBefore(NewRHS, I);
3016 return BinaryOperator::create(
3017 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003018 }
Chris Lattner3bedbd92006-02-07 07:27:52 +00003019 if (!isa<Constant>(Op0RHS) &&
Chris Lattnerad1e3022005-01-23 20:26:55 +00003020 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3021 // Not masking anything out for the RHS, move to LHS.
3022 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
3023 Op0LHS->getName()+".masked");
3024 InsertNewInstBefore(NewLHS, I);
3025 return BinaryOperator::create(
3026 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3027 }
3028 }
3029
Chris Lattner6e7ba452005-01-01 16:22:27 +00003030 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00003031 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00003032 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3033 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3034 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3035 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3036 return BinaryOperator::createAnd(V, AndRHS);
3037 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3038 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00003039 break;
3040
3041 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00003042 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3043 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3044 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3045 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3046 return BinaryOperator::createAnd(V, AndRHS);
Chris Lattnerc8e77562005-09-18 04:24:45 +00003047 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00003048 }
3049
Chris Lattner58403262003-07-23 19:25:52 +00003050 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003051 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003052 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00003053 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3054 const Type *SrcTy = CI->getOperand(0)->getType();
3055
Chris Lattner2b83af22005-08-07 07:03:10 +00003056 // If this is an integer truncation or change from signed-to-unsigned, and
3057 // if the source is an and/or with immediate, transform it. This
3058 // frequently occurs for bitfield accesses.
3059 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
3060 if (SrcTy->getPrimitiveSizeInBits() >=
3061 I.getType()->getPrimitiveSizeInBits() &&
3062 CastOp->getNumOperands() == 2)
Chris Lattner7560c3a2006-02-08 07:34:50 +00003063 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
Chris Lattner2b83af22005-08-07 07:03:10 +00003064 if (CastOp->getOpcode() == Instruction::And) {
3065 // Change: and (cast (and X, C1) to T), C2
3066 // into : and (cast X to T), trunc(C1)&C2
3067 // This will folds the two ands together, which may allow other
3068 // simplifications.
3069 Instruction *NewCast =
3070 new CastInst(CastOp->getOperand(0), I.getType(),
3071 CastOp->getName()+".shrunk");
3072 NewCast = InsertNewInstBefore(NewCast, I);
3073
3074 Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
3075 C3 = ConstantExpr::getAnd(C3, AndRHS); // trunc(C1)&C2
3076 return BinaryOperator::createAnd(NewCast, C3);
3077 } else if (CastOp->getOpcode() == Instruction::Or) {
3078 // Change: and (cast (or X, C1) to T), C2
3079 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
3080 Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
3081 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3082 return ReplaceInstUsesWith(I, AndRHS);
3083 }
3084 }
Chris Lattner06782f82003-07-23 19:36:21 +00003085 }
Chris Lattner2eefe512004-04-09 19:05:30 +00003086
3087 // Try to fold constant and into select arguments.
3088 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003089 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00003090 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00003091 if (isa<PHINode>(Op0))
3092 if (Instruction *NV = FoldOpIntoPhi(I))
3093 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00003094 }
3095
Chris Lattner8d969642003-03-10 23:06:50 +00003096 Value *Op0NotVal = dyn_castNotVal(Op0);
3097 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00003098
Chris Lattner5b62aa72004-06-18 06:07:51 +00003099 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3100 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3101
Misha Brukmancb6267b2004-07-30 12:50:08 +00003102 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00003103 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattner48595f12004-06-10 02:07:29 +00003104 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
3105 I.getName()+".demorgan");
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00003106 InsertNewInstBefore(Or, I);
Chris Lattnera2881962003-02-18 19:28:33 +00003107 return BinaryOperator::createNot(Or);
3108 }
Chris Lattner2082ad92006-02-13 23:07:23 +00003109
3110 {
3111 Value *A = 0, *B = 0;
3112 ConstantInt *C1 = 0, *C2 = 0;
3113 if (match(Op0, m_Or(m_Value(A), m_Value(B))))
3114 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3115 return ReplaceInstUsesWith(I, Op1);
3116 if (match(Op1, m_Or(m_Value(A), m_Value(B))))
3117 if (A == Op0 || B == Op0) // A & (A | ?) --> A
3118 return ReplaceInstUsesWith(I, Op0);
Chris Lattner64daab52006-04-01 08:03:55 +00003119
3120 if (Op0->hasOneUse() &&
3121 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3122 if (A == Op1) { // (A^B)&A -> A&(A^B)
3123 I.swapOperands(); // Simplify below
3124 std::swap(Op0, Op1);
3125 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
3126 cast<BinaryOperator>(Op0)->swapOperands();
3127 I.swapOperands(); // Simplify below
3128 std::swap(Op0, Op1);
3129 }
3130 }
3131 if (Op1->hasOneUse() &&
3132 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3133 if (B == Op0) { // B&(A^B) -> B&(B^A)
3134 cast<BinaryOperator>(Op1)->swapOperands();
3135 std::swap(A, B);
3136 }
3137 if (A == Op0) { // A&(A^B) -> A & ~B
3138 Instruction *NotB = BinaryOperator::createNot(B, "tmp");
3139 InsertNewInstBefore(NotB, I);
3140 return BinaryOperator::createAnd(A, NotB);
3141 }
3142 }
Chris Lattner2082ad92006-02-13 23:07:23 +00003143 }
3144
Chris Lattnera2881962003-02-18 19:28:33 +00003145
Chris Lattner955f3312004-09-28 21:48:02 +00003146 if (SetCondInst *RHS = dyn_cast<SetCondInst>(Op1)) {
3147 // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003148 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
3149 return R;
3150
Chris Lattner955f3312004-09-28 21:48:02 +00003151 Value *LHSVal, *RHSVal;
3152 ConstantInt *LHSCst, *RHSCst;
3153 Instruction::BinaryOps LHSCC, RHSCC;
3154 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3155 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3156 if (LHSVal == RHSVal && // Found (X setcc C1) & (X setcc C2)
3157 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
Misha Brukmanfd939082005-04-21 23:48:37 +00003158 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
Chris Lattner955f3312004-09-28 21:48:02 +00003159 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
3160 // Ensure that the larger constant is on the RHS.
3161 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
3162 SetCondInst *LHS = cast<SetCondInst>(Op0);
3163 if (cast<ConstantBool>(Cmp)->getValue()) {
3164 std::swap(LHS, RHS);
3165 std::swap(LHSCst, RHSCst);
3166 std::swap(LHSCC, RHSCC);
3167 }
3168
3169 // At this point, we know we have have two setcc instructions
3170 // comparing a value against two constants and and'ing the result
3171 // together. Because of the above check, we know that we only have
3172 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
3173 // FoldSetCCLogical check above), that the two constants are not
3174 // equal.
3175 assert(LHSCst != RHSCst && "Compares not folded above?");
3176
3177 switch (LHSCC) {
3178 default: assert(0 && "Unknown integer condition code!");
3179 case Instruction::SetEQ:
3180 switch (RHSCC) {
3181 default: assert(0 && "Unknown integer condition code!");
3182 case Instruction::SetEQ: // (X == 13 & X == 15) -> false
3183 case Instruction::SetGT: // (X == 13 & X > 15) -> false
Chris Lattner47811b72006-09-28 23:35:22 +00003184 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattner955f3312004-09-28 21:48:02 +00003185 case Instruction::SetNE: // (X == 13 & X != 15) -> X == 13
3186 case Instruction::SetLT: // (X == 13 & X < 15) -> X == 13
3187 return ReplaceInstUsesWith(I, LHS);
3188 }
3189 case Instruction::SetNE:
3190 switch (RHSCC) {
3191 default: assert(0 && "Unknown integer condition code!");
3192 case Instruction::SetLT:
3193 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X < 14) -> X < 13
3194 return new SetCondInst(Instruction::SetLT, LHSVal, LHSCst);
3195 break; // (X != 13 & X < 15) -> no change
3196 case Instruction::SetEQ: // (X != 13 & X == 15) -> X == 15
3197 case Instruction::SetGT: // (X != 13 & X > 15) -> X > 15
3198 return ReplaceInstUsesWith(I, RHS);
3199 case Instruction::SetNE:
3200 if (LHSCst == SubOne(RHSCst)) {// (X != 13 & X != 14) -> X-13 >u 1
3201 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3202 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3203 LHSVal->getName()+".off");
3204 InsertNewInstBefore(Add, I);
3205 const Type *UnsType = Add->getType()->getUnsignedVersion();
3206 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
3207 AddCST = ConstantExpr::getSub(RHSCst, LHSCst);
3208 AddCST = ConstantExpr::getCast(AddCST, UnsType);
3209 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
3210 }
3211 break; // (X != 13 & X != 15) -> no change
3212 }
3213 break;
3214 case Instruction::SetLT:
3215 switch (RHSCC) {
3216 default: assert(0 && "Unknown integer condition code!");
3217 case Instruction::SetEQ: // (X < 13 & X == 15) -> false
3218 case Instruction::SetGT: // (X < 13 & X > 15) -> false
Chris Lattner47811b72006-09-28 23:35:22 +00003219 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattner955f3312004-09-28 21:48:02 +00003220 case Instruction::SetNE: // (X < 13 & X != 15) -> X < 13
3221 case Instruction::SetLT: // (X < 13 & X < 15) -> X < 13
3222 return ReplaceInstUsesWith(I, LHS);
3223 }
3224 case Instruction::SetGT:
3225 switch (RHSCC) {
3226 default: assert(0 && "Unknown integer condition code!");
3227 case Instruction::SetEQ: // (X > 13 & X == 15) -> X > 13
3228 return ReplaceInstUsesWith(I, LHS);
3229 case Instruction::SetGT: // (X > 13 & X > 15) -> X > 15
3230 return ReplaceInstUsesWith(I, RHS);
3231 case Instruction::SetNE:
3232 if (RHSCst == AddOne(LHSCst)) // (X > 13 & X != 14) -> X > 14
3233 return new SetCondInst(Instruction::SetGT, LHSVal, RHSCst);
3234 break; // (X > 13 & X != 15) -> no change
Chris Lattnera96879a2004-09-29 17:40:11 +00003235 case Instruction::SetLT: // (X > 13 & X < 15) -> (X-14) <u 1
3236 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, I);
Chris Lattner955f3312004-09-28 21:48:02 +00003237 }
3238 }
3239 }
3240 }
3241
Chris Lattner6fc205f2006-05-05 06:39:07 +00003242 // fold (and (cast A), (cast B)) -> (cast (and A, B))
3243 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner581a7ad2006-05-05 20:51:30 +00003244 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner6fc205f2006-05-05 06:39:07 +00003245 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Chris Lattner581a7ad2006-05-05 20:51:30 +00003246 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
Chris Lattner33a61132006-05-06 09:00:16 +00003247 // Only do this if the casts both really cause code to be generated.
3248 ValueRequiresCast(Op0C->getOperand(0), I.getType(), TD) &&
3249 ValueRequiresCast(Op1C->getOperand(0), I.getType(), TD)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00003250 Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
3251 Op1C->getOperand(0),
3252 I.getName());
3253 InsertNewInstBefore(NewOp, I);
3254 return new CastInst(NewOp, I.getType());
3255 }
3256 }
3257
Chris Lattner7e708292002-06-25 16:13:24 +00003258 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00003259}
3260
Chris Lattnerafe91a52006-06-15 19:07:26 +00003261/// CollectBSwapParts - Look to see if the specified value defines a single byte
3262/// in the result. If it does, and if the specified byte hasn't been filled in
3263/// yet, fill it in and return false.
3264static bool CollectBSwapParts(Value *V, std::vector<Value*> &ByteValues) {
3265 Instruction *I = dyn_cast<Instruction>(V);
3266 if (I == 0) return true;
3267
3268 // If this is an or instruction, it is an inner node of the bswap.
3269 if (I->getOpcode() == Instruction::Or)
3270 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3271 CollectBSwapParts(I->getOperand(1), ByteValues);
3272
3273 // If this is a shift by a constant int, and it is "24", then its operand
3274 // defines a byte. We only handle unsigned types here.
3275 if (isa<ShiftInst>(I) && isa<ConstantInt>(I->getOperand(1))) {
3276 // Not shifting the entire input by N-1 bytes?
Reid Spencerb83eb642006-10-20 07:07:24 +00003277 if (cast<ConstantInt>(I->getOperand(1))->getZExtValue() !=
Chris Lattnerafe91a52006-06-15 19:07:26 +00003278 8*(ByteValues.size()-1))
3279 return true;
3280
3281 unsigned DestNo;
3282 if (I->getOpcode() == Instruction::Shl) {
3283 // X << 24 defines the top byte with the lowest of the input bytes.
3284 DestNo = ByteValues.size()-1;
3285 } else {
3286 // X >>u 24 defines the low byte with the highest of the input bytes.
3287 DestNo = 0;
3288 }
3289
3290 // If the destination byte value is already defined, the values are or'd
3291 // together, which isn't a bswap (unless it's an or of the same bits).
3292 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3293 return true;
3294 ByteValues[DestNo] = I->getOperand(0);
3295 return false;
3296 }
3297
3298 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
3299 // don't have this.
3300 Value *Shift = 0, *ShiftLHS = 0;
3301 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3302 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3303 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3304 return true;
3305 Instruction *SI = cast<Instruction>(Shift);
3306
3307 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
Reid Spencerb83eb642006-10-20 07:07:24 +00003308 if (ShiftAmt->getZExtValue() & 7 ||
3309 ShiftAmt->getZExtValue() > 8*ByteValues.size())
Chris Lattnerafe91a52006-06-15 19:07:26 +00003310 return true;
3311
3312 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3313 unsigned DestByte;
3314 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
Reid Spencerb83eb642006-10-20 07:07:24 +00003315 if (AndAmt->getZExtValue() == uint64_t(0xFF) << 8*DestByte)
Chris Lattnerafe91a52006-06-15 19:07:26 +00003316 break;
3317 // Unknown mask for bswap.
3318 if (DestByte == ByteValues.size()) return true;
3319
Reid Spencerb83eb642006-10-20 07:07:24 +00003320 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
Chris Lattnerafe91a52006-06-15 19:07:26 +00003321 unsigned SrcByte;
3322 if (SI->getOpcode() == Instruction::Shl)
3323 SrcByte = DestByte - ShiftBytes;
3324 else
3325 SrcByte = DestByte + ShiftBytes;
3326
3327 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3328 if (SrcByte != ByteValues.size()-DestByte-1)
3329 return true;
3330
3331 // If the destination byte value is already defined, the values are or'd
3332 // together, which isn't a bswap (unless it's an or of the same bits).
3333 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3334 return true;
3335 ByteValues[DestByte] = SI->getOperand(0);
3336 return false;
3337}
3338
3339/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3340/// If so, insert the new bswap intrinsic and return it.
3341Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
3342 // We can only handle bswap of unsigned integers, and cannot bswap one byte.
3343 if (!I.getType()->isUnsigned() || I.getType() == Type::UByteTy)
3344 return 0;
3345
3346 /// ByteValues - For each byte of the result, we keep track of which value
3347 /// defines each byte.
3348 std::vector<Value*> ByteValues;
3349 ByteValues.resize(I.getType()->getPrimitiveSize());
3350
3351 // Try to find all the pieces corresponding to the bswap.
3352 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3353 CollectBSwapParts(I.getOperand(1), ByteValues))
3354 return 0;
3355
3356 // Check to see if all of the bytes come from the same value.
3357 Value *V = ByteValues[0];
3358 if (V == 0) return 0; // Didn't find a byte? Must be zero.
3359
3360 // Check to make sure that all of the bytes come from the same value.
3361 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3362 if (ByteValues[i] != V)
3363 return 0;
3364
3365 // If they do then *success* we can turn this into a bswap. Figure out what
3366 // bswap to make it into.
3367 Module *M = I.getParent()->getParent()->getParent();
Chris Lattnered36b2f2006-07-11 18:31:26 +00003368 const char *FnName = 0;
Chris Lattnerafe91a52006-06-15 19:07:26 +00003369 if (I.getType() == Type::UShortTy)
3370 FnName = "llvm.bswap.i16";
3371 else if (I.getType() == Type::UIntTy)
3372 FnName = "llvm.bswap.i32";
3373 else if (I.getType() == Type::ULongTy)
3374 FnName = "llvm.bswap.i64";
3375 else
3376 assert(0 && "Unknown integer type!");
3377 Function *F = M->getOrInsertFunction(FnName, I.getType(), I.getType(), NULL);
3378
3379 return new CallInst(F, V);
3380}
3381
3382
Chris Lattner7e708292002-06-25 16:13:24 +00003383Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003384 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00003385 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003386
Chris Lattnere87597f2004-10-16 18:11:37 +00003387 if (isa<UndefValue>(Op1))
3388 return ReplaceInstUsesWith(I, // X | undef -> -1
3389 ConstantIntegral::getAllOnesValue(I.getType()));
3390
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003391 // or X, X = X
3392 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00003393 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003394
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003395 // See if we can simplify any instructions used by the instruction whose sole
3396 // purpose is to compute bits we don't care about.
3397 uint64_t KnownZero, KnownOne;
Chris Lattner98509ef2006-03-25 21:58:26 +00003398 if (!isa<PackedType>(I.getType()) &&
3399 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003400 KnownZero, KnownOne))
3401 return &I;
3402
Chris Lattner3f5b8772002-05-06 16:14:14 +00003403 // or X, -1 == -1
Chris Lattnerad44ebf2003-07-23 18:29:44 +00003404 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00003405 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003406 // (X & C1) | C2 --> (X | C2) & (C1|C2)
3407 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattner6e4c6492005-05-09 04:58:36 +00003408 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0->getName());
3409 Op0->setName("");
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003410 InsertNewInstBefore(Or, I);
3411 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
3412 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00003413
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003414 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3415 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3416 std::string Op0Name = Op0->getName(); Op0->setName("");
3417 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
3418 InsertNewInstBefore(Or, I);
3419 return BinaryOperator::createXor(Or,
3420 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00003421 }
Chris Lattner2eefe512004-04-09 19:05:30 +00003422
3423 // Try to fold constant and into select arguments.
3424 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003425 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00003426 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00003427 if (isa<PHINode>(Op0))
3428 if (Instruction *NV = FoldOpIntoPhi(I))
3429 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00003430 }
3431
Chris Lattner4f637d42006-01-06 17:59:59 +00003432 Value *A = 0, *B = 0;
3433 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00003434
3435 if (match(Op0, m_And(m_Value(A), m_Value(B))))
3436 if (A == Op1 || B == Op1) // (A & ?) | A --> A
3437 return ReplaceInstUsesWith(I, Op1);
3438 if (match(Op1, m_And(m_Value(A), m_Value(B))))
3439 if (A == Op0 || B == Op0) // A | (A & ?) --> A
3440 return ReplaceInstUsesWith(I, Op0);
3441
Chris Lattner6423d4c2006-07-10 20:25:24 +00003442 // (A | B) | C and A | (B | C) -> bswap if possible.
3443 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Chris Lattnerafe91a52006-06-15 19:07:26 +00003444 if (match(Op0, m_Or(m_Value(), m_Value())) ||
Chris Lattner6423d4c2006-07-10 20:25:24 +00003445 match(Op1, m_Or(m_Value(), m_Value())) ||
3446 (match(Op0, m_Shift(m_Value(), m_Value())) &&
3447 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00003448 if (Instruction *BSwap = MatchBSwap(I))
3449 return BSwap;
3450 }
3451
Chris Lattner6e4c6492005-05-09 04:58:36 +00003452 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
3453 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattner3bedbd92006-02-07 07:27:52 +00003454 MaskedValueIsZero(Op1, C1->getZExtValue())) {
Chris Lattner6e4c6492005-05-09 04:58:36 +00003455 Instruction *NOr = BinaryOperator::createOr(A, Op1, Op0->getName());
3456 Op0->setName("");
3457 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
3458 }
3459
3460 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
3461 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattner3bedbd92006-02-07 07:27:52 +00003462 MaskedValueIsZero(Op0, C1->getZExtValue())) {
Chris Lattner6e4c6492005-05-09 04:58:36 +00003463 Instruction *NOr = BinaryOperator::createOr(A, Op0, Op1->getName());
3464 Op0->setName("");
3465 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
3466 }
3467
Chris Lattnere9bed7d2005-09-18 03:42:07 +00003468 // (A & C1)|(B & C2)
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003469 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattnere9bed7d2005-09-18 03:42:07 +00003470 match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
3471
3472 if (A == B) // (A & C1)|(A & C2) == A & (C1|C2)
3473 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
3474
3475
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00003476 // If we have: ((V + N) & C1) | (V & C2)
3477 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
3478 // replace with V+N.
3479 if (C1 == ConstantExpr::getNot(C2)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00003480 Value *V1 = 0, *V2 = 0;
Reid Spencerb83eb642006-10-20 07:07:24 +00003481 if ((C2->getZExtValue() & (C2->getZExtValue()+1)) == 0 && // C2 == 0+1+
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00003482 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
3483 // Add commutes, try both ways.
Chris Lattner3bedbd92006-02-07 07:27:52 +00003484 if (V1 == B && MaskedValueIsZero(V2, C2->getZExtValue()))
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00003485 return ReplaceInstUsesWith(I, A);
Chris Lattner3bedbd92006-02-07 07:27:52 +00003486 if (V2 == B && MaskedValueIsZero(V1, C2->getZExtValue()))
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00003487 return ReplaceInstUsesWith(I, A);
3488 }
3489 // Or commutes, try both ways.
Reid Spencerb83eb642006-10-20 07:07:24 +00003490 if ((C1->getZExtValue() & (C1->getZExtValue()+1)) == 0 &&
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00003491 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
3492 // Add commutes, try both ways.
Chris Lattner3bedbd92006-02-07 07:27:52 +00003493 if (V1 == A && MaskedValueIsZero(V2, C1->getZExtValue()))
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00003494 return ReplaceInstUsesWith(I, B);
Chris Lattner3bedbd92006-02-07 07:27:52 +00003495 if (V2 == A && MaskedValueIsZero(V1, C1->getZExtValue()))
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00003496 return ReplaceInstUsesWith(I, B);
Chris Lattnere9bed7d2005-09-18 03:42:07 +00003497 }
3498 }
3499 }
Chris Lattner67ca7682003-08-12 19:11:07 +00003500
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003501 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
3502 if (A == Op1) // ~A | A == -1
Misha Brukmanfd939082005-04-21 23:48:37 +00003503 return ReplaceInstUsesWith(I,
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003504 ConstantIntegral::getAllOnesValue(I.getType()));
3505 } else {
3506 A = 0;
3507 }
Chris Lattnerf4d4c872005-05-07 23:49:08 +00003508 // Note, A is still live here!
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003509 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
3510 if (Op0 == B)
Misha Brukmanfd939082005-04-21 23:48:37 +00003511 return ReplaceInstUsesWith(I,
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003512 ConstantIntegral::getAllOnesValue(I.getType()));
Chris Lattnera27231a2003-03-10 23:13:59 +00003513
Misha Brukmancb6267b2004-07-30 12:50:08 +00003514 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003515 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3516 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
3517 I.getName()+".demorgan"), I);
3518 return BinaryOperator::createNot(And);
3519 }
Chris Lattnera27231a2003-03-10 23:13:59 +00003520 }
Chris Lattnera2881962003-02-18 19:28:33 +00003521
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003522 // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
Chris Lattnerb4f40d22004-09-28 22:33:08 +00003523 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1))) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003524 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
3525 return R;
3526
Chris Lattnerb4f40d22004-09-28 22:33:08 +00003527 Value *LHSVal, *RHSVal;
3528 ConstantInt *LHSCst, *RHSCst;
3529 Instruction::BinaryOps LHSCC, RHSCC;
3530 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3531 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3532 if (LHSVal == RHSVal && // Found (X setcc C1) | (X setcc C2)
3533 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
Misha Brukmanfd939082005-04-21 23:48:37 +00003534 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
Chris Lattnerb4f40d22004-09-28 22:33:08 +00003535 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
3536 // Ensure that the larger constant is on the RHS.
3537 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
3538 SetCondInst *LHS = cast<SetCondInst>(Op0);
3539 if (cast<ConstantBool>(Cmp)->getValue()) {
3540 std::swap(LHS, RHS);
3541 std::swap(LHSCst, RHSCst);
3542 std::swap(LHSCC, RHSCC);
3543 }
3544
3545 // At this point, we know we have have two setcc instructions
3546 // comparing a value against two constants and or'ing the result
3547 // together. Because of the above check, we know that we only have
3548 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
3549 // FoldSetCCLogical check above), that the two constants are not
3550 // equal.
3551 assert(LHSCst != RHSCst && "Compares not folded above?");
3552
3553 switch (LHSCC) {
3554 default: assert(0 && "Unknown integer condition code!");
3555 case Instruction::SetEQ:
3556 switch (RHSCC) {
3557 default: assert(0 && "Unknown integer condition code!");
3558 case Instruction::SetEQ:
3559 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
3560 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3561 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3562 LHSVal->getName()+".off");
3563 InsertNewInstBefore(Add, I);
3564 const Type *UnsType = Add->getType()->getUnsignedVersion();
3565 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
3566 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
3567 AddCST = ConstantExpr::getCast(AddCST, UnsType);
3568 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
3569 }
3570 break; // (X == 13 | X == 15) -> no change
3571
Chris Lattner240d6f42005-04-19 06:04:18 +00003572 case Instruction::SetGT: // (X == 13 | X > 14) -> no change
3573 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00003574 case Instruction::SetNE: // (X == 13 | X != 15) -> X != 15
3575 case Instruction::SetLT: // (X == 13 | X < 15) -> X < 15
3576 return ReplaceInstUsesWith(I, RHS);
3577 }
3578 break;
3579 case Instruction::SetNE:
3580 switch (RHSCC) {
3581 default: assert(0 && "Unknown integer condition code!");
Chris Lattnerb4f40d22004-09-28 22:33:08 +00003582 case Instruction::SetEQ: // (X != 13 | X == 15) -> X != 13
3583 case Instruction::SetGT: // (X != 13 | X > 15) -> X != 13
3584 return ReplaceInstUsesWith(I, LHS);
3585 case Instruction::SetNE: // (X != 13 | X != 15) -> true
Chris Lattnere88b7532005-06-17 03:59:17 +00003586 case Instruction::SetLT: // (X != 13 | X < 15) -> true
Chris Lattner47811b72006-09-28 23:35:22 +00003587 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattnerb4f40d22004-09-28 22:33:08 +00003588 }
3589 break;
3590 case Instruction::SetLT:
3591 switch (RHSCC) {
3592 default: assert(0 && "Unknown integer condition code!");
3593 case Instruction::SetEQ: // (X < 13 | X == 14) -> no change
3594 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00003595 case Instruction::SetGT: // (X < 13 | X > 15) -> (X-13) > 2
3596 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, I);
Chris Lattnerb4f40d22004-09-28 22:33:08 +00003597 case Instruction::SetNE: // (X < 13 | X != 15) -> X != 15
3598 case Instruction::SetLT: // (X < 13 | X < 15) -> X < 15
3599 return ReplaceInstUsesWith(I, RHS);
3600 }
3601 break;
3602 case Instruction::SetGT:
3603 switch (RHSCC) {
3604 default: assert(0 && "Unknown integer condition code!");
3605 case Instruction::SetEQ: // (X > 13 | X == 15) -> X > 13
3606 case Instruction::SetGT: // (X > 13 | X > 15) -> X > 13
3607 return ReplaceInstUsesWith(I, LHS);
3608 case Instruction::SetNE: // (X > 13 | X != 15) -> true
3609 case Instruction::SetLT: // (X > 13 | X < 15) -> true
Chris Lattner47811b72006-09-28 23:35:22 +00003610 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattnerb4f40d22004-09-28 22:33:08 +00003611 }
3612 }
3613 }
3614 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00003615
3616 // fold (or (cast A), (cast B)) -> (cast (or A, B))
3617 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner581a7ad2006-05-05 20:51:30 +00003618 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner6fc205f2006-05-05 06:39:07 +00003619 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Chris Lattner581a7ad2006-05-05 20:51:30 +00003620 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
Chris Lattner33a61132006-05-06 09:00:16 +00003621 // Only do this if the casts both really cause code to be generated.
3622 ValueRequiresCast(Op0C->getOperand(0), I.getType(), TD) &&
3623 ValueRequiresCast(Op1C->getOperand(0), I.getType(), TD)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00003624 Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
3625 Op1C->getOperand(0),
3626 I.getName());
3627 InsertNewInstBefore(NewOp, I);
3628 return new CastInst(NewOp, I.getType());
3629 }
3630 }
3631
Chris Lattnere9bed7d2005-09-18 03:42:07 +00003632
Chris Lattner7e708292002-06-25 16:13:24 +00003633 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00003634}
3635
Chris Lattnerc317d392004-02-16 01:20:27 +00003636// XorSelf - Implements: X ^ X --> 0
3637struct XorSelf {
3638 Value *RHS;
3639 XorSelf(Value *rhs) : RHS(rhs) {}
3640 bool shouldApply(Value *LHS) const { return LHS == RHS; }
3641 Instruction *apply(BinaryOperator &Xor) const {
3642 return &Xor;
3643 }
3644};
Chris Lattner3f5b8772002-05-06 16:14:14 +00003645
3646
Chris Lattner7e708292002-06-25 16:13:24 +00003647Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003648 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00003649 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003650
Chris Lattnere87597f2004-10-16 18:11:37 +00003651 if (isa<UndefValue>(Op1))
3652 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
3653
Chris Lattnerc317d392004-02-16 01:20:27 +00003654 // xor X, X = 0, even if X is nested in a sequence of Xor's.
3655 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
3656 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattner233f7dc2002-08-12 21:17:25 +00003657 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00003658 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003659
3660 // See if we can simplify any instructions used by the instruction whose sole
3661 // purpose is to compute bits we don't care about.
3662 uint64_t KnownZero, KnownOne;
Chris Lattner98509ef2006-03-25 21:58:26 +00003663 if (!isa<PackedType>(I.getType()) &&
3664 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003665 KnownZero, KnownOne))
3666 return &I;
Chris Lattner3f5b8772002-05-06 16:14:14 +00003667
Chris Lattnereca0c5c2003-07-23 21:37:07 +00003668 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattnereca0c5c2003-07-23 21:37:07 +00003669 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner05bd1b22002-08-20 18:24:26 +00003670 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
Chris Lattnereca0c5c2003-07-23 21:37:07 +00003671 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
Chris Lattner47811b72006-09-28 23:35:22 +00003672 if (RHS == ConstantBool::getTrue() && SCI->hasOneUse())
Chris Lattner05bd1b22002-08-20 18:24:26 +00003673 return new SetCondInst(SCI->getInverseCondition(),
3674 SCI->getOperand(0), SCI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00003675
Chris Lattnerd65460f2003-11-05 01:06:05 +00003676 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00003677 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
3678 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattner48595f12004-06-10 02:07:29 +00003679 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
3680 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattner7c4049c2004-01-12 19:35:11 +00003681 ConstantInt::get(I.getType(), 1));
Chris Lattner48595f12004-06-10 02:07:29 +00003682 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00003683 }
Chris Lattner5b62aa72004-06-18 06:07:51 +00003684
3685 // ~(~X & Y) --> (X | ~Y)
3686 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
3687 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
3688 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
3689 Instruction *NotY =
Misha Brukmanfd939082005-04-21 23:48:37 +00003690 BinaryOperator::createNot(Op0I->getOperand(1),
Chris Lattner5b62aa72004-06-18 06:07:51 +00003691 Op0I->getOperand(1)->getName()+".not");
3692 InsertNewInstBefore(NotY, I);
3693 return BinaryOperator::createOr(Op0NotVal, NotY);
3694 }
3695 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003696
Chris Lattnereca0c5c2003-07-23 21:37:07 +00003697 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003698 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00003699 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00003700 if (RHS->isAllOnesValue()) {
Chris Lattner48595f12004-06-10 02:07:29 +00003701 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
3702 return BinaryOperator::createSub(
3703 ConstantExpr::getSub(NegOp0CI,
Chris Lattner7c4049c2004-01-12 19:35:11 +00003704 ConstantInt::get(I.getType(), 1)),
Chris Lattner689d24b2003-11-04 23:37:10 +00003705 Op0I->getOperand(0));
Chris Lattner7c4049c2004-01-12 19:35:11 +00003706 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00003707 } else if (Op0I->getOpcode() == Instruction::Or) {
3708 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
3709 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getZExtValue())) {
3710 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
3711 // Anything in both C1 and C2 is known to be zero, remove it from
3712 // NewRHS.
3713 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
3714 NewRHS = ConstantExpr::getAnd(NewRHS,
3715 ConstantExpr::getNot(CommonBits));
3716 WorkList.push_back(Op0I);
3717 I.setOperand(0, Op0I->getOperand(0));
3718 I.setOperand(1, NewRHS);
3719 return &I;
3720 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00003721 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00003722 }
Chris Lattner2eefe512004-04-09 19:05:30 +00003723
3724 // Try to fold constant and into select arguments.
3725 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003726 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00003727 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00003728 if (isa<PHINode>(Op0))
3729 if (Instruction *NV = FoldOpIntoPhi(I))
3730 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00003731 }
3732
Chris Lattner8d969642003-03-10 23:06:50 +00003733 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00003734 if (X == Op1)
3735 return ReplaceInstUsesWith(I,
3736 ConstantIntegral::getAllOnesValue(I.getType()));
3737
Chris Lattner8d969642003-03-10 23:06:50 +00003738 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00003739 if (X == Op0)
3740 return ReplaceInstUsesWith(I,
3741 ConstantIntegral::getAllOnesValue(I.getType()));
3742
Chris Lattner64daab52006-04-01 08:03:55 +00003743 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
Chris Lattner26ca7e12004-02-16 03:54:20 +00003744 if (Op1I->getOpcode() == Instruction::Or) {
Chris Lattnercb40a372003-03-10 18:24:17 +00003745 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00003746 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00003747 I.swapOperands();
3748 std::swap(Op0, Op1);
3749 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00003750 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00003751 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00003752 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00003753 } else if (Op1I->getOpcode() == Instruction::Xor) {
3754 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
3755 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
3756 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
3757 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
Chris Lattner64daab52006-04-01 08:03:55 +00003758 } else if (Op1I->getOpcode() == Instruction::And && Op1I->hasOneUse()) {
3759 if (Op1I->getOperand(0) == Op0) // A^(A&B) -> A^(B&A)
3760 Op1I->swapOperands();
3761 if (Op0 == Op1I->getOperand(1)) { // A^(B&A) -> (B&A)^A
3762 I.swapOperands(); // Simplified below.
3763 std::swap(Op0, Op1);
3764 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00003765 }
Chris Lattnercb40a372003-03-10 18:24:17 +00003766
Chris Lattner64daab52006-04-01 08:03:55 +00003767 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
Chris Lattnerfd059242003-10-15 16:48:29 +00003768 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
Chris Lattnercb40a372003-03-10 18:24:17 +00003769 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00003770 Op0I->swapOperands();
Chris Lattner4f98c562003-03-10 21:43:22 +00003771 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattner64daab52006-04-01 08:03:55 +00003772 Instruction *NotB = BinaryOperator::createNot(Op1, "tmp");
3773 InsertNewInstBefore(NotB, I);
Chris Lattner48595f12004-06-10 02:07:29 +00003774 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
Chris Lattnercb40a372003-03-10 18:24:17 +00003775 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00003776 } else if (Op0I->getOpcode() == Instruction::Xor) {
3777 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
3778 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
3779 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
3780 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner64daab52006-04-01 08:03:55 +00003781 } else if (Op0I->getOpcode() == Instruction::And && Op0I->hasOneUse()) {
3782 if (Op0I->getOperand(0) == Op1) // (A&B)^A -> (B&A)^A
3783 Op0I->swapOperands();
Chris Lattnerae1ab392006-04-01 22:05:01 +00003784 if (Op0I->getOperand(1) == Op1 && // (B&A)^A == ~B & A
3785 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner64daab52006-04-01 08:03:55 +00003786 Instruction *N = BinaryOperator::createNot(Op0I->getOperand(0), "tmp");
3787 InsertNewInstBefore(N, I);
3788 return BinaryOperator::createAnd(N, Op1);
3789 }
Chris Lattnercb40a372003-03-10 18:24:17 +00003790 }
3791
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003792 // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
3793 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
3794 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
3795 return R;
3796
Chris Lattner6fc205f2006-05-05 06:39:07 +00003797 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
3798 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner581a7ad2006-05-05 20:51:30 +00003799 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner6fc205f2006-05-05 06:39:07 +00003800 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Chris Lattner581a7ad2006-05-05 20:51:30 +00003801 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
Chris Lattner33a61132006-05-06 09:00:16 +00003802 // Only do this if the casts both really cause code to be generated.
3803 ValueRequiresCast(Op0C->getOperand(0), I.getType(), TD) &&
3804 ValueRequiresCast(Op1C->getOperand(0), I.getType(), TD)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00003805 Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
3806 Op1C->getOperand(0),
3807 I.getName());
3808 InsertNewInstBefore(NewOp, I);
3809 return new CastInst(NewOp, I.getType());
3810 }
3811 }
3812
Chris Lattner7e708292002-06-25 16:13:24 +00003813 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00003814}
3815
Chris Lattnera96879a2004-09-29 17:40:11 +00003816static bool isPositive(ConstantInt *C) {
Reid Spencerb83eb642006-10-20 07:07:24 +00003817 return C->getSExtValue() >= 0;
Chris Lattnera96879a2004-09-29 17:40:11 +00003818}
3819
3820/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
3821/// overflowed for this type.
3822static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
3823 ConstantInt *In2) {
3824 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
3825
3826 if (In1->getType()->isUnsigned())
Reid Spencerb83eb642006-10-20 07:07:24 +00003827 return cast<ConstantInt>(Result)->getZExtValue() <
3828 cast<ConstantInt>(In1)->getZExtValue();
Chris Lattnera96879a2004-09-29 17:40:11 +00003829 if (isPositive(In1) != isPositive(In2))
3830 return false;
3831 if (isPositive(In1))
Reid Spencerb83eb642006-10-20 07:07:24 +00003832 return cast<ConstantInt>(Result)->getSExtValue() <
3833 cast<ConstantInt>(In1)->getSExtValue();
3834 return cast<ConstantInt>(Result)->getSExtValue() >
3835 cast<ConstantInt>(In1)->getSExtValue();
Chris Lattnera96879a2004-09-29 17:40:11 +00003836}
3837
Chris Lattner574da9b2005-01-13 20:14:25 +00003838/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
3839/// code necessary to compute the offset from the base pointer (without adding
3840/// in the base pointer). Return the result as a signed integer of intptr size.
3841static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
3842 TargetData &TD = IC.getTargetData();
3843 gep_type_iterator GTI = gep_type_begin(GEP);
3844 const Type *UIntPtrTy = TD.getIntPtrType();
3845 const Type *SIntPtrTy = UIntPtrTy->getSignedVersion();
3846 Value *Result = Constant::getNullValue(SIntPtrTy);
3847
3848 // Build a mask for high order bits.
Chris Lattner1a074fc2006-02-07 07:00:41 +00003849 uint64_t PtrSizeMask = ~0ULL >> (64-TD.getPointerSize()*8);
Chris Lattner574da9b2005-01-13 20:14:25 +00003850
Chris Lattner574da9b2005-01-13 20:14:25 +00003851 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
3852 Value *Op = GEP->getOperand(i);
Chris Lattner0b84c802005-01-13 23:26:48 +00003853 uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
Reid Spencerb83eb642006-10-20 07:07:24 +00003854 Constant *Scale = ConstantExpr::getCast(ConstantInt::get(UIntPtrTy, Size),
Chris Lattner574da9b2005-01-13 20:14:25 +00003855 SIntPtrTy);
3856 if (Constant *OpC = dyn_cast<Constant>(Op)) {
3857 if (!OpC->isNullValue()) {
Chris Lattner5bdf04c2005-01-13 20:40:58 +00003858 OpC = ConstantExpr::getCast(OpC, SIntPtrTy);
Chris Lattner574da9b2005-01-13 20:14:25 +00003859 Scale = ConstantExpr::getMul(OpC, Scale);
3860 if (Constant *RC = dyn_cast<Constant>(Result))
3861 Result = ConstantExpr::getAdd(RC, Scale);
3862 else {
3863 // Emit an add instruction.
3864 Result = IC.InsertNewInstBefore(
3865 BinaryOperator::createAdd(Result, Scale,
3866 GEP->getName()+".offs"), I);
3867 }
3868 }
3869 } else {
Chris Lattner6f7f02f2005-01-14 17:17:59 +00003870 // Convert to correct type.
3871 Op = IC.InsertNewInstBefore(new CastInst(Op, SIntPtrTy,
3872 Op->getName()+".c"), I);
3873 if (Size != 1)
Chris Lattner5bdf04c2005-01-13 20:40:58 +00003874 // We'll let instcombine(mul) convert this to a shl if possible.
3875 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
3876 GEP->getName()+".idx"), I);
Chris Lattner574da9b2005-01-13 20:14:25 +00003877
3878 // Emit an add instruction.
Chris Lattner5bdf04c2005-01-13 20:40:58 +00003879 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
Chris Lattner574da9b2005-01-13 20:14:25 +00003880 GEP->getName()+".offs"), I);
3881 }
3882 }
3883 return Result;
3884}
3885
3886/// FoldGEPSetCC - Fold comparisons between a GEP instruction and something
3887/// else. At this point we know that the GEP is on the LHS of the comparison.
3888Instruction *InstCombiner::FoldGEPSetCC(User *GEPLHS, Value *RHS,
3889 Instruction::BinaryOps Cond,
3890 Instruction &I) {
3891 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattnere9d782b2005-01-13 22:25:21 +00003892
3893 if (CastInst *CI = dyn_cast<CastInst>(RHS))
3894 if (isa<PointerType>(CI->getOperand(0)->getType()))
3895 RHS = CI->getOperand(0);
3896
Chris Lattner574da9b2005-01-13 20:14:25 +00003897 Value *PtrBase = GEPLHS->getOperand(0);
3898 if (PtrBase == RHS) {
3899 // As an optimization, we don't actually have to compute the actual value of
3900 // OFFSET if this is a seteq or setne comparison, just return whether each
3901 // index is zero or not.
Chris Lattnere9d782b2005-01-13 22:25:21 +00003902 if (Cond == Instruction::SetEQ || Cond == Instruction::SetNE) {
3903 Instruction *InVal = 0;
Chris Lattnerad5fec12005-01-28 19:32:01 +00003904 gep_type_iterator GTI = gep_type_begin(GEPLHS);
3905 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattnere9d782b2005-01-13 22:25:21 +00003906 bool EmitIt = true;
3907 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
3908 if (isa<UndefValue>(C)) // undef index -> undef.
3909 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3910 if (C->isNullValue())
3911 EmitIt = false;
Chris Lattnerad5fec12005-01-28 19:32:01 +00003912 else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
3913 EmitIt = false; // This is indexing into a zero sized array?
Misha Brukmanfd939082005-04-21 23:48:37 +00003914 } else if (isa<ConstantInt>(C))
Chris Lattnere9d782b2005-01-13 22:25:21 +00003915 return ReplaceInstUsesWith(I, // No comparison is needed here.
3916 ConstantBool::get(Cond == Instruction::SetNE));
3917 }
3918
3919 if (EmitIt) {
Misha Brukmanfd939082005-04-21 23:48:37 +00003920 Instruction *Comp =
Chris Lattnere9d782b2005-01-13 22:25:21 +00003921 new SetCondInst(Cond, GEPLHS->getOperand(i),
3922 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
3923 if (InVal == 0)
3924 InVal = Comp;
3925 else {
3926 InVal = InsertNewInstBefore(InVal, I);
3927 InsertNewInstBefore(Comp, I);
3928 if (Cond == Instruction::SetNE) // True if any are unequal
3929 InVal = BinaryOperator::createOr(InVal, Comp);
3930 else // True if all are equal
3931 InVal = BinaryOperator::createAnd(InVal, Comp);
3932 }
3933 }
3934 }
3935
3936 if (InVal)
3937 return InVal;
3938 else
3939 ReplaceInstUsesWith(I, // No comparison is needed here, all indexes = 0
3940 ConstantBool::get(Cond == Instruction::SetEQ));
3941 }
Chris Lattner574da9b2005-01-13 20:14:25 +00003942
3943 // Only lower this if the setcc is the only user of the GEP or if we expect
3944 // the result to fold to a constant!
3945 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
3946 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
3947 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
3948 return new SetCondInst(Cond, Offset,
3949 Constant::getNullValue(Offset->getType()));
3950 }
3951 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00003952 // If the base pointers are different, but the indices are the same, just
3953 // compare the base pointer.
3954 if (PtrBase != GEPRHS->getOperand(0)) {
3955 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00003956 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00003957 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00003958 if (IndicesTheSame)
3959 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
3960 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
3961 IndicesTheSame = false;
3962 break;
3963 }
3964
3965 // If all indices are the same, just compare the base pointers.
3966 if (IndicesTheSame)
3967 return new SetCondInst(Cond, GEPLHS->getOperand(0),
3968 GEPRHS->getOperand(0));
3969
3970 // Otherwise, the base pointers are different and the indices are
3971 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00003972 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00003973 }
Chris Lattner574da9b2005-01-13 20:14:25 +00003974
Chris Lattnere9d782b2005-01-13 22:25:21 +00003975 // If one of the GEPs has all zero indices, recurse.
3976 bool AllZeros = true;
3977 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
3978 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
3979 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
3980 AllZeros = false;
3981 break;
3982 }
3983 if (AllZeros)
3984 return FoldGEPSetCC(GEPRHS, GEPLHS->getOperand(0),
3985 SetCondInst::getSwappedCondition(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00003986
3987 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00003988 AllZeros = true;
3989 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
3990 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
3991 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
3992 AllZeros = false;
3993 break;
3994 }
3995 if (AllZeros)
3996 return FoldGEPSetCC(GEPLHS, GEPRHS->getOperand(0), Cond, I);
3997
Chris Lattner4401c9c2005-01-14 00:20:05 +00003998 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
3999 // If the GEPs only differ by one index, compare it.
4000 unsigned NumDifferences = 0; // Keep track of # differences.
4001 unsigned DiffOperand = 0; // The operand that differs.
4002 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4003 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00004004 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4005 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00004006 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00004007 NumDifferences = 2;
4008 break;
4009 } else {
4010 if (NumDifferences++) break;
4011 DiffOperand = i;
4012 }
4013 }
4014
4015 if (NumDifferences == 0) // SAME GEP?
4016 return ReplaceInstUsesWith(I, // No comparison is needed here.
4017 ConstantBool::get(Cond == Instruction::SetEQ));
4018 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00004019 Value *LHSV = GEPLHS->getOperand(DiffOperand);
4020 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Chris Lattner7911f032005-07-18 23:07:33 +00004021
4022 // Convert the operands to signed values to make sure to perform a
4023 // signed comparison.
4024 const Type *NewTy = LHSV->getType()->getSignedVersion();
4025 if (LHSV->getType() != NewTy)
Reid Spencer811b0cb2006-10-26 19:19:06 +00004026 LHSV = InsertCastBefore(LHSV, NewTy, I);
Chris Lattner7911f032005-07-18 23:07:33 +00004027 if (RHSV->getType() != NewTy)
Reid Spencer811b0cb2006-10-26 19:19:06 +00004028 RHSV = InsertCastBefore(RHSV, NewTy, I);
Chris Lattner7911f032005-07-18 23:07:33 +00004029 return new SetCondInst(Cond, LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00004030 }
4031 }
4032
Chris Lattner574da9b2005-01-13 20:14:25 +00004033 // Only lower this if the setcc is the only user of the GEP or if we expect
4034 // the result to fold to a constant!
4035 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4036 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4037 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
4038 Value *L = EmitGEPOffset(GEPLHS, I, *this);
4039 Value *R = EmitGEPOffset(GEPRHS, I, *this);
4040 return new SetCondInst(Cond, L, R);
4041 }
4042 }
4043 return 0;
4044}
4045
4046
Chris Lattner484d3cf2005-04-24 06:59:08 +00004047Instruction *InstCombiner::visitSetCondInst(SetCondInst &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004048 bool Changed = SimplifyCommutative(I);
Chris Lattner8b170942002-08-09 23:47:40 +00004049 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4050 const Type *Ty = Op0->getType();
Chris Lattner3f5b8772002-05-06 16:14:14 +00004051
4052 // setcc X, X
Chris Lattner8b170942002-08-09 23:47:40 +00004053 if (Op0 == Op1)
4054 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
Chris Lattner53a5b572002-05-09 20:11:54 +00004055
Chris Lattnere87597f2004-10-16 18:11:37 +00004056 if (isa<UndefValue>(Op1)) // X setcc undef -> undef
4057 return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
4058
Chris Lattner711b3402004-11-14 07:33:16 +00004059 // setcc <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
4060 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanfd939082005-04-21 23:48:37 +00004061 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
4062 isa<ConstantPointerNull>(Op0)) &&
4063 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner711b3402004-11-14 07:33:16 +00004064 isa<ConstantPointerNull>(Op1)))
Chris Lattner8b170942002-08-09 23:47:40 +00004065 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
4066
4067 // setcc's with boolean values can always be turned into bitwise operations
4068 if (Ty == Type::BoolTy) {
Chris Lattner5dbef222004-08-11 00:50:51 +00004069 switch (I.getOpcode()) {
4070 default: assert(0 && "Invalid setcc instruction!");
4071 case Instruction::SetEQ: { // seteq bool %A, %B -> ~(A^B)
Chris Lattner48595f12004-06-10 02:07:29 +00004072 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner8b170942002-08-09 23:47:40 +00004073 InsertNewInstBefore(Xor, I);
Chris Lattnerde90b762003-11-03 04:25:02 +00004074 return BinaryOperator::createNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00004075 }
Chris Lattner5dbef222004-08-11 00:50:51 +00004076 case Instruction::SetNE:
4077 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00004078
Chris Lattner5dbef222004-08-11 00:50:51 +00004079 case Instruction::SetGT:
4080 std::swap(Op0, Op1); // Change setgt -> setlt
4081 // FALL THROUGH
4082 case Instruction::SetLT: { // setlt bool A, B -> ~X & Y
4083 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4084 InsertNewInstBefore(Not, I);
4085 return BinaryOperator::createAnd(Not, Op1);
4086 }
4087 case Instruction::SetGE:
Chris Lattner8b170942002-08-09 23:47:40 +00004088 std::swap(Op0, Op1); // Change setge -> setle
Chris Lattner5dbef222004-08-11 00:50:51 +00004089 // FALL THROUGH
4090 case Instruction::SetLE: { // setle bool %A, %B -> ~A | B
4091 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4092 InsertNewInstBefore(Not, I);
4093 return BinaryOperator::createOr(Not, Op1);
4094 }
4095 }
Chris Lattner8b170942002-08-09 23:47:40 +00004096 }
4097
Chris Lattner2be51ae2004-06-09 04:24:29 +00004098 // See if we are doing a comparison between a constant and an instruction that
4099 // can be folded into the comparison.
Chris Lattner8b170942002-08-09 23:47:40 +00004100 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnera96879a2004-09-29 17:40:11 +00004101 // Check to see if we are comparing against the minimum or maximum value...
4102 if (CI->isMinValue()) {
4103 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
Chris Lattner47811b72006-09-28 23:35:22 +00004104 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattnera96879a2004-09-29 17:40:11 +00004105 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
Chris Lattner47811b72006-09-28 23:35:22 +00004106 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattnera96879a2004-09-29 17:40:11 +00004107 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
4108 return BinaryOperator::createSetEQ(Op0, Op1);
4109 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
4110 return BinaryOperator::createSetNE(Op0, Op1);
4111
4112 } else if (CI->isMaxValue()) {
4113 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
Chris Lattner47811b72006-09-28 23:35:22 +00004114 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattnera96879a2004-09-29 17:40:11 +00004115 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
Chris Lattner47811b72006-09-28 23:35:22 +00004116 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattnera96879a2004-09-29 17:40:11 +00004117 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
4118 return BinaryOperator::createSetEQ(Op0, Op1);
4119 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
4120 return BinaryOperator::createSetNE(Op0, Op1);
4121
4122 // Comparing against a value really close to min or max?
4123 } else if (isMinValuePlusOne(CI)) {
4124 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
4125 return BinaryOperator::createSetEQ(Op0, SubOne(CI));
4126 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
4127 return BinaryOperator::createSetNE(Op0, SubOne(CI));
4128
4129 } else if (isMaxValueMinusOne(CI)) {
4130 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
4131 return BinaryOperator::createSetEQ(Op0, AddOne(CI));
4132 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
4133 return BinaryOperator::createSetNE(Op0, AddOne(CI));
4134 }
4135
4136 // If we still have a setle or setge instruction, turn it into the
4137 // appropriate setlt or setgt instruction. Since the border cases have
4138 // already been handled above, this requires little checking.
4139 //
4140 if (I.getOpcode() == Instruction::SetLE)
4141 return BinaryOperator::createSetLT(Op0, AddOne(CI));
4142 if (I.getOpcode() == Instruction::SetGE)
4143 return BinaryOperator::createSetGT(Op0, SubOne(CI));
4144
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00004145
4146 // See if we can fold the comparison based on bits known to be zero or one
4147 // in the input.
4148 uint64_t KnownZero, KnownOne;
4149 if (SimplifyDemandedBits(Op0, Ty->getIntegralTypeMask(),
4150 KnownZero, KnownOne, 0))
4151 return &I;
4152
4153 // Given the known and unknown bits, compute a range that the LHS could be
4154 // in.
4155 if (KnownOne | KnownZero) {
4156 if (Ty->isUnsigned()) { // Unsigned comparison.
4157 uint64_t Min, Max;
4158 uint64_t RHSVal = CI->getZExtValue();
4159 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,
4160 Min, Max);
4161 switch (I.getOpcode()) { // LE/GE have been folded already.
4162 default: assert(0 && "Unknown setcc opcode!");
4163 case Instruction::SetEQ:
4164 if (Max < RHSVal || Min > RHSVal)
Chris Lattner47811b72006-09-28 23:35:22 +00004165 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00004166 break;
4167 case Instruction::SetNE:
4168 if (Max < RHSVal || Min > RHSVal)
Chris Lattner47811b72006-09-28 23:35:22 +00004169 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00004170 break;
4171 case Instruction::SetLT:
Chris Lattner47811b72006-09-28 23:35:22 +00004172 if (Max < RHSVal)
4173 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4174 if (Min > RHSVal)
4175 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00004176 break;
4177 case Instruction::SetGT:
Chris Lattner47811b72006-09-28 23:35:22 +00004178 if (Min > RHSVal)
4179 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4180 if (Max < RHSVal)
4181 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00004182 break;
4183 }
4184 } else { // Signed comparison.
4185 int64_t Min, Max;
4186 int64_t RHSVal = CI->getSExtValue();
4187 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,
4188 Min, Max);
4189 switch (I.getOpcode()) { // LE/GE have been folded already.
4190 default: assert(0 && "Unknown setcc opcode!");
4191 case Instruction::SetEQ:
4192 if (Max < RHSVal || Min > RHSVal)
Chris Lattner47811b72006-09-28 23:35:22 +00004193 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00004194 break;
4195 case Instruction::SetNE:
4196 if (Max < RHSVal || Min > RHSVal)
Chris Lattner47811b72006-09-28 23:35:22 +00004197 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00004198 break;
4199 case Instruction::SetLT:
Chris Lattner47811b72006-09-28 23:35:22 +00004200 if (Max < RHSVal)
4201 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4202 if (Min > RHSVal)
4203 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00004204 break;
4205 case Instruction::SetGT:
Chris Lattner47811b72006-09-28 23:35:22 +00004206 if (Min > RHSVal)
4207 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4208 if (Max < RHSVal)
4209 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00004210 break;
4211 }
4212 }
4213 }
4214
Reid Spencer1628cec2006-10-26 06:15:43 +00004215 // Since the RHS is a constantInt (CI), if the left hand side is an
4216 // instruction, see if that instruction also has constants so that the
4217 // instruction can be folded into the setcc
Chris Lattner3c6a0d42004-05-25 06:32:08 +00004218 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner648e3bc2004-09-23 21:52:49 +00004219 switch (LHSI->getOpcode()) {
4220 case Instruction::And:
4221 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
4222 LHSI->getOperand(0)->hasOneUse()) {
Chris Lattnere695a3b2006-09-18 05:27:43 +00004223 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
4224
4225 // If an operand is an AND of a truncating cast, we can widen the
4226 // and/compare to be the input width without changing the value
4227 // produced, eliminating a cast.
4228 if (CastInst *Cast = dyn_cast<CastInst>(LHSI->getOperand(0))) {
4229 // We can do this transformation if either the AND constant does not
4230 // have its sign bit set or if it is an equality comparison.
4231 // Extending a relational comparison when we're checking the sign
4232 // bit would not work.
4233 if (Cast->hasOneUse() && Cast->isTruncIntCast() &&
4234 (I.isEquality() ||
4235 (AndCST->getZExtValue() == (uint64_t)AndCST->getSExtValue()) &&
4236 (CI->getZExtValue() == (uint64_t)CI->getSExtValue()))) {
4237 ConstantInt *NewCST;
4238 ConstantInt *NewCI;
4239 if (Cast->getOperand(0)->getType()->isSigned()) {
Reid Spencerb83eb642006-10-20 07:07:24 +00004240 NewCST = ConstantInt::get(Cast->getOperand(0)->getType(),
Chris Lattnere695a3b2006-09-18 05:27:43 +00004241 AndCST->getZExtValue());
Reid Spencerb83eb642006-10-20 07:07:24 +00004242 NewCI = ConstantInt::get(Cast->getOperand(0)->getType(),
Chris Lattnere695a3b2006-09-18 05:27:43 +00004243 CI->getZExtValue());
4244 } else {
Reid Spencerb83eb642006-10-20 07:07:24 +00004245 NewCST = ConstantInt::get(Cast->getOperand(0)->getType(),
Chris Lattnere695a3b2006-09-18 05:27:43 +00004246 AndCST->getZExtValue());
Reid Spencerb83eb642006-10-20 07:07:24 +00004247 NewCI = ConstantInt::get(Cast->getOperand(0)->getType(),
Chris Lattnere695a3b2006-09-18 05:27:43 +00004248 CI->getZExtValue());
4249 }
4250 Instruction *NewAnd =
4251 BinaryOperator::createAnd(Cast->getOperand(0), NewCST,
4252 LHSI->getName());
4253 InsertNewInstBefore(NewAnd, I);
4254 return new SetCondInst(I.getOpcode(), NewAnd, NewCI);
4255 }
4256 }
4257
Chris Lattner648e3bc2004-09-23 21:52:49 +00004258 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
4259 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
4260 // happens a LOT in code produced by the C front-end, for bitfield
4261 // access.
4262 ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00004263
4264 // Check to see if there is a noop-cast between the shift and the and.
4265 if (!Shift) {
4266 if (CastInst *CI = dyn_cast<CastInst>(LHSI->getOperand(0)))
4267 if (CI->getOperand(0)->getType()->isIntegral() &&
4268 CI->getOperand(0)->getType()->getPrimitiveSizeInBits() ==
4269 CI->getType()->getPrimitiveSizeInBits())
4270 Shift = dyn_cast<ShiftInst>(CI->getOperand(0));
4271 }
Chris Lattner65b72ba2006-09-18 04:22:48 +00004272
Reid Spencerb83eb642006-10-20 07:07:24 +00004273 ConstantInt *ShAmt;
4274 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00004275 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
4276 const Type *AndTy = AndCST->getType(); // Type of the and.
Misha Brukmanfd939082005-04-21 23:48:37 +00004277
Chris Lattner648e3bc2004-09-23 21:52:49 +00004278 // We can fold this as long as we can't shift unknown bits
4279 // into the mask. This can only happen with signed shift
4280 // rights, as they sign-extend.
4281 if (ShAmt) {
Chris Lattner65b72ba2006-09-18 04:22:48 +00004282 bool CanFold = Shift->isLogicalShift();
Chris Lattner648e3bc2004-09-23 21:52:49 +00004283 if (!CanFold) {
4284 // To test for the bad case of the signed shr, see if any
4285 // of the bits shifted in could be tested after the mask.
Reid Spencerb83eb642006-10-20 07:07:24 +00004286 int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getZExtValue();
Chris Lattnerd7e31cf2005-06-17 01:29:28 +00004287 if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
4288
Reid Spencerb83eb642006-10-20 07:07:24 +00004289 Constant *OShAmt = ConstantInt::get(Type::UByteTy, ShAmtVal);
Misha Brukmanfd939082005-04-21 23:48:37 +00004290 Constant *ShVal =
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00004291 ConstantExpr::getShl(ConstantInt::getAllOnesValue(AndTy),
4292 OShAmt);
Chris Lattner648e3bc2004-09-23 21:52:49 +00004293 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
4294 CanFold = true;
4295 }
Misha Brukmanfd939082005-04-21 23:48:37 +00004296
Chris Lattner648e3bc2004-09-23 21:52:49 +00004297 if (CanFold) {
Chris Lattner0cba71b2004-09-28 17:54:07 +00004298 Constant *NewCst;
4299 if (Shift->getOpcode() == Instruction::Shl)
4300 NewCst = ConstantExpr::getUShr(CI, ShAmt);
4301 else
4302 NewCst = ConstantExpr::getShl(CI, ShAmt);
Chris Lattner83c4ec02004-09-27 19:29:18 +00004303
Chris Lattner648e3bc2004-09-23 21:52:49 +00004304 // Check to see if we are shifting out any of the bits being
4305 // compared.
4306 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
4307 // If we shifted bits out, the fold is not going to work out.
4308 // As a special case, check to see if this means that the
4309 // result is always true or false now.
4310 if (I.getOpcode() == Instruction::SetEQ)
Chris Lattner47811b72006-09-28 23:35:22 +00004311 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattner648e3bc2004-09-23 21:52:49 +00004312 if (I.getOpcode() == Instruction::SetNE)
Chris Lattner47811b72006-09-28 23:35:22 +00004313 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattner648e3bc2004-09-23 21:52:49 +00004314 } else {
4315 I.setOperand(1, NewCst);
Chris Lattner0cba71b2004-09-28 17:54:07 +00004316 Constant *NewAndCST;
4317 if (Shift->getOpcode() == Instruction::Shl)
4318 NewAndCST = ConstantExpr::getUShr(AndCST, ShAmt);
4319 else
4320 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
4321 LHSI->setOperand(1, NewAndCST);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00004322 if (AndTy == Ty)
4323 LHSI->setOperand(0, Shift->getOperand(0));
4324 else {
4325 Value *NewCast = InsertCastBefore(Shift->getOperand(0), AndTy,
4326 *Shift);
4327 LHSI->setOperand(0, NewCast);
4328 }
Chris Lattner648e3bc2004-09-23 21:52:49 +00004329 WorkList.push_back(Shift); // Shift is dead.
4330 AddUsesToWorkList(I);
4331 return &I;
Chris Lattner5eb91942004-07-21 19:50:44 +00004332 }
4333 }
Chris Lattner457dd822004-06-09 07:59:58 +00004334 }
Chris Lattner65b72ba2006-09-18 04:22:48 +00004335
4336 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
4337 // preferable because it allows the C<<Y expression to be hoisted out
4338 // of a loop if Y is invariant and X is not.
4339 if (Shift && Shift->hasOneUse() && CI->isNullValue() &&
Chris Lattner6d7ca922006-09-18 18:27:05 +00004340 I.isEquality() && !Shift->isArithmeticShift() &&
4341 isa<Instruction>(Shift->getOperand(0))) {
Chris Lattner65b72ba2006-09-18 04:22:48 +00004342 // Compute C << Y.
4343 Value *NS;
4344 if (Shift->getOpcode() == Instruction::Shr) {
4345 NS = new ShiftInst(Instruction::Shl, AndCST, Shift->getOperand(1),
4346 "tmp");
4347 } else {
4348 // Make sure we insert a logical shift.
Chris Lattnere695a3b2006-09-18 05:27:43 +00004349 Constant *NewAndCST = AndCST;
Chris Lattner65b72ba2006-09-18 04:22:48 +00004350 if (AndCST->getType()->isSigned())
Chris Lattnere695a3b2006-09-18 05:27:43 +00004351 NewAndCST = ConstantExpr::getCast(AndCST,
Chris Lattner65b72ba2006-09-18 04:22:48 +00004352 AndCST->getType()->getUnsignedVersion());
Chris Lattnere695a3b2006-09-18 05:27:43 +00004353 NS = new ShiftInst(Instruction::Shr, NewAndCST,
4354 Shift->getOperand(1), "tmp");
Chris Lattner65b72ba2006-09-18 04:22:48 +00004355 }
4356 InsertNewInstBefore(cast<Instruction>(NS), I);
4357
4358 // If C's sign doesn't agree with the and, insert a cast now.
4359 if (NS->getType() != LHSI->getType())
4360 NS = InsertCastBefore(NS, LHSI->getType(), I);
4361
4362 Value *ShiftOp = Shift->getOperand(0);
4363 if (ShiftOp->getType() != LHSI->getType())
4364 ShiftOp = InsertCastBefore(ShiftOp, LHSI->getType(), I);
4365
4366 // Compute X & (C << Y).
4367 Instruction *NewAnd =
4368 BinaryOperator::createAnd(ShiftOp, NS, LHSI->getName());
4369 InsertNewInstBefore(NewAnd, I);
4370
4371 I.setOperand(0, NewAnd);
4372 return &I;
4373 }
Chris Lattner648e3bc2004-09-23 21:52:49 +00004374 }
4375 break;
Chris Lattner83c4ec02004-09-27 19:29:18 +00004376
Chris Lattner18d19ca2004-09-28 18:22:15 +00004377 case Instruction::Shl: // (setcc (shl X, ShAmt), CI)
Reid Spencerb83eb642006-10-20 07:07:24 +00004378 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Chris Lattner65b72ba2006-09-18 04:22:48 +00004379 if (I.isEquality()) {
Chris Lattnere17a1282005-06-15 20:53:31 +00004380 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
4381
4382 // Check that the shift amount is in range. If not, don't perform
4383 // undefined shifts. When the shift is visited it will be
4384 // simplified.
Reid Spencerb83eb642006-10-20 07:07:24 +00004385 if (ShAmt->getZExtValue() >= TypeBits)
Chris Lattnere17a1282005-06-15 20:53:31 +00004386 break;
4387
Chris Lattner18d19ca2004-09-28 18:22:15 +00004388 // If we are comparing against bits always shifted out, the
4389 // comparison cannot succeed.
Misha Brukmanfd939082005-04-21 23:48:37 +00004390 Constant *Comp =
Chris Lattner18d19ca2004-09-28 18:22:15 +00004391 ConstantExpr::getShl(ConstantExpr::getShr(CI, ShAmt), ShAmt);
4392 if (Comp != CI) {// Comparing against a bit that we know is zero.
4393 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
4394 Constant *Cst = ConstantBool::get(IsSetNE);
4395 return ReplaceInstUsesWith(I, Cst);
4396 }
4397
4398 if (LHSI->hasOneUse()) {
4399 // Otherwise strength reduce the shift into an and.
Reid Spencerb83eb642006-10-20 07:07:24 +00004400 unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
Chris Lattner18d19ca2004-09-28 18:22:15 +00004401 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
4402
4403 Constant *Mask;
4404 if (CI->getType()->isUnsigned()) {
Reid Spencerb83eb642006-10-20 07:07:24 +00004405 Mask = ConstantInt::get(CI->getType(), Val);
Chris Lattner18d19ca2004-09-28 18:22:15 +00004406 } else if (ShAmtVal != 0) {
Reid Spencerb83eb642006-10-20 07:07:24 +00004407 Mask = ConstantInt::get(CI->getType(), Val);
Chris Lattner18d19ca2004-09-28 18:22:15 +00004408 } else {
4409 Mask = ConstantInt::getAllOnesValue(CI->getType());
4410 }
Misha Brukmanfd939082005-04-21 23:48:37 +00004411
Chris Lattner18d19ca2004-09-28 18:22:15 +00004412 Instruction *AndI =
4413 BinaryOperator::createAnd(LHSI->getOperand(0),
4414 Mask, LHSI->getName()+".mask");
4415 Value *And = InsertNewInstBefore(AndI, I);
4416 return new SetCondInst(I.getOpcode(), And,
4417 ConstantExpr::getUShr(CI, ShAmt));
4418 }
4419 }
Chris Lattner18d19ca2004-09-28 18:22:15 +00004420 }
4421 break;
4422
Chris Lattner83c4ec02004-09-27 19:29:18 +00004423 case Instruction::Shr: // (setcc (shr X, ShAmt), CI)
Reid Spencerb83eb642006-10-20 07:07:24 +00004424 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Chris Lattner65b72ba2006-09-18 04:22:48 +00004425 if (I.isEquality()) {
Chris Lattnere17a1282005-06-15 20:53:31 +00004426 // Check that the shift amount is in range. If not, don't perform
4427 // undefined shifts. When the shift is visited it will be
4428 // simplified.
Chris Lattneraa457ac2005-06-16 01:52:07 +00004429 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencerb83eb642006-10-20 07:07:24 +00004430 if (ShAmt->getZExtValue() >= TypeBits)
Chris Lattnere17a1282005-06-15 20:53:31 +00004431 break;
4432
Chris Lattnerf63f6472004-09-27 16:18:50 +00004433 // If we are comparing against bits always shifted out, the
4434 // comparison cannot succeed.
Misha Brukmanfd939082005-04-21 23:48:37 +00004435 Constant *Comp =
Chris Lattnerf63f6472004-09-27 16:18:50 +00004436 ConstantExpr::getShr(ConstantExpr::getShl(CI, ShAmt), ShAmt);
Misha Brukmanfd939082005-04-21 23:48:37 +00004437
Chris Lattnerf63f6472004-09-27 16:18:50 +00004438 if (Comp != CI) {// Comparing against a bit that we know is zero.
4439 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
4440 Constant *Cst = ConstantBool::get(IsSetNE);
4441 return ReplaceInstUsesWith(I, Cst);
4442 }
Misha Brukmanfd939082005-04-21 23:48:37 +00004443
Chris Lattnerf63f6472004-09-27 16:18:50 +00004444 if (LHSI->hasOneUse() || CI->isNullValue()) {
Reid Spencerb83eb642006-10-20 07:07:24 +00004445 unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
Chris Lattner18d19ca2004-09-28 18:22:15 +00004446
Chris Lattnerf63f6472004-09-27 16:18:50 +00004447 // Otherwise strength reduce the shift into an and.
4448 uint64_t Val = ~0ULL; // All ones.
4449 Val <<= ShAmtVal; // Shift over to the right spot.
4450
4451 Constant *Mask;
4452 if (CI->getType()->isUnsigned()) {
Chris Lattnerf52d6812005-04-24 17:46:05 +00004453 Val &= ~0ULL >> (64-TypeBits);
Reid Spencerb83eb642006-10-20 07:07:24 +00004454 Mask = ConstantInt::get(CI->getType(), Val);
Chris Lattnerf63f6472004-09-27 16:18:50 +00004455 } else {
Reid Spencerb83eb642006-10-20 07:07:24 +00004456 Mask = ConstantInt::get(CI->getType(), Val);
Chris Lattnerf63f6472004-09-27 16:18:50 +00004457 }
Misha Brukmanfd939082005-04-21 23:48:37 +00004458
Chris Lattnerf63f6472004-09-27 16:18:50 +00004459 Instruction *AndI =
4460 BinaryOperator::createAnd(LHSI->getOperand(0),
4461 Mask, LHSI->getName()+".mask");
4462 Value *And = InsertNewInstBefore(AndI, I);
4463 return new SetCondInst(I.getOpcode(), And,
4464 ConstantExpr::getShl(CI, ShAmt));
4465 }
Chris Lattnerf63f6472004-09-27 16:18:50 +00004466 }
4467 }
4468 break;
Chris Lattner0c967662004-09-24 15:21:34 +00004469
Reid Spencer1628cec2006-10-26 06:15:43 +00004470 case Instruction::SDiv:
4471 case Instruction::UDiv:
4472 // Fold: setcc ([us]div X, C1), C2 -> range test
4473 // Fold this div into the comparison, producing a range check.
4474 // Determine, based on the divide type, what the range is being
4475 // checked. If there is an overflow on the low or high side, remember
4476 // it, otherwise compute the range [low, hi) bounding the new value.
4477 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattnera96879a2004-09-29 17:40:11 +00004478 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00004479 // FIXME: If the operand types don't match the type of the divide
4480 // then don't attempt this transform. The code below doesn't have the
4481 // logic to deal with a signed divide and an unsigned compare (and
4482 // vice versa). This is because (x /s C1) <s C2 produces different
4483 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
4484 // (x /u C1) <u C2. Simply casting the operands and result won't
4485 // work. :( The if statement below tests that condition and bails
4486 // if it finds it.
4487 const Type* DivRHSTy = DivRHS->getType();
4488 unsigned DivOpCode = LHSI->getOpcode();
4489 if (I.isEquality() &&
4490 ((DivOpCode == Instruction::SDiv && DivRHSTy->isUnsigned()) ||
4491 (DivOpCode == Instruction::UDiv && DivRHSTy->isSigned())))
4492 break;
4493
4494 // Initialize the variables that will indicate the nature of the
4495 // range check.
4496 bool LoOverflow = false, HiOverflow = false;
Chris Lattnera96879a2004-09-29 17:40:11 +00004497 ConstantInt *LoBound = 0, *HiBound = 0;
4498
Reid Spencer1628cec2006-10-26 06:15:43 +00004499 // Compute Prod = CI * DivRHS. We are essentially solving an equation
4500 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
4501 // C2 (CI). By solving for X we can turn this into a range check
4502 // instead of computing a divide.
4503 ConstantInt *Prod =
4504 cast<ConstantInt>(ConstantExpr::getMul(CI, DivRHS));
Chris Lattnera96879a2004-09-29 17:40:11 +00004505
Reid Spencer1628cec2006-10-26 06:15:43 +00004506 // Determine if the product overflows by seeing if the product is
4507 // not equal to the divide. Make sure we do the same kind of divide
4508 // as in the LHS instruction that we're folding.
4509 bool ProdOV = !DivRHS->isNullValue() &&
4510 (DivOpCode == Instruction::SDiv ?
4511 ConstantExpr::getSDiv(Prod, DivRHS) :
4512 ConstantExpr::getUDiv(Prod, DivRHS)) != CI;
4513
4514 // Get the SetCC opcode
Chris Lattner6a9fdfa2004-10-11 19:40:04 +00004515 Instruction::BinaryOps Opcode = I.getOpcode();
4516
Reid Spencer1628cec2006-10-26 06:15:43 +00004517 if (DivRHS->isNullValue()) {
4518 // Don't hack on divide by zeros!
4519 } else if (DivOpCode == Instruction::UDiv) { // udiv
Chris Lattnera96879a2004-09-29 17:40:11 +00004520 LoBound = Prod;
4521 LoOverflow = ProdOV;
4522 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
Reid Spencer1628cec2006-10-26 06:15:43 +00004523 } else if (isPositive(DivRHS)) { // Divisor is > 0.
Chris Lattnera96879a2004-09-29 17:40:11 +00004524 if (CI->isNullValue()) { // (X / pos) op 0
4525 // Can't overflow.
4526 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
4527 HiBound = DivRHS;
4528 } else if (isPositive(CI)) { // (X / pos) op pos
4529 LoBound = Prod;
4530 LoOverflow = ProdOV;
4531 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
4532 } else { // (X / pos) op neg
4533 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
4534 LoOverflow = AddWithOverflow(LoBound, Prod,
4535 cast<ConstantInt>(DivRHSH));
4536 HiBound = Prod;
4537 HiOverflow = ProdOV;
4538 }
Reid Spencer1628cec2006-10-26 06:15:43 +00004539 } else { // Divisor is < 0.
Chris Lattnera96879a2004-09-29 17:40:11 +00004540 if (CI->isNullValue()) { // (X / neg) op 0
4541 LoBound = AddOne(DivRHS);
4542 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner56625032005-06-17 02:05:55 +00004543 if (HiBound == DivRHS)
Reid Spencer1628cec2006-10-26 06:15:43 +00004544 LoBound = 0; // - INTMIN = INTMIN
Chris Lattnera96879a2004-09-29 17:40:11 +00004545 } else if (isPositive(CI)) { // (X / neg) op pos
4546 HiOverflow = LoOverflow = ProdOV;
4547 if (!LoOverflow)
4548 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
4549 HiBound = AddOne(Prod);
4550 } else { // (X / neg) op neg
4551 LoBound = Prod;
4552 LoOverflow = HiOverflow = ProdOV;
4553 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
4554 }
Chris Lattner340a05f2004-10-08 19:15:44 +00004555
Chris Lattner6a9fdfa2004-10-11 19:40:04 +00004556 // Dividing by a negate swaps the condition.
4557 Opcode = SetCondInst::getSwappedCondition(Opcode);
Chris Lattnera96879a2004-09-29 17:40:11 +00004558 }
4559
4560 if (LoBound) {
4561 Value *X = LHSI->getOperand(0);
Chris Lattner6a9fdfa2004-10-11 19:40:04 +00004562 switch (Opcode) {
Chris Lattnera96879a2004-09-29 17:40:11 +00004563 default: assert(0 && "Unhandled setcc opcode!");
4564 case Instruction::SetEQ:
4565 if (LoOverflow && HiOverflow)
Chris Lattner47811b72006-09-28 23:35:22 +00004566 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattnera96879a2004-09-29 17:40:11 +00004567 else if (HiOverflow)
4568 return new SetCondInst(Instruction::SetGE, X, LoBound);
4569 else if (LoOverflow)
4570 return new SetCondInst(Instruction::SetLT, X, HiBound);
4571 else
4572 return InsertRangeTest(X, LoBound, HiBound, true, I);
4573 case Instruction::SetNE:
4574 if (LoOverflow && HiOverflow)
Chris Lattner47811b72006-09-28 23:35:22 +00004575 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattnera96879a2004-09-29 17:40:11 +00004576 else if (HiOverflow)
4577 return new SetCondInst(Instruction::SetLT, X, LoBound);
4578 else if (LoOverflow)
4579 return new SetCondInst(Instruction::SetGE, X, HiBound);
4580 else
4581 return InsertRangeTest(X, LoBound, HiBound, false, I);
4582 case Instruction::SetLT:
4583 if (LoOverflow)
Chris Lattner47811b72006-09-28 23:35:22 +00004584 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattnera96879a2004-09-29 17:40:11 +00004585 return new SetCondInst(Instruction::SetLT, X, LoBound);
4586 case Instruction::SetGT:
4587 if (HiOverflow)
Chris Lattner47811b72006-09-28 23:35:22 +00004588 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattnera96879a2004-09-29 17:40:11 +00004589 return new SetCondInst(Instruction::SetGE, X, HiBound);
4590 }
4591 }
4592 }
4593 break;
Chris Lattner648e3bc2004-09-23 21:52:49 +00004594 }
Misha Brukmanfd939082005-04-21 23:48:37 +00004595
Chris Lattnerbc5d4142003-07-23 17:02:11 +00004596 // Simplify seteq and setne instructions...
Chris Lattner65b72ba2006-09-18 04:22:48 +00004597 if (I.isEquality()) {
Chris Lattnerbc5d4142003-07-23 17:02:11 +00004598 bool isSetNE = I.getOpcode() == Instruction::SetNE;
4599
Reid Spencerb83eb642006-10-20 07:07:24 +00004600 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
4601 // the second operand is a constant, simplify a bit.
Chris Lattner934754b2003-08-13 05:33:12 +00004602 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
4603 switch (BO->getOpcode()) {
Reid Spencerb83eb642006-10-20 07:07:24 +00004604 case Instruction::SRem:
4605 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
4606 if (CI->isNullValue() && isa<ConstantInt>(BO->getOperand(1)) &&
4607 BO->hasOneUse()) {
4608 int64_t V = cast<ConstantInt>(BO->getOperand(1))->getSExtValue();
4609 if (V > 1 && isPowerOf2_64(V)) {
Reid Spencer0a783f72006-11-02 01:53:59 +00004610 Value *NewRem = InsertNewInstBefore(BinaryOperator::createURem(
4611 BO->getOperand(0), BO->getOperand(1), BO->getName()), I);
Chris Lattner3571b722004-07-06 07:38:18 +00004612 return BinaryOperator::create(I.getOpcode(), NewRem,
Reid Spencer0a783f72006-11-02 01:53:59 +00004613 Constant::getNullValue(BO->getType()));
Chris Lattner3571b722004-07-06 07:38:18 +00004614 }
Chris Lattnerbcd7db52005-08-02 19:16:58 +00004615 }
Misha Brukmanfd939082005-04-21 23:48:37 +00004616 break;
Chris Lattner934754b2003-08-13 05:33:12 +00004617 case Instruction::Add:
Chris Lattner15d58b62004-06-27 22:51:36 +00004618 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
4619 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattner3d834bf2004-09-21 21:35:23 +00004620 if (BO->hasOneUse())
4621 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
4622 ConstantExpr::getSub(CI, BOp1C));
Chris Lattner15d58b62004-06-27 22:51:36 +00004623 } else if (CI->isNullValue()) {
Chris Lattner934754b2003-08-13 05:33:12 +00004624 // Replace ((add A, B) != 0) with (A != -B) if A or B is
4625 // efficiently invertible, or if the add has just this one use.
4626 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Misha Brukmanfd939082005-04-21 23:48:37 +00004627
Chris Lattner934754b2003-08-13 05:33:12 +00004628 if (Value *NegVal = dyn_castNegVal(BOp1))
4629 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
4630 else if (Value *NegVal = dyn_castNegVal(BOp0))
4631 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
Chris Lattnerfd059242003-10-15 16:48:29 +00004632 else if (BO->hasOneUse()) {
Chris Lattner934754b2003-08-13 05:33:12 +00004633 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
4634 BO->setName("");
4635 InsertNewInstBefore(Neg, I);
4636 return new SetCondInst(I.getOpcode(), BOp0, Neg);
4637 }
4638 }
4639 break;
4640 case Instruction::Xor:
4641 // For the xor case, we can xor two constants together, eliminating
4642 // the explicit xor.
4643 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
4644 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
Chris Lattner48595f12004-06-10 02:07:29 +00004645 ConstantExpr::getXor(CI, BOC));
Chris Lattner934754b2003-08-13 05:33:12 +00004646
4647 // FALLTHROUGH
4648 case Instruction::Sub:
4649 // Replace (([sub|xor] A, B) != 0) with (A != B)
4650 if (CI->isNullValue())
4651 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
4652 BO->getOperand(1));
4653 break;
4654
4655 case Instruction::Or:
4656 // If bits are being or'd in that are not present in the constant we
4657 // are comparing against, then the comparison could never succeed!
Chris Lattner7c4049c2004-01-12 19:35:11 +00004658 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattner448c3232004-06-10 02:12:35 +00004659 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattner48595f12004-06-10 02:07:29 +00004660 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Chris Lattnerbc5d4142003-07-23 17:02:11 +00004661 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattner7c4049c2004-01-12 19:35:11 +00004662 }
Chris Lattner934754b2003-08-13 05:33:12 +00004663 break;
4664
4665 case Instruction::And:
4666 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerbc5d4142003-07-23 17:02:11 +00004667 // If bits are being compared against that are and'd out, then the
4668 // comparison can never succeed!
Chris Lattner448c3232004-06-10 02:12:35 +00004669 if (!ConstantExpr::getAnd(CI,
4670 ConstantExpr::getNot(BOC))->isNullValue())
Chris Lattnerbc5d4142003-07-23 17:02:11 +00004671 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattner934754b2003-08-13 05:33:12 +00004672
Chris Lattner457dd822004-06-09 07:59:58 +00004673 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattner3285a6f2004-06-10 02:33:20 +00004674 if (CI == BOC && isOneBitSet(CI))
Chris Lattner457dd822004-06-09 07:59:58 +00004675 return new SetCondInst(isSetNE ? Instruction::SetEQ :
4676 Instruction::SetNE, Op0,
4677 Constant::getNullValue(CI->getType()));
Chris Lattner457dd822004-06-09 07:59:58 +00004678
Chris Lattner934754b2003-08-13 05:33:12 +00004679 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
4680 // to be a signed value as appropriate.
4681 if (isSignBit(BOC)) {
4682 Value *X = BO->getOperand(0);
4683 // If 'X' is not signed, insert a cast now...
4684 if (!BOC->getType()->isSigned()) {
Chris Lattner5dd04022004-06-17 18:16:02 +00004685 const Type *DestTy = BOC->getType()->getSignedVersion();
Chris Lattner83c4ec02004-09-27 19:29:18 +00004686 X = InsertCastBefore(X, DestTy, I);
Chris Lattner934754b2003-08-13 05:33:12 +00004687 }
4688 return new SetCondInst(isSetNE ? Instruction::SetLT :
4689 Instruction::SetGE, X,
4690 Constant::getNullValue(X->getType()));
4691 }
Misha Brukmanfd939082005-04-21 23:48:37 +00004692
Chris Lattner83c4ec02004-09-27 19:29:18 +00004693 // ((X & ~7) == 0) --> X < 8
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00004694 if (CI->isNullValue() && isHighOnes(BOC)) {
4695 Value *X = BO->getOperand(0);
Chris Lattner83c4ec02004-09-27 19:29:18 +00004696 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00004697
4698 // If 'X' is signed, insert a cast now.
Chris Lattner83c4ec02004-09-27 19:29:18 +00004699 if (NegX->getType()->isSigned()) {
4700 const Type *DestTy = NegX->getType()->getUnsignedVersion();
4701 X = InsertCastBefore(X, DestTy, I);
4702 NegX = ConstantExpr::getCast(NegX, DestTy);
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00004703 }
4704
4705 return new SetCondInst(isSetNE ? Instruction::SetGE :
Chris Lattner83c4ec02004-09-27 19:29:18 +00004706 Instruction::SetLT, X, NegX);
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00004707 }
4708
Chris Lattnerbc5d4142003-07-23 17:02:11 +00004709 }
Chris Lattner934754b2003-08-13 05:33:12 +00004710 default: break;
4711 }
4712 }
Chris Lattnerc5943fb2004-02-23 07:16:20 +00004713 } else { // Not a SetEQ/SetNE
Misha Brukmanfd939082005-04-21 23:48:37 +00004714 // If the LHS is a cast from an integral value of the same size,
Chris Lattnerc5943fb2004-02-23 07:16:20 +00004715 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
4716 Value *CastOp = Cast->getOperand(0);
4717 const Type *SrcTy = CastOp->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00004718 unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
Chris Lattnerc5943fb2004-02-23 07:16:20 +00004719 if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
Chris Lattner484d3cf2005-04-24 06:59:08 +00004720 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
Misha Brukmanfd939082005-04-21 23:48:37 +00004721 assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) &&
Chris Lattnerc5943fb2004-02-23 07:16:20 +00004722 "Source and destination signednesses should differ!");
4723 if (Cast->getType()->isSigned()) {
4724 // If this is a signed comparison, check for comparisons in the
4725 // vicinity of zero.
4726 if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
4727 // X < 0 => x > 127
Chris Lattner48595f12004-06-10 02:07:29 +00004728 return BinaryOperator::createSetGT(CastOp,
Reid Spencerb83eb642006-10-20 07:07:24 +00004729 ConstantInt::get(SrcTy, (1ULL << (SrcTySize-1))-1));
Chris Lattnerc5943fb2004-02-23 07:16:20 +00004730 else if (I.getOpcode() == Instruction::SetGT &&
Reid Spencerb83eb642006-10-20 07:07:24 +00004731 cast<ConstantInt>(CI)->getSExtValue() == -1)
Chris Lattnerc5943fb2004-02-23 07:16:20 +00004732 // X > -1 => x < 128
Chris Lattner48595f12004-06-10 02:07:29 +00004733 return BinaryOperator::createSetLT(CastOp,
Reid Spencerb83eb642006-10-20 07:07:24 +00004734 ConstantInt::get(SrcTy, 1ULL << (SrcTySize-1)));
Chris Lattnerc5943fb2004-02-23 07:16:20 +00004735 } else {
Reid Spencerb83eb642006-10-20 07:07:24 +00004736 ConstantInt *CUI = cast<ConstantInt>(CI);
Chris Lattnerc5943fb2004-02-23 07:16:20 +00004737 if (I.getOpcode() == Instruction::SetLT &&
Reid Spencerb83eb642006-10-20 07:07:24 +00004738 CUI->getZExtValue() == 1ULL << (SrcTySize-1))
Chris Lattnerc5943fb2004-02-23 07:16:20 +00004739 // X < 128 => X > -1
Chris Lattner48595f12004-06-10 02:07:29 +00004740 return BinaryOperator::createSetGT(CastOp,
Reid Spencerb83eb642006-10-20 07:07:24 +00004741 ConstantInt::get(SrcTy, -1));
Chris Lattnerc5943fb2004-02-23 07:16:20 +00004742 else if (I.getOpcode() == Instruction::SetGT &&
Reid Spencerb83eb642006-10-20 07:07:24 +00004743 CUI->getZExtValue() == (1ULL << (SrcTySize-1))-1)
Chris Lattnerc5943fb2004-02-23 07:16:20 +00004744 // X > 127 => X < 0
Chris Lattner48595f12004-06-10 02:07:29 +00004745 return BinaryOperator::createSetLT(CastOp,
4746 Constant::getNullValue(SrcTy));
Chris Lattnerc5943fb2004-02-23 07:16:20 +00004747 }
4748 }
4749 }
Chris Lattner40f5d702003-06-04 05:10:11 +00004750 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00004751 }
4752
Chris Lattner6970b662005-04-23 15:31:55 +00004753 // Handle setcc with constant RHS's that can be integer, FP or pointer.
4754 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4755 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4756 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00004757 case Instruction::GetElementPtr:
4758 if (RHSC->isNullValue()) {
4759 // Transform setcc GEP P, int 0, int 0, int 0, null -> setcc P, null
4760 bool isAllZeros = true;
4761 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
4762 if (!isa<Constant>(LHSI->getOperand(i)) ||
4763 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
4764 isAllZeros = false;
4765 break;
4766 }
4767 if (isAllZeros)
4768 return new SetCondInst(I.getOpcode(), LHSI->getOperand(0),
4769 Constant::getNullValue(LHSI->getOperand(0)->getType()));
4770 }
4771 break;
4772
Chris Lattner6970b662005-04-23 15:31:55 +00004773 case Instruction::PHI:
4774 if (Instruction *NV = FoldOpIntoPhi(I))
4775 return NV;
4776 break;
4777 case Instruction::Select:
4778 // If either operand of the select is a constant, we can fold the
4779 // comparison into the select arms, which will cause one to be
4780 // constant folded and the select turned into a bitwise or.
4781 Value *Op1 = 0, *Op2 = 0;
4782 if (LHSI->hasOneUse()) {
4783 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4784 // Fold the known value into the constant operand.
4785 Op1 = ConstantExpr::get(I.getOpcode(), C, RHSC);
4786 // Insert a new SetCC of the other select operand.
4787 Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
4788 LHSI->getOperand(2), RHSC,
4789 I.getName()), I);
4790 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4791 // Fold the known value into the constant operand.
4792 Op2 = ConstantExpr::get(I.getOpcode(), C, RHSC);
4793 // Insert a new SetCC of the other select operand.
4794 Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
4795 LHSI->getOperand(1), RHSC,
4796 I.getName()), I);
4797 }
4798 }
Jeff Cohen9d809302005-04-23 21:38:35 +00004799
Chris Lattner6970b662005-04-23 15:31:55 +00004800 if (Op1)
4801 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4802 break;
4803 }
4804 }
4805
Chris Lattner574da9b2005-01-13 20:14:25 +00004806 // If we can optimize a 'setcc GEP, P' or 'setcc P, GEP', do so now.
4807 if (User *GEP = dyn_castGetElementPtr(Op0))
4808 if (Instruction *NI = FoldGEPSetCC(GEP, Op1, I.getOpcode(), I))
4809 return NI;
4810 if (User *GEP = dyn_castGetElementPtr(Op1))
4811 if (Instruction *NI = FoldGEPSetCC(GEP, Op0,
4812 SetCondInst::getSwappedCondition(I.getOpcode()), I))
4813 return NI;
4814
Chris Lattnerde90b762003-11-03 04:25:02 +00004815 // Test to see if the operands of the setcc are casted versions of other
4816 // values. If the cast can be stripped off both arguments, we do so now.
Chris Lattner68708052003-11-03 05:17:03 +00004817 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4818 Value *CastOp0 = CI->getOperand(0);
4819 if (CastOp0->getType()->isLosslesslyConvertibleTo(CI->getType()) &&
Chris Lattner65b72ba2006-09-18 04:22:48 +00004820 (isa<Constant>(Op1) || isa<CastInst>(Op1)) && I.isEquality()) {
Chris Lattnerde90b762003-11-03 04:25:02 +00004821 // We keep moving the cast from the left operand over to the right
4822 // operand, where it can often be eliminated completely.
Chris Lattner68708052003-11-03 05:17:03 +00004823 Op0 = CastOp0;
Misha Brukmanfd939082005-04-21 23:48:37 +00004824
Chris Lattnerde90b762003-11-03 04:25:02 +00004825 // If operand #1 is a cast instruction, see if we can eliminate it as
4826 // well.
Chris Lattner68708052003-11-03 05:17:03 +00004827 if (CastInst *CI2 = dyn_cast<CastInst>(Op1))
4828 if (CI2->getOperand(0)->getType()->isLosslesslyConvertibleTo(
Chris Lattnerde90b762003-11-03 04:25:02 +00004829 Op0->getType()))
Chris Lattner68708052003-11-03 05:17:03 +00004830 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00004831
Chris Lattnerde90b762003-11-03 04:25:02 +00004832 // If Op1 is a constant, we can fold the cast into the constant.
4833 if (Op1->getType() != Op0->getType())
4834 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
4835 Op1 = ConstantExpr::getCast(Op1C, Op0->getType());
4836 } else {
4837 // Otherwise, cast the RHS right before the setcc
Reid Spencer811b0cb2006-10-26 19:19:06 +00004838 Op1 = InsertCastBefore(Op1, Op0->getType(), I);
Chris Lattnerde90b762003-11-03 04:25:02 +00004839 }
4840 return BinaryOperator::create(I.getOpcode(), Op0, Op1);
4841 }
4842
Chris Lattner68708052003-11-03 05:17:03 +00004843 // Handle the special case of: setcc (cast bool to X), <cst>
4844 // This comes up when you have code like
4845 // int X = A < B;
4846 // if (X) ...
4847 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00004848 // with a constant or another cast from the same type.
4849 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
4850 if (Instruction *R = visitSetCondInstWithCastAndCast(I))
4851 return R;
Chris Lattner68708052003-11-03 05:17:03 +00004852 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00004853
Chris Lattner65b72ba2006-09-18 04:22:48 +00004854 if (I.isEquality()) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00004855 Value *A, *B;
4856 if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
4857 (A == Op1 || B == Op1)) {
4858 // (A^B) == A -> B == 0
4859 Value *OtherVal = A == Op1 ? B : A;
4860 return BinaryOperator::create(I.getOpcode(), OtherVal,
4861 Constant::getNullValue(A->getType()));
4862 } else if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
4863 (A == Op0 || B == Op0)) {
4864 // A == (A^B) -> B == 0
4865 Value *OtherVal = A == Op0 ? B : A;
4866 return BinaryOperator::create(I.getOpcode(), OtherVal,
4867 Constant::getNullValue(A->getType()));
4868 } else if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
4869 // (A-B) == A -> B == 0
4870 return BinaryOperator::create(I.getOpcode(), B,
4871 Constant::getNullValue(B->getType()));
4872 } else if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
4873 // A == (A-B) -> B == 0
4874 return BinaryOperator::create(I.getOpcode(), B,
4875 Constant::getNullValue(B->getType()));
4876 }
4877 }
Chris Lattner7e708292002-06-25 16:13:24 +00004878 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004879}
4880
Chris Lattner484d3cf2005-04-24 06:59:08 +00004881// visitSetCondInstWithCastAndCast - Handle setcond (cast x to y), (cast/cst).
4882// We only handle extending casts so far.
4883//
4884Instruction *InstCombiner::visitSetCondInstWithCastAndCast(SetCondInst &SCI) {
4885 Value *LHSCIOp = cast<CastInst>(SCI.getOperand(0))->getOperand(0);
4886 const Type *SrcTy = LHSCIOp->getType();
4887 const Type *DestTy = SCI.getOperand(0)->getType();
4888 Value *RHSCIOp;
4889
4890 if (!DestTy->isIntegral() || !SrcTy->isIntegral())
Chris Lattnerb352fa52005-01-17 03:20:02 +00004891 return 0;
4892
Chris Lattner484d3cf2005-04-24 06:59:08 +00004893 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
4894 unsigned DestBits = DestTy->getPrimitiveSizeInBits();
4895 if (SrcBits >= DestBits) return 0; // Only handle extending cast.
4896
4897 // Is this a sign or zero extension?
4898 bool isSignSrc = SrcTy->isSigned();
4899 bool isSignDest = DestTy->isSigned();
4900
4901 if (CastInst *CI = dyn_cast<CastInst>(SCI.getOperand(1))) {
4902 // Not an extension from the same type?
4903 RHSCIOp = CI->getOperand(0);
4904 if (RHSCIOp->getType() != LHSCIOp->getType()) return 0;
4905 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(SCI.getOperand(1))) {
4906 // Compute the constant that would happen if we truncated to SrcTy then
4907 // reextended to DestTy.
4908 Constant *Res = ConstantExpr::getCast(CI, SrcTy);
4909
4910 if (ConstantExpr::getCast(Res, DestTy) == CI) {
Devang Patel6ce890b2006-10-19 18:54:08 +00004911 // Make sure that src sign and dest sign match. For example,
4912 //
4913 // %A = cast short %X to uint
4914 // %B = setgt uint %A, 1330
4915 //
Devang Pateldf308fa2006-10-19 19:21:36 +00004916 // It is incorrect to transform this into
Devang Patel6ce890b2006-10-19 18:54:08 +00004917 //
4918 // %B = setgt short %X, 1330
4919 //
4920 // because %A may have negative value.
Devang Patel002e4992006-10-19 20:59:13 +00004921 // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
4922 // OR operation is EQ/NE.
4923 if (isSignSrc == isSignDest || SrcTy == Type::BoolTy || SCI.isEquality())
Devang Patel6ce890b2006-10-19 18:54:08 +00004924 RHSCIOp = Res;
4925 else
4926 return 0;
Chris Lattner484d3cf2005-04-24 06:59:08 +00004927 } else {
4928 // If the value cannot be represented in the shorter type, we cannot emit
4929 // a simple comparison.
4930 if (SCI.getOpcode() == Instruction::SetEQ)
Chris Lattner47811b72006-09-28 23:35:22 +00004931 return ReplaceInstUsesWith(SCI, ConstantBool::getFalse());
Chris Lattner484d3cf2005-04-24 06:59:08 +00004932 if (SCI.getOpcode() == Instruction::SetNE)
Chris Lattner47811b72006-09-28 23:35:22 +00004933 return ReplaceInstUsesWith(SCI, ConstantBool::getTrue());
Chris Lattner484d3cf2005-04-24 06:59:08 +00004934
Chris Lattner484d3cf2005-04-24 06:59:08 +00004935 // Evaluate the comparison for LT.
4936 Value *Result;
4937 if (DestTy->isSigned()) {
4938 // We're performing a signed comparison.
4939 if (isSignSrc) {
4940 // Signed extend and signed comparison.
Reid Spencerb83eb642006-10-20 07:07:24 +00004941 if (cast<ConstantInt>(CI)->getSExtValue() < 0)// X < (small) --> false
Chris Lattner47811b72006-09-28 23:35:22 +00004942 Result = ConstantBool::getFalse();
Chris Lattner484d3cf2005-04-24 06:59:08 +00004943 else
Reid Spencerb83eb642006-10-20 07:07:24 +00004944 Result = ConstantBool::getTrue(); // X < (large) --> true
Chris Lattner484d3cf2005-04-24 06:59:08 +00004945 } else {
4946 // Unsigned extend and signed comparison.
Reid Spencerb83eb642006-10-20 07:07:24 +00004947 if (cast<ConstantInt>(CI)->getSExtValue() < 0)
Chris Lattner47811b72006-09-28 23:35:22 +00004948 Result = ConstantBool::getFalse();
Chris Lattner484d3cf2005-04-24 06:59:08 +00004949 else
Chris Lattner47811b72006-09-28 23:35:22 +00004950 Result = ConstantBool::getTrue();
Chris Lattner484d3cf2005-04-24 06:59:08 +00004951 }
4952 } else {
4953 // We're performing an unsigned comparison.
4954 if (!isSignSrc) {
4955 // Unsigned extend & compare -> always true.
Chris Lattner47811b72006-09-28 23:35:22 +00004956 Result = ConstantBool::getTrue();
Chris Lattner484d3cf2005-04-24 06:59:08 +00004957 } else {
4958 // We're performing an unsigned comp with a sign extended value.
4959 // This is true if the input is >= 0. [aka >s -1]
4960 Constant *NegOne = ConstantIntegral::getAllOnesValue(SrcTy);
4961 Result = InsertNewInstBefore(BinaryOperator::createSetGT(LHSCIOp,
4962 NegOne, SCI.getName()), SCI);
4963 }
Reid Spencer6731d5c2004-11-28 21:31:15 +00004964 }
Chris Lattnerb352fa52005-01-17 03:20:02 +00004965
Jeff Cohen00b168892005-07-27 06:12:32 +00004966 // Finally, return the value computed.
Chris Lattner484d3cf2005-04-24 06:59:08 +00004967 if (SCI.getOpcode() == Instruction::SetLT) {
4968 return ReplaceInstUsesWith(SCI, Result);
4969 } else {
4970 assert(SCI.getOpcode()==Instruction::SetGT &&"SetCC should be folded!");
4971 if (Constant *CI = dyn_cast<Constant>(Result))
4972 return ReplaceInstUsesWith(SCI, ConstantExpr::getNot(CI));
4973 else
4974 return BinaryOperator::createNot(Result);
4975 }
Chris Lattnerb352fa52005-01-17 03:20:02 +00004976 }
Chris Lattner484d3cf2005-04-24 06:59:08 +00004977 } else {
4978 return 0;
Reid Spencer6731d5c2004-11-28 21:31:15 +00004979 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00004980
Chris Lattner8d7089e2005-06-16 03:00:08 +00004981 // Okay, just insert a compare of the reduced operands now!
Chris Lattner484d3cf2005-04-24 06:59:08 +00004982 return BinaryOperator::create(SCI.getOpcode(), LHSCIOp, RHSCIOp);
4983}
Chris Lattner3f5b8772002-05-06 16:14:14 +00004984
Chris Lattnerea340052003-03-10 19:16:08 +00004985Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00004986 assert(I.getOperand(1)->getType() == Type::UByteTy);
4987 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdf17af12003-08-12 21:53:41 +00004988 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004989
4990 // shl X, 0 == X and shr X, 0 == X
4991 // shl 0, X == 0 and shr 0, X == 0
4992 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
Chris Lattner233f7dc2002-08-12 21:17:25 +00004993 Op0 == Constant::getNullValue(Op0->getType()))
4994 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00004995
Chris Lattnere87597f2004-10-16 18:11:37 +00004996 if (isa<UndefValue>(Op0)) { // undef >>s X -> undef
4997 if (!isLeftShift && I.getType()->isSigned())
Chris Lattner79a564c2004-10-16 23:28:04 +00004998 return ReplaceInstUsesWith(I, Op0);
Chris Lattnere87597f2004-10-16 18:11:37 +00004999 else // undef << X -> 0 AND undef >>u X -> 0
5000 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5001 }
5002 if (isa<UndefValue>(Op1)) {
Chris Lattnerf9944f12005-07-20 18:49:28 +00005003 if (isLeftShift || I.getType()->isUnsigned())// X << undef, X >>u undef -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00005004 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5005 else
5006 return ReplaceInstUsesWith(I, Op0); // X >>s undef -> X
5007 }
5008
Chris Lattnerdf17af12003-08-12 21:53:41 +00005009 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
5010 if (!isLeftShift)
Reid Spencerb83eb642006-10-20 07:07:24 +00005011 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Chris Lattner87d84292006-10-20 18:20:21 +00005012 if (CSI->isAllOnesValue() && Op0->getType()->isSigned())
Chris Lattnerdf17af12003-08-12 21:53:41 +00005013 return ReplaceInstUsesWith(I, CSI);
5014
Chris Lattner2eefe512004-04-09 19:05:30 +00005015 // Try to fold constant and into select arguments.
5016 if (isa<Constant>(Op0))
5017 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00005018 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00005019 return R;
5020
Chris Lattner120347e2005-05-08 17:34:56 +00005021 // See if we can turn a signed shr into an unsigned shr.
Chris Lattner65b72ba2006-09-18 04:22:48 +00005022 if (I.isArithmeticShift()) {
Chris Lattner3bedbd92006-02-07 07:27:52 +00005023 if (MaskedValueIsZero(Op0,
5024 1ULL << (I.getType()->getPrimitiveSizeInBits()-1))) {
Chris Lattner120347e2005-05-08 17:34:56 +00005025 Value *V = InsertCastBefore(Op0, I.getType()->getUnsignedVersion(), I);
5026 V = InsertNewInstBefore(new ShiftInst(Instruction::Shr, V, Op1,
5027 I.getName()), I);
5028 return new CastInst(V, I.getType());
5029 }
5030 }
Jeff Cohen00b168892005-07-27 06:12:32 +00005031
Reid Spencerb83eb642006-10-20 07:07:24 +00005032 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
5033 if (CUI->getType()->isUnsigned())
5034 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
5035 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00005036 return 0;
5037}
5038
Reid Spencerb83eb642006-10-20 07:07:24 +00005039Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Chris Lattner4d5542c2006-01-06 07:12:35 +00005040 ShiftInst &I) {
5041 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner830ed032006-01-06 07:22:22 +00005042 bool isSignedShift = Op0->getType()->isSigned();
5043 bool isUnsignedShift = !isSignedShift;
Chris Lattner4d5542c2006-01-06 07:12:35 +00005044
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00005045 // See if we can simplify any instructions used by the instruction whose sole
5046 // purpose is to compute bits we don't care about.
5047 uint64_t KnownZero, KnownOne;
5048 if (SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
5049 KnownZero, KnownOne))
5050 return &I;
5051
Chris Lattner4d5542c2006-01-06 07:12:35 +00005052 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
5053 // of a signed value.
5054 //
5055 unsigned TypeBits = Op0->getType()->getPrimitiveSizeInBits();
Reid Spencerb83eb642006-10-20 07:07:24 +00005056 if (Op1->getZExtValue() >= TypeBits) {
Chris Lattner830ed032006-01-06 07:22:22 +00005057 if (isUnsignedShift || isLeftShift)
Chris Lattner4d5542c2006-01-06 07:12:35 +00005058 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
5059 else {
Reid Spencerb83eb642006-10-20 07:07:24 +00005060 I.setOperand(1, ConstantInt::get(Type::UByteTy, TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00005061 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00005062 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00005063 }
5064
5065 // ((X*C1) << C2) == (X * (C1 << C2))
5066 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
5067 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
5068 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
5069 return BinaryOperator::createMul(BO->getOperand(0),
5070 ConstantExpr::getShl(BOOp, Op1));
5071
5072 // Try to fold constant and into select arguments.
5073 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5074 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5075 return R;
5076 if (isa<PHINode>(Op0))
5077 if (Instruction *NV = FoldOpIntoPhi(I))
5078 return NV;
5079
5080 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00005081 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
5082 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
5083 Value *V1, *V2;
5084 ConstantInt *CC;
5085 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00005086 default: break;
5087 case Instruction::Add:
5088 case Instruction::And:
5089 case Instruction::Or:
5090 case Instruction::Xor:
5091 // These operators commute.
5092 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00005093 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
5094 match(Op0BO->getOperand(1),
Chris Lattner4d5542c2006-01-06 07:12:35 +00005095 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Chris Lattner150f12a2005-09-18 06:30:59 +00005096 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner4d5542c2006-01-06 07:12:35 +00005097 Op0BO->getOperand(0), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00005098 Op0BO->getName());
5099 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00005100 Instruction *X =
5101 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
5102 Op0BO->getOperand(1)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00005103 InsertNewInstBefore(X, I); // (X + (Y << C))
5104 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner4d5542c2006-01-06 07:12:35 +00005105 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner150f12a2005-09-18 06:30:59 +00005106 return BinaryOperator::createAnd(X, C2);
5107 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00005108
Chris Lattner150f12a2005-09-18 06:30:59 +00005109 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
5110 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
5111 match(Op0BO->getOperand(1),
5112 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner4d5542c2006-01-06 07:12:35 +00005113 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00005114 cast<BinaryOperator>(Op0BO->getOperand(1))->getOperand(0)->hasOneUse()) {
Chris Lattner150f12a2005-09-18 06:30:59 +00005115 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner4d5542c2006-01-06 07:12:35 +00005116 Op0BO->getOperand(0), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00005117 Op0BO->getName());
5118 InsertNewInstBefore(YS, I); // (Y << C)
5119 Instruction *XM =
Chris Lattner4d5542c2006-01-06 07:12:35 +00005120 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00005121 V1->getName()+".mask");
5122 InsertNewInstBefore(XM, I); // X & (CC << C)
5123
5124 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
5125 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00005126
Chris Lattner150f12a2005-09-18 06:30:59 +00005127 // FALL THROUGH.
Chris Lattner11021cb2005-09-18 05:12:10 +00005128 case Instruction::Sub:
5129 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00005130 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5131 match(Op0BO->getOperand(0),
Chris Lattner4d5542c2006-01-06 07:12:35 +00005132 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Chris Lattner150f12a2005-09-18 06:30:59 +00005133 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner4d5542c2006-01-06 07:12:35 +00005134 Op0BO->getOperand(1), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00005135 Op0BO->getName());
5136 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00005137 Instruction *X =
Chris Lattner13d4ab42006-05-31 21:14:00 +00005138 BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00005139 Op0BO->getOperand(0)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00005140 InsertNewInstBefore(X, I); // (X + (Y << C))
5141 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner4d5542c2006-01-06 07:12:35 +00005142 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner150f12a2005-09-18 06:30:59 +00005143 return BinaryOperator::createAnd(X, C2);
5144 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00005145
Chris Lattner13d4ab42006-05-31 21:14:00 +00005146 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00005147 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5148 match(Op0BO->getOperand(0),
5149 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner4d5542c2006-01-06 07:12:35 +00005150 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00005151 cast<BinaryOperator>(Op0BO->getOperand(0))
5152 ->getOperand(0)->hasOneUse()) {
Chris Lattner150f12a2005-09-18 06:30:59 +00005153 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner4d5542c2006-01-06 07:12:35 +00005154 Op0BO->getOperand(1), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00005155 Op0BO->getName());
5156 InsertNewInstBefore(YS, I); // (Y << C)
5157 Instruction *XM =
Chris Lattner4d5542c2006-01-06 07:12:35 +00005158 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00005159 V1->getName()+".mask");
5160 InsertNewInstBefore(XM, I); // X & (CC << C)
5161
Chris Lattner13d4ab42006-05-31 21:14:00 +00005162 return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00005163 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00005164
Chris Lattner11021cb2005-09-18 05:12:10 +00005165 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00005166 }
5167
5168
5169 // If the operand is an bitwise operator with a constant RHS, and the
5170 // shift is the only use, we can pull it out of the shift.
5171 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
5172 bool isValid = true; // Valid only for And, Or, Xor
5173 bool highBitSet = false; // Transform if high bit of constant set?
5174
5175 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00005176 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00005177 case Instruction::Add:
5178 isValid = isLeftShift;
5179 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00005180 case Instruction::Or:
5181 case Instruction::Xor:
5182 highBitSet = false;
5183 break;
5184 case Instruction::And:
5185 highBitSet = true;
5186 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00005187 }
5188
5189 // If this is a signed shift right, and the high bit is modified
5190 // by the logical operation, do not perform the transformation.
5191 // The highBitSet boolean indicates the value of the high bit of
5192 // the constant which would cause it to be modified for this
5193 // operation.
5194 //
Chris Lattner830ed032006-01-06 07:22:22 +00005195 if (isValid && !isLeftShift && isSignedShift) {
Reid Spencerb83eb642006-10-20 07:07:24 +00005196 uint64_t Val = Op0C->getZExtValue();
Chris Lattner4d5542c2006-01-06 07:12:35 +00005197 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
5198 }
5199
5200 if (isValid) {
5201 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
5202
5203 Instruction *NewShift =
5204 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), Op1,
5205 Op0BO->getName());
5206 Op0BO->setName("");
5207 InsertNewInstBefore(NewShift, I);
5208
5209 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
5210 NewRHS);
5211 }
5212 }
5213 }
5214 }
5215
Chris Lattnerad0124c2006-01-06 07:52:12 +00005216 // Find out if this is a shift of a shift by a constant.
5217 ShiftInst *ShiftOp = 0;
Chris Lattner4d5542c2006-01-06 07:12:35 +00005218 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
Chris Lattnerad0124c2006-01-06 07:52:12 +00005219 ShiftOp = Op0SI;
5220 else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
5221 // If this is a noop-integer case of a shift instruction, use the shift.
5222 if (CI->getOperand(0)->getType()->isInteger() &&
5223 CI->getOperand(0)->getType()->getPrimitiveSizeInBits() ==
5224 CI->getType()->getPrimitiveSizeInBits() &&
5225 isa<ShiftInst>(CI->getOperand(0))) {
5226 ShiftOp = cast<ShiftInst>(CI->getOperand(0));
5227 }
5228 }
5229
Reid Spencerb83eb642006-10-20 07:07:24 +00005230 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Chris Lattnerad0124c2006-01-06 07:52:12 +00005231 // Find the operands and properties of the input shift. Note that the
5232 // signedness of the input shift may differ from the current shift if there
5233 // is a noop cast between the two.
5234 bool isShiftOfLeftShift = ShiftOp->getOpcode() == Instruction::Shl;
5235 bool isShiftOfSignedShift = ShiftOp->getType()->isSigned();
Chris Lattnere8d56c52006-01-07 01:32:28 +00005236 bool isShiftOfUnsignedShift = !isShiftOfSignedShift;
Chris Lattnerad0124c2006-01-06 07:52:12 +00005237
Reid Spencerb83eb642006-10-20 07:07:24 +00005238 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Chris Lattnerad0124c2006-01-06 07:52:12 +00005239
Reid Spencerb83eb642006-10-20 07:07:24 +00005240 unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getZExtValue();
5241 unsigned ShiftAmt2 = (unsigned)Op1->getZExtValue();
Chris Lattnerad0124c2006-01-06 07:52:12 +00005242
5243 // Check for (A << c1) << c2 and (A >> c1) >> c2.
5244 if (isLeftShift == isShiftOfLeftShift) {
5245 // Do not fold these shifts if the first one is signed and the second one
5246 // is unsigned and this is a right shift. Further, don't do any folding
5247 // on them.
5248 if (isShiftOfSignedShift && isUnsignedShift && !isLeftShift)
5249 return 0;
Chris Lattner4d5542c2006-01-06 07:12:35 +00005250
Chris Lattnerad0124c2006-01-06 07:52:12 +00005251 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
5252 if (Amt > Op0->getType()->getPrimitiveSizeInBits())
5253 Amt = Op0->getType()->getPrimitiveSizeInBits();
Chris Lattner4d5542c2006-01-06 07:12:35 +00005254
Chris Lattnerad0124c2006-01-06 07:52:12 +00005255 Value *Op = ShiftOp->getOperand(0);
5256 if (isShiftOfSignedShift != isSignedShift)
5257 Op = InsertNewInstBefore(new CastInst(Op, I.getType(), "tmp"), I);
5258 return new ShiftInst(I.getOpcode(), Op,
Reid Spencerb83eb642006-10-20 07:07:24 +00005259 ConstantInt::get(Type::UByteTy, Amt));
Chris Lattnerad0124c2006-01-06 07:52:12 +00005260 }
5261
5262 // Check for (A << c1) >> c2 or (A >> c1) << c2. If we are dealing with
5263 // signed types, we can only support the (A >> c1) << c2 configuration,
5264 // because it can not turn an arbitrary bit of A into a sign bit.
5265 if (isUnsignedShift || isLeftShift) {
5266 // Calculate bitmask for what gets shifted off the edge.
5267 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
5268 if (isLeftShift)
5269 C = ConstantExpr::getShl(C, ShiftAmt1C);
5270 else
Chris Lattnere8d56c52006-01-07 01:32:28 +00005271 C = ConstantExpr::getUShr(C, ShiftAmt1C);
Chris Lattnerad0124c2006-01-06 07:52:12 +00005272
5273 Value *Op = ShiftOp->getOperand(0);
5274 if (isShiftOfSignedShift != isSignedShift)
Reid Spencer811b0cb2006-10-26 19:19:06 +00005275 Op = InsertCastBefore(Op, I.getType(), I);
Chris Lattnerad0124c2006-01-06 07:52:12 +00005276
5277 Instruction *Mask =
5278 BinaryOperator::createAnd(Op, C, Op->getName()+".mask");
5279 InsertNewInstBefore(Mask, I);
5280
5281 // Figure out what flavor of shift we should use...
Chris Lattnere8d56c52006-01-07 01:32:28 +00005282 if (ShiftAmt1 == ShiftAmt2) {
Chris Lattnerad0124c2006-01-06 07:52:12 +00005283 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
Chris Lattnere8d56c52006-01-07 01:32:28 +00005284 } else if (ShiftAmt1 < ShiftAmt2) {
Chris Lattnerad0124c2006-01-06 07:52:12 +00005285 return new ShiftInst(I.getOpcode(), Mask,
Reid Spencerb83eb642006-10-20 07:07:24 +00005286 ConstantInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
Chris Lattnere8d56c52006-01-07 01:32:28 +00005287 } else if (isShiftOfUnsignedShift || isShiftOfLeftShift) {
5288 if (isShiftOfUnsignedShift && !isShiftOfLeftShift && isSignedShift) {
5289 // Make sure to emit an unsigned shift right, not a signed one.
5290 Mask = InsertNewInstBefore(new CastInst(Mask,
5291 Mask->getType()->getUnsignedVersion(),
5292 Op->getName()), I);
5293 Mask = new ShiftInst(Instruction::Shr, Mask,
Reid Spencerb83eb642006-10-20 07:07:24 +00005294 ConstantInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
Chris Lattnere8d56c52006-01-07 01:32:28 +00005295 InsertNewInstBefore(Mask, I);
5296 return new CastInst(Mask, I.getType());
5297 } else {
5298 return new ShiftInst(ShiftOp->getOpcode(), Mask,
Reid Spencerb83eb642006-10-20 07:07:24 +00005299 ConstantInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
Chris Lattnere8d56c52006-01-07 01:32:28 +00005300 }
5301 } else {
5302 // (X >>s C1) << C2 where C1 > C2 === (X >>s (C1-C2)) & mask
Reid Spencer811b0cb2006-10-26 19:19:06 +00005303 Op = InsertCastBefore(Mask, I.getType()->getSignedVersion(), I);
Chris Lattnere8d56c52006-01-07 01:32:28 +00005304 Instruction *Shift =
5305 new ShiftInst(ShiftOp->getOpcode(), Op,
Reid Spencerb83eb642006-10-20 07:07:24 +00005306 ConstantInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
Chris Lattnere8d56c52006-01-07 01:32:28 +00005307 InsertNewInstBefore(Shift, I);
5308
5309 C = ConstantIntegral::getAllOnesValue(Shift->getType());
5310 C = ConstantExpr::getShl(C, Op1);
5311 Mask = BinaryOperator::createAnd(Shift, C, Op->getName()+".mask");
5312 InsertNewInstBefore(Mask, I);
5313 return new CastInst(Mask, I.getType());
Chris Lattnerad0124c2006-01-06 07:52:12 +00005314 }
5315 } else {
Chris Lattnere8d56c52006-01-07 01:32:28 +00005316 // We can handle signed (X << C1) >>s C2 if it's a sign extend. In
Chris Lattnerad0124c2006-01-06 07:52:12 +00005317 // this case, C1 == C2 and C1 is 8, 16, or 32.
5318 if (ShiftAmt1 == ShiftAmt2) {
5319 const Type *SExtType = 0;
Chris Lattner94046b42006-04-28 22:21:41 +00005320 switch (Op0->getType()->getPrimitiveSizeInBits() - ShiftAmt1) {
Chris Lattnerad0124c2006-01-06 07:52:12 +00005321 case 8 : SExtType = Type::SByteTy; break;
5322 case 16: SExtType = Type::ShortTy; break;
5323 case 32: SExtType = Type::IntTy; break;
5324 }
5325
5326 if (SExtType) {
5327 Instruction *NewTrunc = new CastInst(ShiftOp->getOperand(0),
5328 SExtType, "sext");
5329 InsertNewInstBefore(NewTrunc, I);
5330 return new CastInst(NewTrunc, I.getType());
Chris Lattnerdf17af12003-08-12 21:53:41 +00005331 }
Chris Lattner11021cb2005-09-18 05:12:10 +00005332 }
Chris Lattner6e7ba452005-01-01 16:22:27 +00005333 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00005334 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00005335 return 0;
5336}
5337
Chris Lattnera1be5662002-05-02 17:06:02 +00005338
Chris Lattnercfd65102005-10-29 04:36:15 +00005339/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
5340/// expression. If so, decompose it, returning some value X, such that Val is
5341/// X*Scale+Offset.
5342///
5343static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
5344 unsigned &Offset) {
5345 assert(Val->getType() == Type::UIntTy && "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00005346 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
5347 if (CI->getType()->isUnsigned()) {
5348 Offset = CI->getZExtValue();
5349 Scale = 1;
5350 return ConstantInt::get(Type::UIntTy, 0);
5351 }
Chris Lattnercfd65102005-10-29 04:36:15 +00005352 } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
5353 if (I->getNumOperands() == 2) {
Reid Spencerb83eb642006-10-20 07:07:24 +00005354 if (ConstantInt *CUI = dyn_cast<ConstantInt>(I->getOperand(1))) {
5355 if (CUI->getType()->isUnsigned()) {
5356 if (I->getOpcode() == Instruction::Shl) {
5357 // This is a value scaled by '1 << the shift amt'.
5358 Scale = 1U << CUI->getZExtValue();
5359 Offset = 0;
5360 return I->getOperand(0);
5361 } else if (I->getOpcode() == Instruction::Mul) {
5362 // This value is scaled by 'CUI'.
5363 Scale = CUI->getZExtValue();
5364 Offset = 0;
5365 return I->getOperand(0);
5366 } else if (I->getOpcode() == Instruction::Add) {
5367 // We have X+C. Check to see if we really have (X*C2)+C1,
5368 // where C1 is divisible by C2.
5369 unsigned SubScale;
5370 Value *SubVal =
5371 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
5372 Offset += CUI->getZExtValue();
5373 if (SubScale > 1 && (Offset % SubScale == 0)) {
5374 Scale = SubScale;
5375 return SubVal;
5376 }
Chris Lattnercfd65102005-10-29 04:36:15 +00005377 }
5378 }
5379 }
5380 }
5381 }
5382
5383 // Otherwise, we can't look past this.
5384 Scale = 1;
5385 Offset = 0;
5386 return Val;
5387}
5388
5389
Chris Lattnerb3f83972005-10-24 06:03:58 +00005390/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
5391/// try to eliminate the cast by moving the type information into the alloc.
5392Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
5393 AllocationInst &AI) {
5394 const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
Chris Lattner0ddac2a2005-10-27 05:53:56 +00005395 if (!PTy) return 0; // Not casting the allocation to a pointer type.
Chris Lattnerb3f83972005-10-24 06:03:58 +00005396
Chris Lattnerb53c2382005-10-24 06:22:12 +00005397 // Remove any uses of AI that are dead.
5398 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
5399 std::vector<Instruction*> DeadUsers;
5400 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
5401 Instruction *User = cast<Instruction>(*UI++);
5402 if (isInstructionTriviallyDead(User)) {
5403 while (UI != E && *UI == User)
5404 ++UI; // If this instruction uses AI more than once, don't break UI.
5405
5406 // Add operands to the worklist.
5407 AddUsesToWorkList(*User);
5408 ++NumDeadInst;
5409 DEBUG(std::cerr << "IC: DCE: " << *User);
5410
5411 User->eraseFromParent();
5412 removeFromWorkList(User);
5413 }
5414 }
5415
Chris Lattnerb3f83972005-10-24 06:03:58 +00005416 // Get the type really allocated and the type casted to.
5417 const Type *AllocElTy = AI.getAllocatedType();
5418 const Type *CastElTy = PTy->getElementType();
5419 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00005420
Chris Lattnere831b9a2006-10-01 19:40:58 +00005421 unsigned AllocElTyAlign = TD->getTypeAlignment(AllocElTy);
5422 unsigned CastElTyAlign = TD->getTypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00005423 if (CastElTyAlign < AllocElTyAlign) return 0;
5424
Chris Lattner39387a52005-10-24 06:35:18 +00005425 // If the allocation has multiple uses, only promote it if we are strictly
5426 // increasing the alignment of the resultant allocation. If we keep it the
5427 // same, we open the door to infinite loops of various kinds.
5428 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
5429
Chris Lattnerb3f83972005-10-24 06:03:58 +00005430 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
5431 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00005432 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00005433
Chris Lattner455fcc82005-10-29 03:19:53 +00005434 // See if we can satisfy the modulus by pulling a scale out of the array
5435 // size argument.
Chris Lattnercfd65102005-10-29 04:36:15 +00005436 unsigned ArraySizeScale, ArrayOffset;
5437 Value *NumElements = // See if the array size is a decomposable linear expr.
5438 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
5439
Chris Lattner455fcc82005-10-29 03:19:53 +00005440 // If we can now satisfy the modulus, by using a non-1 scale, we really can
5441 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00005442 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
5443 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00005444
Chris Lattner455fcc82005-10-29 03:19:53 +00005445 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
5446 Value *Amt = 0;
5447 if (Scale == 1) {
5448 Amt = NumElements;
5449 } else {
Reid Spencerb83eb642006-10-20 07:07:24 +00005450 // If the allocation size is constant, form a constant mul expression
5451 Amt = ConstantInt::get(Type::UIntTy, Scale);
5452 if (isa<ConstantInt>(NumElements) && NumElements->getType()->isUnsigned())
5453 Amt = ConstantExpr::getMul(
5454 cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
5455 // otherwise multiply the amount and the number of elements
Chris Lattner455fcc82005-10-29 03:19:53 +00005456 else if (Scale != 1) {
5457 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
5458 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattner8142b0a2005-10-27 06:12:00 +00005459 }
Chris Lattner0ddac2a2005-10-27 05:53:56 +00005460 }
5461
Chris Lattnercfd65102005-10-29 04:36:15 +00005462 if (unsigned Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Reid Spencerb83eb642006-10-20 07:07:24 +00005463 Value *Off = ConstantInt::get(Type::UIntTy, Offset);
Chris Lattnercfd65102005-10-29 04:36:15 +00005464 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
5465 Amt = InsertNewInstBefore(Tmp, AI);
5466 }
5467
Chris Lattnerb3f83972005-10-24 06:03:58 +00005468 std::string Name = AI.getName(); AI.setName("");
5469 AllocationInst *New;
5470 if (isa<MallocInst>(AI))
Nate Begeman14b05292005-11-05 09:21:28 +00005471 New = new MallocInst(CastElTy, Amt, AI.getAlignment(), Name);
Chris Lattnerb3f83972005-10-24 06:03:58 +00005472 else
Nate Begeman14b05292005-11-05 09:21:28 +00005473 New = new AllocaInst(CastElTy, Amt, AI.getAlignment(), Name);
Chris Lattnerb3f83972005-10-24 06:03:58 +00005474 InsertNewInstBefore(New, AI);
Chris Lattner39387a52005-10-24 06:35:18 +00005475
5476 // If the allocation has multiple uses, insert a cast and change all things
5477 // that used it to use the new cast. This will also hack on CI, but it will
5478 // die soon.
5479 if (!AI.hasOneUse()) {
5480 AddUsesToWorkList(AI);
5481 CastInst *NewCast = new CastInst(New, AI.getType(), "tmpcast");
5482 InsertNewInstBefore(NewCast, AI);
5483 AI.replaceAllUsesWith(NewCast);
5484 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00005485 return ReplaceInstUsesWith(CI, New);
5486}
5487
Chris Lattner70074e02006-05-13 02:06:03 +00005488/// CanEvaluateInDifferentType - Return true if we can take the specified value
5489/// and return it without inserting any new casts. This is used by code that
5490/// tries to decide whether promoting or shrinking integer operations to wider
5491/// or smaller types will allow us to eliminate a truncate or extend.
5492static bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
5493 int &NumCastsRemoved) {
5494 if (isa<Constant>(V)) return true;
5495
5496 Instruction *I = dyn_cast<Instruction>(V);
5497 if (!I || !I->hasOneUse()) return false;
5498
5499 switch (I->getOpcode()) {
5500 case Instruction::And:
5501 case Instruction::Or:
5502 case Instruction::Xor:
5503 // These operators can all arbitrarily be extended or truncated.
5504 return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved) &&
5505 CanEvaluateInDifferentType(I->getOperand(1), Ty, NumCastsRemoved);
5506 case Instruction::Cast:
5507 // If this is a cast from the destination type, we can trivially eliminate
5508 // it, and this will remove a cast overall.
5509 if (I->getOperand(0)->getType() == Ty) {
Chris Lattnerd2280182006-06-28 17:34:50 +00005510 // If the first operand is itself a cast, and is eliminable, do not count
5511 // this as an eliminable cast. We would prefer to eliminate those two
5512 // casts first.
5513 if (CastInst *OpCast = dyn_cast<CastInst>(I->getOperand(0)))
5514 return true;
5515
Chris Lattner70074e02006-05-13 02:06:03 +00005516 ++NumCastsRemoved;
5517 return true;
5518 }
5519 // TODO: Can handle more cases here.
5520 break;
5521 }
5522
5523 return false;
5524}
5525
5526/// EvaluateInDifferentType - Given an expression that
5527/// CanEvaluateInDifferentType returns true for, actually insert the code to
5528/// evaluate the expression.
5529Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty) {
5530 if (Constant *C = dyn_cast<Constant>(V))
5531 return ConstantExpr::getCast(C, Ty);
5532
5533 // Otherwise, it must be an instruction.
5534 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00005535 Instruction *Res = 0;
Chris Lattner70074e02006-05-13 02:06:03 +00005536 switch (I->getOpcode()) {
5537 case Instruction::And:
5538 case Instruction::Or:
5539 case Instruction::Xor: {
5540 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty);
5541 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty);
5542 Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
5543 LHS, RHS, I->getName());
5544 break;
5545 }
5546 case Instruction::Cast:
5547 // If this is a cast from the destination type, return the input.
5548 if (I->getOperand(0)->getType() == Ty)
5549 return I->getOperand(0);
5550
5551 // TODO: Can handle more cases here.
5552 assert(0 && "Unreachable!");
5553 break;
5554 }
5555
5556 return InsertNewInstBefore(Res, *I);
5557}
5558
Chris Lattnerb3f83972005-10-24 06:03:58 +00005559
Chris Lattnera1be5662002-05-02 17:06:02 +00005560// CastInst simplification
Chris Lattnerdd841ae2002-04-18 17:39:14 +00005561//
Chris Lattner7e708292002-06-25 16:13:24 +00005562Instruction *InstCombiner::visitCastInst(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00005563 Value *Src = CI.getOperand(0);
5564
Chris Lattnera1be5662002-05-02 17:06:02 +00005565 // If the user is casting a value to the same type, eliminate this cast
5566 // instruction...
Chris Lattner79d35b32003-06-23 21:59:52 +00005567 if (CI.getType() == Src->getType())
5568 return ReplaceInstUsesWith(CI, Src);
Chris Lattnera1be5662002-05-02 17:06:02 +00005569
Chris Lattnere87597f2004-10-16 18:11:37 +00005570 if (isa<UndefValue>(Src)) // cast undef -> undef
5571 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
5572
Chris Lattnera1be5662002-05-02 17:06:02 +00005573 // If casting the result of another cast instruction, try to eliminate this
5574 // one!
5575 //
Chris Lattner6e7ba452005-01-01 16:22:27 +00005576 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
5577 Value *A = CSrc->getOperand(0);
5578 if (isEliminableCastOfCast(A->getType(), CSrc->getType(),
5579 CI.getType(), TD)) {
Chris Lattnera1be5662002-05-02 17:06:02 +00005580 // This instruction now refers directly to the cast's src operand. This
5581 // has a good chance of making CSrc dead.
Chris Lattner7e708292002-06-25 16:13:24 +00005582 CI.setOperand(0, CSrc->getOperand(0));
5583 return &CI;
Chris Lattnera1be5662002-05-02 17:06:02 +00005584 }
5585
Chris Lattner8fd217c2002-08-02 20:00:25 +00005586 // If this is an A->B->A cast, and we are dealing with integral types, try
5587 // to convert this into a logical 'and' instruction.
5588 //
Misha Brukmanfd939082005-04-21 23:48:37 +00005589 if (A->getType()->isInteger() &&
Chris Lattner0c4e8862002-09-03 01:08:28 +00005590 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
Chris Lattner6e7ba452005-01-01 16:22:27 +00005591 CSrc->getType()->isUnsigned() && // B->A cast must zero extend
Chris Lattner484d3cf2005-04-24 06:59:08 +00005592 CSrc->getType()->getPrimitiveSizeInBits() <
5593 CI.getType()->getPrimitiveSizeInBits()&&
5594 A->getType()->getPrimitiveSizeInBits() ==
5595 CI.getType()->getPrimitiveSizeInBits()) {
Chris Lattner8fd217c2002-08-02 20:00:25 +00005596 assert(CSrc->getType() != Type::ULongTy &&
5597 "Cannot have type bigger than ulong!");
Chris Lattner1a074fc2006-02-07 07:00:41 +00005598 uint64_t AndValue = CSrc->getType()->getIntegralTypeMask();
Reid Spencerb83eb642006-10-20 07:07:24 +00005599 Constant *AndOp = ConstantInt::get(A->getType()->getUnsignedVersion(),
Chris Lattner6e7ba452005-01-01 16:22:27 +00005600 AndValue);
5601 AndOp = ConstantExpr::getCast(AndOp, A->getType());
5602 Instruction *And = BinaryOperator::createAnd(CSrc->getOperand(0), AndOp);
5603 if (And->getType() != CI.getType()) {
5604 And->setName(CSrc->getName()+".mask");
5605 InsertNewInstBefore(And, CI);
5606 And = new CastInst(And, CI.getType());
5607 }
5608 return And;
Chris Lattner8fd217c2002-08-02 20:00:25 +00005609 }
5610 }
Chris Lattner6dce1a72006-02-07 06:56:34 +00005611
Chris Lattnera710ddc2004-05-25 04:29:21 +00005612 // If this is a cast to bool, turn it into the appropriate setne instruction.
5613 if (CI.getType() == Type::BoolTy)
Chris Lattner48595f12004-06-10 02:07:29 +00005614 return BinaryOperator::createSetNE(CI.getOperand(0),
Chris Lattnera710ddc2004-05-25 04:29:21 +00005615 Constant::getNullValue(CI.getOperand(0)->getType()));
5616
Chris Lattner6dce1a72006-02-07 06:56:34 +00005617 // See if we can simplify any instructions used by the LHS whose sole
5618 // purpose is to compute bits we don't care about.
Chris Lattner255d8912006-02-11 09:31:47 +00005619 if (CI.getType()->isInteger() && CI.getOperand(0)->getType()->isIntegral()) {
5620 uint64_t KnownZero, KnownOne;
5621 if (SimplifyDemandedBits(&CI, CI.getType()->getIntegralTypeMask(),
5622 KnownZero, KnownOne))
5623 return &CI;
5624 }
Chris Lattner6dce1a72006-02-07 06:56:34 +00005625
Chris Lattner797249b2003-06-21 23:12:02 +00005626 // If casting the result of a getelementptr instruction with no offset, turn
5627 // this into a cast of the original pointer!
5628 //
Chris Lattner79d35b32003-06-23 21:59:52 +00005629 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner797249b2003-06-21 23:12:02 +00005630 bool AllZeroOperands = true;
5631 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
5632 if (!isa<Constant>(GEP->getOperand(i)) ||
5633 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
5634 AllZeroOperands = false;
5635 break;
5636 }
5637 if (AllZeroOperands) {
5638 CI.setOperand(0, GEP->getOperand(0));
5639 return &CI;
5640 }
5641 }
5642
Chris Lattnerbc61e662003-11-02 05:57:39 +00005643 // If we are casting a malloc or alloca to a pointer to a type of the same
5644 // size, rewrite the allocation instruction to allocate the "right" type.
5645 //
5646 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattnerb3f83972005-10-24 06:03:58 +00005647 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
5648 return V;
Chris Lattnerbc61e662003-11-02 05:57:39 +00005649
Chris Lattner6e7ba452005-01-01 16:22:27 +00005650 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
5651 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
5652 return NV;
Chris Lattner4e998b22004-09-29 05:07:12 +00005653 if (isa<PHINode>(Src))
5654 if (Instruction *NV = FoldOpIntoPhi(CI))
5655 return NV;
Chris Lattner9fb92132006-04-12 18:09:35 +00005656
5657 // If the source and destination are pointers, and this cast is equivalent to
5658 // a getelementptr X, 0, 0, 0... turn it into the appropriate getelementptr.
5659 // This can enhance SROA and other transforms that want type-safe pointers.
5660 if (const PointerType *DstPTy = dyn_cast<PointerType>(CI.getType()))
5661 if (const PointerType *SrcPTy = dyn_cast<PointerType>(Src->getType())) {
5662 const Type *DstTy = DstPTy->getElementType();
5663 const Type *SrcTy = SrcPTy->getElementType();
5664
5665 Constant *ZeroUInt = Constant::getNullValue(Type::UIntTy);
5666 unsigned NumZeros = 0;
5667 while (SrcTy != DstTy &&
Chris Lattner63d32202006-09-11 21:43:16 +00005668 isa<CompositeType>(SrcTy) && !isa<PointerType>(SrcTy) &&
5669 SrcTy->getNumContainedTypes() /* not "{}" */) {
Chris Lattner9fb92132006-04-12 18:09:35 +00005670 SrcTy = cast<CompositeType>(SrcTy)->getTypeAtIndex(ZeroUInt);
5671 ++NumZeros;
5672 }
Chris Lattner4e998b22004-09-29 05:07:12 +00005673
Chris Lattner9fb92132006-04-12 18:09:35 +00005674 // If we found a path from the src to dest, create the getelementptr now.
5675 if (SrcTy == DstTy) {
5676 std::vector<Value*> Idxs(NumZeros+1, ZeroUInt);
5677 return new GetElementPtrInst(Src, Idxs);
5678 }
5679 }
5680
Chris Lattner24c8e382003-07-24 17:35:25 +00005681 // If the source value is an instruction with only this use, we can attempt to
5682 // propagate the cast into the instruction. Also, only handle integral types
5683 // for now.
Chris Lattner01575b72006-05-25 23:24:33 +00005684 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
Chris Lattnerfd059242003-10-15 16:48:29 +00005685 if (SrcI->hasOneUse() && Src->getType()->isIntegral() &&
Chris Lattner24c8e382003-07-24 17:35:25 +00005686 CI.getType()->isInteger()) { // Don't mess with casts to bool here
Chris Lattner70074e02006-05-13 02:06:03 +00005687
5688 int NumCastsRemoved = 0;
5689 if (CanEvaluateInDifferentType(SrcI, CI.getType(), NumCastsRemoved)) {
5690 // If this cast is a truncate, evaluting in a different type always
5691 // eliminates the cast, so it is always a win. If this is a noop-cast
5692 // this just removes a noop cast which isn't pointful, but simplifies
5693 // the code. If this is a zero-extension, we need to do an AND to
5694 // maintain the clear top-part of the computation, so we require that
5695 // the input have eliminated at least one cast. If this is a sign
5696 // extension, we insert two new casts (to do the extension) so we
5697 // require that two casts have been eliminated.
5698 bool DoXForm;
5699 switch (getCastType(Src->getType(), CI.getType())) {
5700 default: assert(0 && "Unknown cast type!");
5701 case Noop:
5702 case Truncate:
5703 DoXForm = true;
5704 break;
5705 case Zeroext:
5706 DoXForm = NumCastsRemoved >= 1;
5707 break;
5708 case Signext:
5709 DoXForm = NumCastsRemoved >= 2;
5710 break;
5711 }
5712
5713 if (DoXForm) {
5714 Value *Res = EvaluateInDifferentType(SrcI, CI.getType());
5715 assert(Res->getType() == CI.getType());
5716 switch (getCastType(Src->getType(), CI.getType())) {
5717 default: assert(0 && "Unknown cast type!");
5718 case Noop:
5719 case Truncate:
5720 // Just replace this cast with the result.
5721 return ReplaceInstUsesWith(CI, Res);
5722 case Zeroext: {
5723 // We need to emit an AND to clear the high bits.
5724 unsigned SrcBitSize = Src->getType()->getPrimitiveSizeInBits();
5725 unsigned DestBitSize = CI.getType()->getPrimitiveSizeInBits();
5726 assert(SrcBitSize < DestBitSize && "Not a zext?");
Reid Spencerb83eb642006-10-20 07:07:24 +00005727 Constant *C =
5728 ConstantInt::get(Type::ULongTy, (1ULL << SrcBitSize)-1);
Chris Lattner70074e02006-05-13 02:06:03 +00005729 C = ConstantExpr::getCast(C, CI.getType());
5730 return BinaryOperator::createAnd(Res, C);
5731 }
5732 case Signext:
5733 // We need to emit a cast to truncate, then a cast to sext.
5734 return new CastInst(InsertCastBefore(Res, Src->getType(), CI),
5735 CI.getType());
5736 }
5737 }
5738 }
5739
Chris Lattner24c8e382003-07-24 17:35:25 +00005740 const Type *DestTy = CI.getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00005741 unsigned SrcBitSize = Src->getType()->getPrimitiveSizeInBits();
5742 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
Chris Lattner24c8e382003-07-24 17:35:25 +00005743
5744 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
5745 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
5746
5747 switch (SrcI->getOpcode()) {
5748 case Instruction::Add:
5749 case Instruction::Mul:
5750 case Instruction::And:
5751 case Instruction::Or:
5752 case Instruction::Xor:
5753 // If we are discarding information, or just changing the sign, rewrite.
5754 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
5755 // Don't insert two casts if they cannot be eliminated. We allow two
5756 // casts to be inserted if the sizes are the same. This could only be
5757 // converting signedness, which is a noop.
Chris Lattner59a20772004-07-20 05:21:00 +00005758 if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy,TD) ||
5759 !ValueRequiresCast(Op0, DestTy, TD)) {
Chris Lattner24c8e382003-07-24 17:35:25 +00005760 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
5761 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
5762 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
5763 ->getOpcode(), Op0c, Op1c);
5764 }
5765 }
Chris Lattner7aed7ac2005-05-06 02:07:39 +00005766
5767 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
5768 if (SrcBitSize == 1 && SrcI->getOpcode() == Instruction::Xor &&
Chris Lattner47811b72006-09-28 23:35:22 +00005769 Op1 == ConstantBool::getTrue() &&
Chris Lattner7aed7ac2005-05-06 02:07:39 +00005770 (!Op0->hasOneUse() || !isa<SetCondInst>(Op0))) {
5771 Value *New = InsertOperandCastBefore(Op0, DestTy, &CI);
5772 return BinaryOperator::createXor(New,
5773 ConstantInt::get(CI.getType(), 1));
5774 }
Chris Lattner24c8e382003-07-24 17:35:25 +00005775 break;
Reid Spencer1628cec2006-10-26 06:15:43 +00005776 case Instruction::SDiv:
5777 case Instruction::UDiv:
Reid Spencer0a783f72006-11-02 01:53:59 +00005778 case Instruction::SRem:
5779 case Instruction::URem:
Reid Spencer1628cec2006-10-26 06:15:43 +00005780 // If we are just changing the sign, rewrite.
5781 if (DestBitSize == SrcBitSize) {
5782 // Don't insert two casts if they cannot be eliminated. We allow two
5783 // casts to be inserted if the sizes are the same. This could only be
5784 // converting signedness, which is a noop.
5785 if (!ValueRequiresCast(Op1, DestTy,TD) ||
5786 !ValueRequiresCast(Op0, DestTy, TD)) {
5787 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
5788 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
5789 return BinaryOperator::create(
5790 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
5791 }
5792 }
5793 break;
5794
Chris Lattner24c8e382003-07-24 17:35:25 +00005795 case Instruction::Shl:
5796 // Allow changing the sign of the source operand. Do not allow changing
5797 // the size of the shift, UNLESS the shift amount is a constant. We
5798 // mush not change variable sized shifts to a smaller size, because it
5799 // is undefined to shift more bits out than exist in the value.
5800 if (DestBitSize == SrcBitSize ||
5801 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
5802 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
5803 return new ShiftInst(Instruction::Shl, Op0c, Op1);
5804 }
5805 break;
Chris Lattnerd7115b02005-05-06 04:18:52 +00005806 case Instruction::Shr:
5807 // If this is a signed shr, and if all bits shifted in are about to be
5808 // truncated off, turn it into an unsigned shr to allow greater
5809 // simplifications.
5810 if (DestBitSize < SrcBitSize && Src->getType()->isSigned() &&
5811 isa<ConstantInt>(Op1)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00005812 unsigned ShiftAmt = cast<ConstantInt>(Op1)->getZExtValue();
Chris Lattnerd7115b02005-05-06 04:18:52 +00005813 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
5814 // Convert to unsigned.
5815 Value *N1 = InsertOperandCastBefore(Op0,
5816 Op0->getType()->getUnsignedVersion(), &CI);
5817 // Insert the new shift, which is now unsigned.
5818 N1 = InsertNewInstBefore(new ShiftInst(Instruction::Shr, N1,
5819 Op1, Src->getName()), CI);
5820 return new CastInst(N1, CI.getType());
5821 }
5822 }
5823 break;
5824
Chris Lattner3e88a4d2006-02-27 02:38:23 +00005825 case Instruction::SetEQ:
Chris Lattner693787a2005-05-04 19:10:26 +00005826 case Instruction::SetNE:
Chris Lattner3e88a4d2006-02-27 02:38:23 +00005827 // We if we are just checking for a seteq of a single bit and casting it
5828 // to an integer. If so, shift the bit to the appropriate place then
5829 // cast to integer to avoid the comparison.
Chris Lattner693787a2005-05-04 19:10:26 +00005830 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner3e88a4d2006-02-27 02:38:23 +00005831 uint64_t Op1CV = Op1C->getZExtValue();
5832 // cast (X == 0) to int --> X^1 iff X has only the low bit set.
5833 // cast (X == 0) to int --> (X>>1)^1 iff X has only the 2nd bit set.
5834 // cast (X == 1) to int --> X iff X has only the low bit set.
5835 // cast (X == 2) to int --> X>>1 iff X has only the 2nd bit set.
5836 // cast (X != 0) to int --> X iff X has only the low bit set.
5837 // cast (X != 0) to int --> X>>1 iff X has only the 2nd bit set.
5838 // cast (X != 1) to int --> X^1 iff X has only the low bit set.
5839 // cast (X != 2) to int --> (X>>1)^1 iff X has only the 2nd bit set.
5840 if (Op1CV == 0 || isPowerOf2_64(Op1CV)) {
5841 // If Op1C some other power of two, convert:
5842 uint64_t KnownZero, KnownOne;
5843 uint64_t TypeMask = Op1->getType()->getIntegralTypeMask();
5844 ComputeMaskedBits(Op0, TypeMask, KnownZero, KnownOne);
5845
5846 if (isPowerOf2_64(KnownZero^TypeMask)) { // Exactly one possible 1?
5847 bool isSetNE = SrcI->getOpcode() == Instruction::SetNE;
5848 if (Op1CV && (Op1CV != (KnownZero^TypeMask))) {
5849 // (X&4) == 2 --> false
5850 // (X&4) != 2 --> true
Chris Lattner06e1e252006-02-28 19:47:20 +00005851 Constant *Res = ConstantBool::get(isSetNE);
5852 Res = ConstantExpr::getCast(Res, CI.getType());
5853 return ReplaceInstUsesWith(CI, Res);
Chris Lattner3e88a4d2006-02-27 02:38:23 +00005854 }
5855
5856 unsigned ShiftAmt = Log2_64(KnownZero^TypeMask);
5857 Value *In = Op0;
5858 if (ShiftAmt) {
Chris Lattnerd1523802005-05-06 01:53:19 +00005859 // Perform an unsigned shr by shiftamt. Convert input to
5860 // unsigned if it is signed.
Chris Lattnerd1523802005-05-06 01:53:19 +00005861 if (In->getType()->isSigned())
Reid Spencer811b0cb2006-10-26 19:19:06 +00005862 In = InsertCastBefore(
5863 In, In->getType()->getUnsignedVersion(), CI);
Chris Lattnerd1523802005-05-06 01:53:19 +00005864 // Insert the shift to put the result in the low bit.
5865 In = InsertNewInstBefore(new ShiftInst(Instruction::Shr, In,
Chris Lattner3e88a4d2006-02-27 02:38:23 +00005866 ConstantInt::get(Type::UByteTy, ShiftAmt),
5867 In->getName()+".lobit"), CI);
Chris Lattnerd1523802005-05-06 01:53:19 +00005868 }
Chris Lattner3e88a4d2006-02-27 02:38:23 +00005869
5870 if ((Op1CV != 0) == isSetNE) { // Toggle the low bit.
5871 Constant *One = ConstantInt::get(In->getType(), 1);
5872 In = BinaryOperator::createXor(In, One, "tmp");
5873 InsertNewInstBefore(cast<Instruction>(In), CI);
Chris Lattnerd1523802005-05-06 01:53:19 +00005874 }
Chris Lattner3e88a4d2006-02-27 02:38:23 +00005875
5876 if (CI.getType() == In->getType())
5877 return ReplaceInstUsesWith(CI, In);
5878 else
5879 return new CastInst(In, CI.getType());
Chris Lattnerd1523802005-05-06 01:53:19 +00005880 }
Chris Lattner693787a2005-05-04 19:10:26 +00005881 }
5882 }
5883 break;
Chris Lattner24c8e382003-07-24 17:35:25 +00005884 }
5885 }
Chris Lattner01575b72006-05-25 23:24:33 +00005886
5887 if (SrcI->hasOneUse()) {
5888 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(SrcI)) {
5889 // Okay, we have (cast (shuffle ..)). We know this cast is a bitconvert
5890 // because the inputs are known to be a vector. Check to see if this is
5891 // a cast to a vector with the same # elts.
5892 if (isa<PackedType>(CI.getType()) &&
5893 cast<PackedType>(CI.getType())->getNumElements() ==
5894 SVI->getType()->getNumElements()) {
5895 CastInst *Tmp;
5896 // If either of the operands is a cast from CI.getType(), then
5897 // evaluating the shuffle in the casted destination's type will allow
5898 // us to eliminate at least one cast.
5899 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
5900 Tmp->getOperand(0)->getType() == CI.getType()) ||
5901 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
Chris Lattner18a4af22006-06-06 22:26:02 +00005902 Tmp->getOperand(0)->getType() == CI.getType())) {
Chris Lattner01575b72006-05-25 23:24:33 +00005903 Value *LHS = InsertOperandCastBefore(SVI->getOperand(0),
5904 CI.getType(), &CI);
5905 Value *RHS = InsertOperandCastBefore(SVI->getOperand(1),
5906 CI.getType(), &CI);
5907 // Return a new shuffle vector. Use the same element ID's, as we
5908 // know the vector types match #elts.
5909 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
5910 }
5911 }
5912 }
5913 }
5914 }
Chris Lattner0ddac2a2005-10-27 05:53:56 +00005915
Chris Lattnerdd841ae2002-04-18 17:39:14 +00005916 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00005917}
5918
Chris Lattnere576b912004-04-09 23:46:01 +00005919/// GetSelectFoldableOperands - We want to turn code that looks like this:
5920/// %C = or %A, %B
5921/// %D = select %cond, %C, %A
5922/// into:
5923/// %C = select %cond, %B, 0
5924/// %D = or %A, %C
5925///
5926/// Assuming that the specified instruction is an operand to the select, return
5927/// a bitmask indicating which operands of this instruction are foldable if they
5928/// equal the other incoming value of the select.
5929///
5930static unsigned GetSelectFoldableOperands(Instruction *I) {
5931 switch (I->getOpcode()) {
5932 case Instruction::Add:
5933 case Instruction::Mul:
5934 case Instruction::And:
5935 case Instruction::Or:
5936 case Instruction::Xor:
5937 return 3; // Can fold through either operand.
5938 case Instruction::Sub: // Can only fold on the amount subtracted.
5939 case Instruction::Shl: // Can only fold on the shift amount.
5940 case Instruction::Shr:
Misha Brukmanfd939082005-04-21 23:48:37 +00005941 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00005942 default:
5943 return 0; // Cannot fold
5944 }
5945}
5946
5947/// GetSelectFoldableConstant - For the same transformation as the previous
5948/// function, return the identity constant that goes into the select.
5949static Constant *GetSelectFoldableConstant(Instruction *I) {
5950 switch (I->getOpcode()) {
5951 default: assert(0 && "This cannot happen!"); abort();
5952 case Instruction::Add:
5953 case Instruction::Sub:
5954 case Instruction::Or:
5955 case Instruction::Xor:
5956 return Constant::getNullValue(I->getType());
5957 case Instruction::Shl:
5958 case Instruction::Shr:
5959 return Constant::getNullValue(Type::UByteTy);
5960 case Instruction::And:
5961 return ConstantInt::getAllOnesValue(I->getType());
5962 case Instruction::Mul:
5963 return ConstantInt::get(I->getType(), 1);
5964 }
5965}
5966
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00005967/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
5968/// have the same opcode and only one use each. Try to simplify this.
5969Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
5970 Instruction *FI) {
5971 if (TI->getNumOperands() == 1) {
5972 // If this is a non-volatile load or a cast from the same type,
5973 // merge.
5974 if (TI->getOpcode() == Instruction::Cast) {
5975 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
5976 return 0;
5977 } else {
5978 return 0; // unknown unary op.
5979 }
Misha Brukmanfd939082005-04-21 23:48:37 +00005980
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00005981 // Fold this by inserting a select from the input values.
5982 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
5983 FI->getOperand(0), SI.getName()+".v");
5984 InsertNewInstBefore(NewSI, SI);
5985 return new CastInst(NewSI, TI->getType());
5986 }
5987
5988 // Only handle binary operators here.
5989 if (!isa<ShiftInst>(TI) && !isa<BinaryOperator>(TI))
5990 return 0;
5991
5992 // Figure out if the operations have any operands in common.
5993 Value *MatchOp, *OtherOpT, *OtherOpF;
5994 bool MatchIsOpZero;
5995 if (TI->getOperand(0) == FI->getOperand(0)) {
5996 MatchOp = TI->getOperand(0);
5997 OtherOpT = TI->getOperand(1);
5998 OtherOpF = FI->getOperand(1);
5999 MatchIsOpZero = true;
6000 } else if (TI->getOperand(1) == FI->getOperand(1)) {
6001 MatchOp = TI->getOperand(1);
6002 OtherOpT = TI->getOperand(0);
6003 OtherOpF = FI->getOperand(0);
6004 MatchIsOpZero = false;
6005 } else if (!TI->isCommutative()) {
6006 return 0;
6007 } else if (TI->getOperand(0) == FI->getOperand(1)) {
6008 MatchOp = TI->getOperand(0);
6009 OtherOpT = TI->getOperand(1);
6010 OtherOpF = FI->getOperand(0);
6011 MatchIsOpZero = true;
6012 } else if (TI->getOperand(1) == FI->getOperand(0)) {
6013 MatchOp = TI->getOperand(1);
6014 OtherOpT = TI->getOperand(0);
6015 OtherOpF = FI->getOperand(1);
6016 MatchIsOpZero = true;
6017 } else {
6018 return 0;
6019 }
6020
6021 // If we reach here, they do have operations in common.
6022 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
6023 OtherOpF, SI.getName()+".v");
6024 InsertNewInstBefore(NewSI, SI);
6025
6026 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
6027 if (MatchIsOpZero)
6028 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
6029 else
6030 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
6031 } else {
6032 if (MatchIsOpZero)
6033 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), MatchOp, NewSI);
6034 else
6035 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), NewSI, MatchOp);
6036 }
6037}
6038
Chris Lattner3d69f462004-03-12 05:52:32 +00006039Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00006040 Value *CondVal = SI.getCondition();
6041 Value *TrueVal = SI.getTrueValue();
6042 Value *FalseVal = SI.getFalseValue();
6043
6044 // select true, X, Y -> X
6045 // select false, X, Y -> Y
6046 if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
Chris Lattner47811b72006-09-28 23:35:22 +00006047 return ReplaceInstUsesWith(SI, C->getValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00006048
6049 // select C, X, X -> X
6050 if (TrueVal == FalseVal)
6051 return ReplaceInstUsesWith(SI, TrueVal);
6052
Chris Lattnere87597f2004-10-16 18:11:37 +00006053 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
6054 return ReplaceInstUsesWith(SI, FalseVal);
6055 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
6056 return ReplaceInstUsesWith(SI, TrueVal);
6057 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
6058 if (isa<Constant>(TrueVal))
6059 return ReplaceInstUsesWith(SI, TrueVal);
6060 else
6061 return ReplaceInstUsesWith(SI, FalseVal);
6062 }
6063
Chris Lattner0c199a72004-04-08 04:43:23 +00006064 if (SI.getType() == Type::BoolTy)
6065 if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
Chris Lattner47811b72006-09-28 23:35:22 +00006066 if (C->getValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00006067 // Change: A = select B, true, C --> A = or B, C
Chris Lattner48595f12004-06-10 02:07:29 +00006068 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00006069 } else {
6070 // Change: A = select B, false, C --> A = and !B, C
6071 Value *NotCond =
6072 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6073 "not."+CondVal->getName()), SI);
Chris Lattner48595f12004-06-10 02:07:29 +00006074 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00006075 }
6076 } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
Chris Lattner47811b72006-09-28 23:35:22 +00006077 if (C->getValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00006078 // Change: A = select B, C, false --> A = and B, C
Chris Lattner48595f12004-06-10 02:07:29 +00006079 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00006080 } else {
6081 // Change: A = select B, C, true --> A = or !B, C
6082 Value *NotCond =
6083 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6084 "not."+CondVal->getName()), SI);
Chris Lattner48595f12004-06-10 02:07:29 +00006085 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00006086 }
6087 }
6088
Chris Lattner2eefe512004-04-09 19:05:30 +00006089 // Selecting between two integer constants?
6090 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
6091 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
6092 // select C, 1, 0 -> cast C to int
Reid Spencerb83eb642006-10-20 07:07:24 +00006093 if (FalseValC->isNullValue() && TrueValC->getZExtValue() == 1) {
Chris Lattner2eefe512004-04-09 19:05:30 +00006094 return new CastInst(CondVal, SI.getType());
Reid Spencerb83eb642006-10-20 07:07:24 +00006095 } else if (TrueValC->isNullValue() && FalseValC->getZExtValue() == 1) {
Chris Lattner2eefe512004-04-09 19:05:30 +00006096 // select C, 0, 1 -> cast !C to int
6097 Value *NotCond =
6098 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00006099 "not."+CondVal->getName()), SI);
Chris Lattner2eefe512004-04-09 19:05:30 +00006100 return new CastInst(NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00006101 }
Chris Lattner457dd822004-06-09 07:59:58 +00006102
Chris Lattnerb8456462006-09-20 04:44:59 +00006103 if (SetCondInst *IC = dyn_cast<SetCondInst>(SI.getCondition())) {
6104
6105 // (x <s 0) ? -1 : 0 -> sra x, 31
6106 // (x >u 2147483647) ? -1 : 0 -> sra x, 31
6107 if (TrueValC->isAllOnesValue() && FalseValC->isNullValue())
6108 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
6109 bool CanXForm = false;
6110 if (CmpCst->getType()->isSigned())
6111 CanXForm = CmpCst->isNullValue() &&
6112 IC->getOpcode() == Instruction::SetLT;
6113 else {
6114 unsigned Bits = CmpCst->getType()->getPrimitiveSizeInBits();
Reid Spencerb83eb642006-10-20 07:07:24 +00006115 CanXForm = (CmpCst->getZExtValue() == ~0ULL >> (64-Bits+1)) &&
Chris Lattnerb8456462006-09-20 04:44:59 +00006116 IC->getOpcode() == Instruction::SetGT;
6117 }
6118
6119 if (CanXForm) {
6120 // The comparison constant and the result are not neccessarily the
6121 // same width. In any case, the first step to do is make sure
6122 // that X is signed.
6123 Value *X = IC->getOperand(0);
6124 if (!X->getType()->isSigned())
6125 X = InsertCastBefore(X, X->getType()->getSignedVersion(), SI);
6126
6127 // Now that X is signed, we have to make the all ones value. Do
6128 // this by inserting a new SRA.
6129 unsigned Bits = X->getType()->getPrimitiveSizeInBits();
Reid Spencerb83eb642006-10-20 07:07:24 +00006130 Constant *ShAmt = ConstantInt::get(Type::UByteTy, Bits-1);
Chris Lattnerb8456462006-09-20 04:44:59 +00006131 Instruction *SRA = new ShiftInst(Instruction::Shr, X,
6132 ShAmt, "ones");
6133 InsertNewInstBefore(SRA, SI);
6134
6135 // Finally, convert to the type of the select RHS. If this is
6136 // smaller than the compare value, it will truncate the ones to
6137 // fit. If it is larger, it will sext the ones to fit.
6138 return new CastInst(SRA, SI.getType());
6139 }
6140 }
6141
6142
6143 // If one of the constants is zero (we know they can't both be) and we
6144 // have a setcc instruction with zero, and we have an 'and' with the
6145 // non-constant value, eliminate this whole mess. This corresponds to
6146 // cases like this: ((X & 27) ? 27 : 0)
6147 if (TrueValC->isNullValue() || FalseValC->isNullValue())
Chris Lattner65b72ba2006-09-18 04:22:48 +00006148 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00006149 cast<Constant>(IC->getOperand(1))->isNullValue())
6150 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
6151 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00006152 isa<ConstantInt>(ICA->getOperand(1)) &&
6153 (ICA->getOperand(1) == TrueValC ||
6154 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00006155 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
6156 // Okay, now we know that everything is set up, we just don't
6157 // know whether we have a setne or seteq and whether the true or
6158 // false val is the zero.
6159 bool ShouldNotVal = !TrueValC->isNullValue();
6160 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
6161 Value *V = ICA;
6162 if (ShouldNotVal)
6163 V = InsertNewInstBefore(BinaryOperator::create(
6164 Instruction::Xor, V, ICA->getOperand(1)), SI);
6165 return ReplaceInstUsesWith(SI, V);
6166 }
Chris Lattnerb8456462006-09-20 04:44:59 +00006167 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00006168 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00006169
6170 // See if we are selecting two values based on a comparison of the two values.
6171 if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
6172 if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
6173 // Transform (X == Y) ? X : Y -> Y
6174 if (SCI->getOpcode() == Instruction::SetEQ)
6175 return ReplaceInstUsesWith(SI, FalseVal);
6176 // Transform (X != Y) ? X : Y -> X
6177 if (SCI->getOpcode() == Instruction::SetNE)
6178 return ReplaceInstUsesWith(SI, TrueVal);
6179 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6180
6181 } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
6182 // Transform (X == Y) ? Y : X -> X
6183 if (SCI->getOpcode() == Instruction::SetEQ)
Chris Lattnerfbede522004-04-11 01:39:19 +00006184 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattnerd76956d2004-04-10 22:21:27 +00006185 // Transform (X != Y) ? Y : X -> Y
6186 if (SCI->getOpcode() == Instruction::SetNE)
Chris Lattnerfbede522004-04-11 01:39:19 +00006187 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerd76956d2004-04-10 22:21:27 +00006188 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6189 }
6190 }
Misha Brukmanfd939082005-04-21 23:48:37 +00006191
Chris Lattner87875da2005-01-13 22:52:24 +00006192 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
6193 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
6194 if (TI->hasOneUse() && FI->hasOneUse()) {
6195 bool isInverse = false;
6196 Instruction *AddOp = 0, *SubOp = 0;
6197
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00006198 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
6199 if (TI->getOpcode() == FI->getOpcode())
6200 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
6201 return IV;
6202
6203 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
6204 // even legal for FP.
Chris Lattner87875da2005-01-13 22:52:24 +00006205 if (TI->getOpcode() == Instruction::Sub &&
6206 FI->getOpcode() == Instruction::Add) {
6207 AddOp = FI; SubOp = TI;
6208 } else if (FI->getOpcode() == Instruction::Sub &&
6209 TI->getOpcode() == Instruction::Add) {
6210 AddOp = TI; SubOp = FI;
6211 }
6212
6213 if (AddOp) {
6214 Value *OtherAddOp = 0;
6215 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
6216 OtherAddOp = AddOp->getOperand(1);
6217 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
6218 OtherAddOp = AddOp->getOperand(0);
6219 }
6220
6221 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00006222 // So at this point we know we have (Y -> OtherAddOp):
6223 // select C, (add X, Y), (sub X, Z)
6224 Value *NegVal; // Compute -Z
6225 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
6226 NegVal = ConstantExpr::getNeg(C);
6227 } else {
6228 NegVal = InsertNewInstBefore(
6229 BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00006230 }
Chris Lattner97f37a42006-02-24 18:05:58 +00006231
6232 Value *NewTrueOp = OtherAddOp;
6233 Value *NewFalseOp = NegVal;
6234 if (AddOp != TI)
6235 std::swap(NewTrueOp, NewFalseOp);
6236 Instruction *NewSel =
6237 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
6238
6239 NewSel = InsertNewInstBefore(NewSel, SI);
6240 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00006241 }
6242 }
6243 }
Misha Brukmanfd939082005-04-21 23:48:37 +00006244
Chris Lattnere576b912004-04-09 23:46:01 +00006245 // See if we can fold the select into one of our operands.
6246 if (SI.getType()->isInteger()) {
6247 // See the comment above GetSelectFoldableOperands for a description of the
6248 // transformation we are doing here.
6249 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
6250 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
6251 !isa<Constant>(FalseVal))
6252 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
6253 unsigned OpToFold = 0;
6254 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
6255 OpToFold = 1;
6256 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
6257 OpToFold = 2;
6258 }
6259
6260 if (OpToFold) {
6261 Constant *C = GetSelectFoldableConstant(TVI);
6262 std::string Name = TVI->getName(); TVI->setName("");
6263 Instruction *NewSel =
6264 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
6265 Name);
6266 InsertNewInstBefore(NewSel, SI);
6267 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
6268 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
6269 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
6270 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
6271 else {
6272 assert(0 && "Unknown instruction!!");
6273 }
6274 }
6275 }
Chris Lattnera96879a2004-09-29 17:40:11 +00006276
Chris Lattnere576b912004-04-09 23:46:01 +00006277 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
6278 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
6279 !isa<Constant>(TrueVal))
6280 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
6281 unsigned OpToFold = 0;
6282 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
6283 OpToFold = 1;
6284 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
6285 OpToFold = 2;
6286 }
6287
6288 if (OpToFold) {
6289 Constant *C = GetSelectFoldableConstant(FVI);
6290 std::string Name = FVI->getName(); FVI->setName("");
6291 Instruction *NewSel =
6292 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
6293 Name);
6294 InsertNewInstBefore(NewSel, SI);
6295 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
6296 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
6297 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
6298 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
6299 else {
6300 assert(0 && "Unknown instruction!!");
6301 }
6302 }
6303 }
6304 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00006305
6306 if (BinaryOperator::isNot(CondVal)) {
6307 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
6308 SI.setOperand(1, FalseVal);
6309 SI.setOperand(2, TrueVal);
6310 return &SI;
6311 }
6312
Chris Lattner3d69f462004-03-12 05:52:32 +00006313 return 0;
6314}
6315
Chris Lattner95a959d2006-03-06 20:18:44 +00006316/// GetKnownAlignment - If the specified pointer has an alignment that we can
6317/// determine, return it, otherwise return 0.
6318static unsigned GetKnownAlignment(Value *V, TargetData *TD) {
6319 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
6320 unsigned Align = GV->getAlignment();
6321 if (Align == 0 && TD)
6322 Align = TD->getTypeAlignment(GV->getType()->getElementType());
6323 return Align;
6324 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
6325 unsigned Align = AI->getAlignment();
6326 if (Align == 0 && TD) {
6327 if (isa<AllocaInst>(AI))
6328 Align = TD->getTypeAlignment(AI->getType()->getElementType());
6329 else if (isa<MallocInst>(AI)) {
6330 // Malloc returns maximally aligned memory.
6331 Align = TD->getTypeAlignment(AI->getType()->getElementType());
6332 Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::DoubleTy));
6333 Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::LongTy));
6334 }
6335 }
6336 return Align;
Chris Lattner51c26e92006-03-07 01:28:57 +00006337 } else if (isa<CastInst>(V) ||
6338 (isa<ConstantExpr>(V) &&
6339 cast<ConstantExpr>(V)->getOpcode() == Instruction::Cast)) {
6340 User *CI = cast<User>(V);
Chris Lattner95a959d2006-03-06 20:18:44 +00006341 if (isa<PointerType>(CI->getOperand(0)->getType()))
6342 return GetKnownAlignment(CI->getOperand(0), TD);
6343 return 0;
Chris Lattner51c26e92006-03-07 01:28:57 +00006344 } else if (isa<GetElementPtrInst>(V) ||
6345 (isa<ConstantExpr>(V) &&
6346 cast<ConstantExpr>(V)->getOpcode()==Instruction::GetElementPtr)) {
6347 User *GEPI = cast<User>(V);
Chris Lattner95a959d2006-03-06 20:18:44 +00006348 unsigned BaseAlignment = GetKnownAlignment(GEPI->getOperand(0), TD);
6349 if (BaseAlignment == 0) return 0;
6350
6351 // If all indexes are zero, it is just the alignment of the base pointer.
6352 bool AllZeroOperands = true;
6353 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
6354 if (!isa<Constant>(GEPI->getOperand(i)) ||
6355 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
6356 AllZeroOperands = false;
6357 break;
6358 }
6359 if (AllZeroOperands)
6360 return BaseAlignment;
6361
6362 // Otherwise, if the base alignment is >= the alignment we expect for the
6363 // base pointer type, then we know that the resultant pointer is aligned at
6364 // least as much as its type requires.
6365 if (!TD) return 0;
6366
6367 const Type *BasePtrTy = GEPI->getOperand(0)->getType();
6368 if (TD->getTypeAlignment(cast<PointerType>(BasePtrTy)->getElementType())
Chris Lattner51c26e92006-03-07 01:28:57 +00006369 <= BaseAlignment) {
6370 const Type *GEPTy = GEPI->getType();
6371 return TD->getTypeAlignment(cast<PointerType>(GEPTy)->getElementType());
6372 }
Chris Lattner95a959d2006-03-06 20:18:44 +00006373 return 0;
6374 }
6375 return 0;
6376}
6377
Chris Lattner3d69f462004-03-12 05:52:32 +00006378
Chris Lattner8b0ea312006-01-13 20:11:04 +00006379/// visitCallInst - CallInst simplification. This mostly only handles folding
6380/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
6381/// the heavy lifting.
6382///
Chris Lattner9fe38862003-06-19 17:00:31 +00006383Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattner8b0ea312006-01-13 20:11:04 +00006384 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
6385 if (!II) return visitCallSite(&CI);
6386
Chris Lattner7bcc0e72004-02-28 05:22:00 +00006387 // Intrinsics cannot occur in an invoke, so handle them here instead of in
6388 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00006389 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00006390 bool Changed = false;
6391
6392 // memmove/cpy/set of zero bytes is a noop.
6393 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
6394 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
6395
Chris Lattner35b9e482004-10-12 04:52:52 +00006396 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +00006397 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +00006398 // Replace the instruction with just byte operations. We would
6399 // transform other cases to loads/stores, but we don't know if
6400 // alignment is sufficient.
6401 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00006402 }
6403
Chris Lattner35b9e482004-10-12 04:52:52 +00006404 // If we have a memmove and the source operation is a constant global,
6405 // then the source and dest pointers can't alias, so we can change this
6406 // into a call to memcpy.
Chris Lattner95a959d2006-03-06 20:18:44 +00006407 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00006408 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
6409 if (GVSrc->isConstant()) {
6410 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner21959392006-03-03 01:34:17 +00006411 const char *Name;
6412 if (CI.getCalledFunction()->getFunctionType()->getParamType(3) ==
6413 Type::UIntTy)
6414 Name = "llvm.memcpy.i32";
6415 else
6416 Name = "llvm.memcpy.i64";
6417 Function *MemCpy = M->getOrInsertFunction(Name,
Chris Lattner35b9e482004-10-12 04:52:52 +00006418 CI.getCalledFunction()->getFunctionType());
6419 CI.setOperand(0, MemCpy);
6420 Changed = true;
6421 }
Chris Lattner95a959d2006-03-06 20:18:44 +00006422 }
Chris Lattner35b9e482004-10-12 04:52:52 +00006423
Chris Lattner95a959d2006-03-06 20:18:44 +00006424 // If we can determine a pointer alignment that is bigger than currently
6425 // set, update the alignment.
6426 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
6427 unsigned Alignment1 = GetKnownAlignment(MI->getOperand(1), TD);
6428 unsigned Alignment2 = GetKnownAlignment(MI->getOperand(2), TD);
6429 unsigned Align = std::min(Alignment1, Alignment2);
Reid Spencerb83eb642006-10-20 07:07:24 +00006430 if (MI->getAlignment()->getZExtValue() < Align) {
6431 MI->setAlignment(ConstantInt::get(Type::UIntTy, Align));
Chris Lattner95a959d2006-03-06 20:18:44 +00006432 Changed = true;
6433 }
6434 } else if (isa<MemSetInst>(MI)) {
6435 unsigned Alignment = GetKnownAlignment(MI->getDest(), TD);
Reid Spencerb83eb642006-10-20 07:07:24 +00006436 if (MI->getAlignment()->getZExtValue() < Alignment) {
6437 MI->setAlignment(ConstantInt::get(Type::UIntTy, Alignment));
Chris Lattner95a959d2006-03-06 20:18:44 +00006438 Changed = true;
6439 }
6440 }
6441
Chris Lattner8b0ea312006-01-13 20:11:04 +00006442 if (Changed) return II;
Chris Lattnera728ddc2006-01-13 21:28:09 +00006443 } else {
6444 switch (II->getIntrinsicID()) {
6445 default: break;
Chris Lattner82ed58f2006-04-02 05:30:25 +00006446 case Intrinsic::ppc_altivec_lvx:
6447 case Intrinsic::ppc_altivec_lvxl:
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00006448 case Intrinsic::x86_sse_loadu_ps:
6449 case Intrinsic::x86_sse2_loadu_pd:
6450 case Intrinsic::x86_sse2_loadu_dq:
6451 // Turn PPC lvx -> load if the pointer is known aligned.
6452 // Turn X86 loadups -> load if the pointer is known aligned.
Chris Lattner82ed58f2006-04-02 05:30:25 +00006453 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
Chris Lattnere2ed0572006-04-06 19:19:17 +00006454 Value *Ptr = InsertCastBefore(II->getOperand(1),
6455 PointerType::get(II->getType()), CI);
Chris Lattner82ed58f2006-04-02 05:30:25 +00006456 return new LoadInst(Ptr);
6457 }
6458 break;
6459 case Intrinsic::ppc_altivec_stvx:
6460 case Intrinsic::ppc_altivec_stvxl:
6461 // Turn stvx -> store if the pointer is known aligned.
6462 if (GetKnownAlignment(II->getOperand(2), TD) >= 16) {
Chris Lattnere2ed0572006-04-06 19:19:17 +00006463 const Type *OpPtrTy = PointerType::get(II->getOperand(1)->getType());
6464 Value *Ptr = InsertCastBefore(II->getOperand(2), OpPtrTy, CI);
Chris Lattner82ed58f2006-04-02 05:30:25 +00006465 return new StoreInst(II->getOperand(1), Ptr);
6466 }
6467 break;
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00006468 case Intrinsic::x86_sse_storeu_ps:
6469 case Intrinsic::x86_sse2_storeu_pd:
6470 case Intrinsic::x86_sse2_storeu_dq:
6471 case Intrinsic::x86_sse2_storel_dq:
6472 // Turn X86 storeu -> store if the pointer is known aligned.
6473 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
6474 const Type *OpPtrTy = PointerType::get(II->getOperand(2)->getType());
6475 Value *Ptr = InsertCastBefore(II->getOperand(1), OpPtrTy, CI);
6476 return new StoreInst(II->getOperand(2), Ptr);
6477 }
6478 break;
Chris Lattner867b99f2006-10-05 06:55:50 +00006479
6480 case Intrinsic::x86_sse_cvttss2si: {
6481 // These intrinsics only demands the 0th element of its input vector. If
6482 // we can simplify the input based on that, do so now.
6483 uint64_t UndefElts;
6484 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
6485 UndefElts)) {
6486 II->setOperand(1, V);
6487 return II;
6488 }
6489 break;
6490 }
6491
Chris Lattnere2ed0572006-04-06 19:19:17 +00006492 case Intrinsic::ppc_altivec_vperm:
6493 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
6494 if (ConstantPacked *Mask = dyn_cast<ConstantPacked>(II->getOperand(3))) {
6495 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
6496
6497 // Check that all of the elements are integer constants or undefs.
6498 bool AllEltsOk = true;
6499 for (unsigned i = 0; i != 16; ++i) {
6500 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
6501 !isa<UndefValue>(Mask->getOperand(i))) {
6502 AllEltsOk = false;
6503 break;
6504 }
6505 }
6506
6507 if (AllEltsOk) {
6508 // Cast the input vectors to byte vectors.
6509 Value *Op0 = InsertCastBefore(II->getOperand(1), Mask->getType(), CI);
6510 Value *Op1 = InsertCastBefore(II->getOperand(2), Mask->getType(), CI);
6511 Value *Result = UndefValue::get(Op0->getType());
6512
6513 // Only extract each element once.
6514 Value *ExtractedElts[32];
6515 memset(ExtractedElts, 0, sizeof(ExtractedElts));
6516
6517 for (unsigned i = 0; i != 16; ++i) {
6518 if (isa<UndefValue>(Mask->getOperand(i)))
6519 continue;
Reid Spencerb83eb642006-10-20 07:07:24 +00006520 unsigned Idx =cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
Chris Lattnere2ed0572006-04-06 19:19:17 +00006521 Idx &= 31; // Match the hardware behavior.
6522
6523 if (ExtractedElts[Idx] == 0) {
6524 Instruction *Elt =
Chris Lattner867b99f2006-10-05 06:55:50 +00006525 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00006526 InsertNewInstBefore(Elt, CI);
6527 ExtractedElts[Idx] = Elt;
6528 }
6529
6530 // Insert this value into the result vector.
Chris Lattner867b99f2006-10-05 06:55:50 +00006531 Result = new InsertElementInst(Result, ExtractedElts[Idx], i,"tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00006532 InsertNewInstBefore(cast<Instruction>(Result), CI);
6533 }
6534 return new CastInst(Result, CI.getType());
6535 }
6536 }
6537 break;
6538
Chris Lattnera728ddc2006-01-13 21:28:09 +00006539 case Intrinsic::stackrestore: {
6540 // If the save is right next to the restore, remove the restore. This can
6541 // happen when variable allocas are DCE'd.
6542 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
6543 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
6544 BasicBlock::iterator BI = SS;
6545 if (&*++BI == II)
6546 return EraseInstFromFunction(CI);
6547 }
6548 }
6549
6550 // If the stack restore is in a return/unwind block and if there are no
6551 // allocas or calls between the restore and the return, nuke the restore.
6552 TerminatorInst *TI = II->getParent()->getTerminator();
6553 if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
6554 BasicBlock::iterator BI = II;
6555 bool CannotRemove = false;
6556 for (++BI; &*BI != TI; ++BI) {
6557 if (isa<AllocaInst>(BI) ||
6558 (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
6559 CannotRemove = true;
6560 break;
6561 }
6562 }
6563 if (!CannotRemove)
6564 return EraseInstFromFunction(CI);
6565 }
6566 break;
6567 }
6568 }
Chris Lattner35b9e482004-10-12 04:52:52 +00006569 }
6570
Chris Lattner8b0ea312006-01-13 20:11:04 +00006571 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +00006572}
6573
6574// InvokeInst simplification
6575//
6576Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +00006577 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +00006578}
6579
Chris Lattnera44d8a22003-10-07 22:32:43 +00006580// visitCallSite - Improvements for call and invoke instructions.
6581//
6582Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +00006583 bool Changed = false;
6584
6585 // If the callee is a constexpr cast of a function, attempt to move the cast
6586 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +00006587 if (transformConstExprCastCall(CS)) return 0;
6588
Chris Lattner6c266db2003-10-07 22:54:13 +00006589 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +00006590
Chris Lattner08b22ec2005-05-13 07:09:09 +00006591 if (Function *CalleeF = dyn_cast<Function>(Callee))
6592 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
6593 Instruction *OldCall = CS.getInstruction();
6594 // If the call and callee calling conventions don't match, this call must
6595 // be unreachable, as the call is undefined.
Chris Lattner47811b72006-09-28 23:35:22 +00006596 new StoreInst(ConstantBool::getTrue(),
Chris Lattner08b22ec2005-05-13 07:09:09 +00006597 UndefValue::get(PointerType::get(Type::BoolTy)), OldCall);
6598 if (!OldCall->use_empty())
6599 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
6600 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
6601 return EraseInstFromFunction(*OldCall);
6602 return 0;
6603 }
6604
Chris Lattner17be6352004-10-18 02:59:09 +00006605 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
6606 // This instruction is not reachable, just remove it. We insert a store to
6607 // undef so that we know that this code is not reachable, despite the fact
6608 // that we can't modify the CFG here.
Chris Lattner47811b72006-09-28 23:35:22 +00006609 new StoreInst(ConstantBool::getTrue(),
Chris Lattner17be6352004-10-18 02:59:09 +00006610 UndefValue::get(PointerType::get(Type::BoolTy)),
6611 CS.getInstruction());
6612
6613 if (!CS.getInstruction()->use_empty())
6614 CS.getInstruction()->
6615 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
6616
6617 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
6618 // Don't break the CFG, insert a dummy cond branch.
6619 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
Chris Lattner47811b72006-09-28 23:35:22 +00006620 ConstantBool::getTrue(), II);
Chris Lattnere87597f2004-10-16 18:11:37 +00006621 }
Chris Lattner17be6352004-10-18 02:59:09 +00006622 return EraseInstFromFunction(*CS.getInstruction());
6623 }
Chris Lattnere87597f2004-10-16 18:11:37 +00006624
Chris Lattner6c266db2003-10-07 22:54:13 +00006625 const PointerType *PTy = cast<PointerType>(Callee->getType());
6626 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
6627 if (FTy->isVarArg()) {
6628 // See if we can optimize any arguments passed through the varargs area of
6629 // the call.
6630 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
6631 E = CS.arg_end(); I != E; ++I)
6632 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
6633 // If this cast does not effect the value passed through the varargs
6634 // area, we can eliminate the use of the cast.
6635 Value *Op = CI->getOperand(0);
6636 if (CI->getType()->isLosslesslyConvertibleTo(Op->getType())) {
6637 *I = Op;
6638 Changed = true;
6639 }
6640 }
6641 }
Misha Brukmanfd939082005-04-21 23:48:37 +00006642
Chris Lattner6c266db2003-10-07 22:54:13 +00006643 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +00006644}
6645
Chris Lattner9fe38862003-06-19 17:00:31 +00006646// transformConstExprCastCall - If the callee is a constexpr cast of a function,
6647// attempt to move the cast to the arguments of the call/invoke.
6648//
6649bool InstCombiner::transformConstExprCastCall(CallSite CS) {
6650 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
6651 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Chris Lattner9db07b92004-07-18 18:59:44 +00006652 if (CE->getOpcode() != Instruction::Cast || !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +00006653 return false;
Reid Spencer8863f182004-07-18 00:38:32 +00006654 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +00006655 Instruction *Caller = CS.getInstruction();
6656
6657 // Okay, this is a cast from a function to a different type. Unless doing so
6658 // would cause a type conversion of one of our arguments, change this call to
6659 // be a direct call with arguments casted to the appropriate types.
6660 //
6661 const FunctionType *FT = Callee->getFunctionType();
6662 const Type *OldRetTy = Caller->getType();
6663
Chris Lattnerf78616b2004-01-14 06:06:08 +00006664 // Check to see if we are changing the return type...
6665 if (OldRetTy != FT->getReturnType()) {
6666 if (Callee->isExternal() &&
Andrew Lenharth8117f9a2006-04-20 14:56:47 +00006667 !(OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()) ||
6668 (isa<PointerType>(FT->getReturnType()) &&
Andrew Lenharth7a31b972006-04-20 15:41:37 +00006669 TD->getIntPtrType()->isLosslesslyConvertibleTo(OldRetTy)))
Andrew Lenharth8117f9a2006-04-20 14:56:47 +00006670 && !Caller->use_empty())
Chris Lattnerf78616b2004-01-14 06:06:08 +00006671 return false; // Cannot transform this return value...
6672
6673 // If the callsite is an invoke instruction, and the return value is used by
6674 // a PHI node in a successor, we cannot change the return type of the call
6675 // because there is no place to put the cast instruction (without breaking
6676 // the critical edge). Bail out in this case.
6677 if (!Caller->use_empty())
6678 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
6679 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
6680 UI != E; ++UI)
6681 if (PHINode *PN = dyn_cast<PHINode>(*UI))
6682 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00006683 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +00006684 return false;
6685 }
Chris Lattner9fe38862003-06-19 17:00:31 +00006686
6687 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
6688 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +00006689
Chris Lattner9fe38862003-06-19 17:00:31 +00006690 CallSite::arg_iterator AI = CS.arg_begin();
6691 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
6692 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +00006693 const Type *ActTy = (*AI)->getType();
Reid Spencerb83eb642006-10-20 07:07:24 +00006694 ConstantInt* c = dyn_cast<ConstantInt>(*AI);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +00006695 //Either we can cast directly, or we can upconvert the argument
6696 bool isConvertible = ActTy->isLosslesslyConvertibleTo(ParamTy) ||
6697 (ParamTy->isIntegral() && ActTy->isIntegral() &&
6698 ParamTy->isSigned() == ActTy->isSigned() &&
6699 ParamTy->getPrimitiveSize() >= ActTy->getPrimitiveSize()) ||
6700 (c && ParamTy->getPrimitiveSize() >= ActTy->getPrimitiveSize() &&
Reid Spencerb83eb642006-10-20 07:07:24 +00006701 c->getSExtValue() > 0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006702 if (Callee->isExternal() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +00006703 }
6704
6705 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
6706 Callee->isExternal())
6707 return false; // Do not delete arguments unless we have a function body...
6708
6709 // Okay, we decided that this is a safe thing to do: go ahead and start
6710 // inserting cast instructions as necessary...
6711 std::vector<Value*> Args;
6712 Args.reserve(NumActualArgs);
6713
6714 AI = CS.arg_begin();
6715 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
6716 const Type *ParamTy = FT->getParamType(i);
6717 if ((*AI)->getType() == ParamTy) {
6718 Args.push_back(*AI);
6719 } else {
Chris Lattner0c199a72004-04-08 04:43:23 +00006720 Args.push_back(InsertNewInstBefore(new CastInst(*AI, ParamTy, "tmp"),
6721 *Caller));
Chris Lattner9fe38862003-06-19 17:00:31 +00006722 }
6723 }
6724
6725 // If the function takes more arguments than the call was taking, add them
6726 // now...
6727 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
6728 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
6729
6730 // If we are removing arguments to the function, emit an obnoxious warning...
6731 if (FT->getNumParams() < NumActualArgs)
6732 if (!FT->isVarArg()) {
6733 std::cerr << "WARNING: While resolving call to function '"
6734 << Callee->getName() << "' arguments were dropped!\n";
6735 } else {
6736 // Add all of the arguments in their promoted form to the arg list...
6737 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
6738 const Type *PTy = getPromotedType((*AI)->getType());
6739 if (PTy != (*AI)->getType()) {
6740 // Must promote to pass through va_arg area!
6741 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
6742 InsertNewInstBefore(Cast, *Caller);
6743 Args.push_back(Cast);
6744 } else {
6745 Args.push_back(*AI);
6746 }
6747 }
6748 }
6749
6750 if (FT->getReturnType() == Type::VoidTy)
6751 Caller->setName(""); // Void type should not have a name...
6752
6753 Instruction *NC;
6754 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00006755 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattner9fe38862003-06-19 17:00:31 +00006756 Args, Caller->getName(), Caller);
Chris Lattnere4370262005-05-14 12:25:32 +00006757 cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
Chris Lattner9fe38862003-06-19 17:00:31 +00006758 } else {
6759 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
Chris Lattnera9e92112005-05-06 06:48:21 +00006760 if (cast<CallInst>(Caller)->isTailCall())
6761 cast<CallInst>(NC)->setTailCall();
Chris Lattnere4370262005-05-14 12:25:32 +00006762 cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Chris Lattner9fe38862003-06-19 17:00:31 +00006763 }
6764
6765 // Insert a cast of the return type as necessary...
6766 Value *NV = NC;
6767 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
6768 if (NV->getType() != Type::VoidTy) {
6769 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +00006770
6771 // If this is an invoke instruction, we should insert it after the first
6772 // non-phi, instruction in the normal successor block.
6773 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
6774 BasicBlock::iterator I = II->getNormalDest()->begin();
6775 while (isa<PHINode>(I)) ++I;
6776 InsertNewInstBefore(NC, *I);
6777 } else {
6778 // Otherwise, it's a call, just insert cast right after the call instr
6779 InsertNewInstBefore(NC, *Caller);
6780 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00006781 AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00006782 } else {
Chris Lattnerc30bda72004-10-17 21:22:38 +00006783 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +00006784 }
6785 }
6786
6787 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
6788 Caller->replaceAllUsesWith(NV);
6789 Caller->getParent()->getInstList().erase(Caller);
6790 removeFromWorkList(Caller);
6791 return true;
6792}
6793
Chris Lattner7da52b22006-11-01 04:51:18 +00006794/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
6795/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
6796/// and a single binop.
6797Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
6798 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Chris Lattner9c080502006-11-01 07:43:41 +00006799 assert(isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst) ||
6800 isa<GetElementPtrInst>(FirstInst));
Chris Lattner7da52b22006-11-01 04:51:18 +00006801 unsigned Opc = FirstInst->getOpcode();
Chris Lattnera90a24c2006-11-01 04:55:47 +00006802 const Type *LHSType = FirstInst->getOperand(0)->getType();
Chris Lattner9c080502006-11-01 07:43:41 +00006803 const Type *RHSType = FirstInst->getOperand(1)->getType();
Chris Lattner7da52b22006-11-01 04:51:18 +00006804
6805 // Scan to see if all operands are the same opcode, all have one use, and all
6806 // kill their operands (i.e. the operands have one use).
Chris Lattnera90a24c2006-11-01 04:55:47 +00006807 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
Chris Lattner7da52b22006-11-01 04:51:18 +00006808 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnera90a24c2006-11-01 04:55:47 +00006809 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
6810 // Verify type of the LHS matches so we don't fold setcc's of different
Chris Lattner9c080502006-11-01 07:43:41 +00006811 // types or GEP's with different index types.
6812 I->getOperand(0)->getType() != LHSType ||
6813 I->getOperand(1)->getType() != RHSType)
Chris Lattner7da52b22006-11-01 04:51:18 +00006814 return 0;
6815 }
6816
6817 // Otherwise, this is safe and profitable to transform. Create two phi nodes.
6818 PHINode *NewLHS = new PHINode(FirstInst->getOperand(0)->getType(),
6819 FirstInst->getOperand(0)->getName()+".pn");
6820 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
6821 PHINode *NewRHS = new PHINode(FirstInst->getOperand(1)->getType(),
6822 FirstInst->getOperand(1)->getName()+".pn");
6823 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
6824
6825 Value *InLHS = FirstInst->getOperand(0);
6826 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
6827 Value *InRHS = FirstInst->getOperand(1);
6828 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
6829
6830 // Add all operands to the new PHsI.
6831 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
6832 Value *NewInLHS = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
6833 Value *NewInRHS = cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
6834 if (NewInLHS != InLHS) InLHS = 0;
6835 if (NewInRHS != InRHS) InRHS = 0;
6836 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
6837 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
6838 }
6839
Chris Lattner9c080502006-11-01 07:43:41 +00006840 Value *LHSVal;
6841 if (InLHS) {
6842 // The new PHI unions all of the same values together. This is really
6843 // common, so we handle it intelligently here for compile-time speed.
6844 LHSVal = InLHS;
6845 delete NewLHS;
6846 } else {
6847 InsertNewInstBefore(NewLHS, PN);
6848 LHSVal = NewLHS;
6849 }
6850 Value *RHSVal;
6851 if (InRHS) {
6852 // The new PHI unions all of the same values together. This is really
6853 // common, so we handle it intelligently here for compile-time speed.
6854 RHSVal = InRHS;
6855 delete NewRHS;
6856 } else {
6857 InsertNewInstBefore(NewRHS, PN);
6858 RHSVal = NewRHS;
6859 }
6860
Chris Lattner7da52b22006-11-01 04:51:18 +00006861 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattner9c080502006-11-01 07:43:41 +00006862 return BinaryOperator::create(BinOp->getOpcode(), LHSVal, RHSVal);
6863 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FirstInst))
6864 return new ShiftInst(SI->getOpcode(), LHSVal, RHSVal);
6865 else {
6866 assert(isa<GetElementPtrInst>(FirstInst));
6867 return new GetElementPtrInst(LHSVal, RHSVal);
6868 }
Chris Lattner7da52b22006-11-01 04:51:18 +00006869}
6870
Chris Lattner76c73142006-11-01 07:13:54 +00006871/// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
6872/// of the block that defines it. This means that it must be obvious the value
6873/// of the load is not changed from the point of the load to the end of the
6874/// block it is in.
6875static bool isSafeToSinkLoad(LoadInst *L) {
6876 BasicBlock::iterator BBI = L, E = L->getParent()->end();
6877
6878 for (++BBI; BBI != E; ++BBI)
6879 if (BBI->mayWriteToMemory())
6880 return false;
6881 return true;
6882}
6883
Chris Lattner9fe38862003-06-19 17:00:31 +00006884
Chris Lattnerbac32862004-11-14 19:13:23 +00006885// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
6886// operator and they all are only used by the PHI, PHI together their
6887// inputs, and do the operation once, to the result of the PHI.
6888Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
6889 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
6890
6891 // Scan the instruction, looking for input operations that can be folded away.
6892 // If all input operands to the phi are the same instruction (e.g. a cast from
6893 // the same type or "+42") we can pull the operation through the PHI, reducing
6894 // code size and simplifying code.
6895 Constant *ConstantOp = 0;
6896 const Type *CastSrcTy = 0;
Chris Lattner76c73142006-11-01 07:13:54 +00006897 bool isVolatile = false;
Chris Lattnerbac32862004-11-14 19:13:23 +00006898 if (isa<CastInst>(FirstInst)) {
6899 CastSrcTy = FirstInst->getOperand(0)->getType();
6900 } else if (isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst)) {
Chris Lattner7da52b22006-11-01 04:51:18 +00006901 // Can fold binop or shift here if the RHS is a constant, otherwise call
6902 // FoldPHIArgBinOpIntoPHI.
Chris Lattnerbac32862004-11-14 19:13:23 +00006903 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattner7da52b22006-11-01 04:51:18 +00006904 if (ConstantOp == 0)
6905 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner76c73142006-11-01 07:13:54 +00006906 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
6907 isVolatile = LI->isVolatile();
6908 // We can't sink the load if the loaded value could be modified between the
6909 // load and the PHI.
6910 if (LI->getParent() != PN.getIncomingBlock(0) ||
6911 !isSafeToSinkLoad(LI))
6912 return 0;
Chris Lattner9c080502006-11-01 07:43:41 +00006913 } else if (isa<GetElementPtrInst>(FirstInst)) {
6914 if (FirstInst->getNumOperands() == 2)
6915 return FoldPHIArgBinOpIntoPHI(PN);
6916 // Can't handle general GEPs yet.
6917 return 0;
Chris Lattnerbac32862004-11-14 19:13:23 +00006918 } else {
6919 return 0; // Cannot fold this operation.
6920 }
6921
6922 // Check to see if all arguments are the same operation.
6923 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
6924 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
6925 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
6926 if (!I->hasOneUse() || I->getOpcode() != FirstInst->getOpcode())
6927 return 0;
6928 if (CastSrcTy) {
6929 if (I->getOperand(0)->getType() != CastSrcTy)
6930 return 0; // Cast operation must match.
Chris Lattner76c73142006-11-01 07:13:54 +00006931 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
6932 // We can't sink the load if the loaded value could be modified between the
6933 // load and the PHI.
6934 if (LI->isVolatile() != isVolatile ||
6935 LI->getParent() != PN.getIncomingBlock(i) ||
6936 !isSafeToSinkLoad(LI))
6937 return 0;
Chris Lattnerbac32862004-11-14 19:13:23 +00006938 } else if (I->getOperand(1) != ConstantOp) {
6939 return 0;
6940 }
6941 }
6942
6943 // Okay, they are all the same operation. Create a new PHI node of the
6944 // correct type, and PHI together all of the LHS's of the instructions.
6945 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
6946 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +00006947 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +00006948
6949 Value *InVal = FirstInst->getOperand(0);
6950 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00006951
6952 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +00006953 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
6954 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
6955 if (NewInVal != InVal)
6956 InVal = 0;
6957 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
6958 }
6959
6960 Value *PhiVal;
6961 if (InVal) {
6962 // The new PHI unions all of the same values together. This is really
6963 // common, so we handle it intelligently here for compile-time speed.
6964 PhiVal = InVal;
6965 delete NewPN;
6966 } else {
6967 InsertNewInstBefore(NewPN, PN);
6968 PhiVal = NewPN;
6969 }
Misha Brukmanfd939082005-04-21 23:48:37 +00006970
Chris Lattnerbac32862004-11-14 19:13:23 +00006971 // Insert and return the new operation.
6972 if (isa<CastInst>(FirstInst))
Chris Lattnerb5893442004-11-14 19:29:34 +00006973 return new CastInst(PhiVal, PN.getType());
Chris Lattner76c73142006-11-01 07:13:54 +00006974 else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst))
6975 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattnerbac32862004-11-14 19:13:23 +00006976 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattnerb5893442004-11-14 19:29:34 +00006977 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattnerbac32862004-11-14 19:13:23 +00006978 else
6979 return new ShiftInst(cast<ShiftInst>(FirstInst)->getOpcode(),
Chris Lattnerb5893442004-11-14 19:29:34 +00006980 PhiVal, ConstantOp);
Chris Lattnerbac32862004-11-14 19:13:23 +00006981}
Chris Lattnera1be5662002-05-02 17:06:02 +00006982
Chris Lattnera3fd1c52005-01-17 05:10:15 +00006983/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
6984/// that is dead.
6985static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
6986 if (PN->use_empty()) return true;
6987 if (!PN->hasOneUse()) return false;
6988
6989 // Remember this node, and if we find the cycle, return.
6990 if (!PotentiallyDeadPHIs.insert(PN).second)
6991 return true;
6992
6993 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
6994 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +00006995
Chris Lattnera3fd1c52005-01-17 05:10:15 +00006996 return false;
6997}
6998
Chris Lattner473945d2002-05-06 18:06:38 +00006999// PHINode simplification
7000//
Chris Lattner7e708292002-06-25 16:13:24 +00007001Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +00007002 // If LCSSA is around, don't mess with Phi nodes
7003 if (mustPreserveAnalysisID(LCSSAID)) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +00007004
Owen Anderson7e057142006-07-10 22:03:18 +00007005 if (Value *V = PN.hasConstantValue())
7006 return ReplaceInstUsesWith(PN, V);
7007
7008 // If the only user of this instruction is a cast instruction, and all of the
7009 // incoming values are constants, change this PHI to merge together the casted
7010 // constants.
7011 if (PN.hasOneUse())
7012 if (CastInst *CI = dyn_cast<CastInst>(PN.use_back()))
7013 if (CI->getType() != PN.getType()) { // noop casts will be folded
7014 bool AllConstant = true;
7015 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
7016 if (!isa<Constant>(PN.getIncomingValue(i))) {
7017 AllConstant = false;
7018 break;
7019 }
7020 if (AllConstant) {
7021 // Make a new PHI with all casted values.
7022 PHINode *New = new PHINode(CI->getType(), PN.getName(), &PN);
7023 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
7024 Constant *OldArg = cast<Constant>(PN.getIncomingValue(i));
7025 New->addIncoming(ConstantExpr::getCast(OldArg, New->getType()),
7026 PN.getIncomingBlock(i));
7027 }
7028
7029 // Update the cast instruction.
7030 CI->setOperand(0, New);
7031 WorkList.push_back(CI); // revisit the cast instruction to fold.
7032 WorkList.push_back(New); // Make sure to revisit the new Phi
7033 return &PN; // PN is now dead!
7034 }
7035 }
7036
7037 // If all PHI operands are the same operation, pull them through the PHI,
7038 // reducing code size.
7039 if (isa<Instruction>(PN.getIncomingValue(0)) &&
7040 PN.getIncomingValue(0)->hasOneUse())
7041 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
7042 return Result;
7043
7044 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
7045 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
7046 // PHI)... break the cycle.
7047 if (PN.hasOneUse())
7048 if (PHINode *PU = dyn_cast<PHINode>(PN.use_back())) {
7049 std::set<PHINode*> PotentiallyDeadPHIs;
7050 PotentiallyDeadPHIs.insert(&PN);
7051 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
7052 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
7053 }
7054
Chris Lattner60921c92003-12-19 05:58:40 +00007055 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +00007056}
7057
Chris Lattner28977af2004-04-05 01:30:19 +00007058static Value *InsertSignExtendToPtrTy(Value *V, const Type *DTy,
7059 Instruction *InsertPoint,
7060 InstCombiner *IC) {
7061 unsigned PS = IC->getTargetData().getPointerSize();
7062 const Type *VTy = V->getType();
Chris Lattner28977af2004-04-05 01:30:19 +00007063 if (!VTy->isSigned() && VTy->getPrimitiveSize() < PS)
7064 // We must insert a cast to ensure we sign-extend.
Reid Spencer811b0cb2006-10-26 19:19:06 +00007065 V = IC->InsertCastBefore(V, VTy->getSignedVersion(), *InsertPoint);
7066 return IC->InsertCastBefore(V, DTy, *InsertPoint);
Chris Lattner28977af2004-04-05 01:30:19 +00007067}
7068
Chris Lattnera1be5662002-05-02 17:06:02 +00007069
Chris Lattner7e708292002-06-25 16:13:24 +00007070Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +00007071 Value *PtrOp = GEP.getOperand(0);
Chris Lattnerc54e2b82003-05-22 19:07:21 +00007072 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner7e708292002-06-25 16:13:24 +00007073 // If so, eliminate the noop.
Chris Lattnerc6bd1952004-02-22 05:25:17 +00007074 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +00007075 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +00007076
Chris Lattnere87597f2004-10-16 18:11:37 +00007077 if (isa<UndefValue>(GEP.getOperand(0)))
7078 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
7079
Chris Lattnerc6bd1952004-02-22 05:25:17 +00007080 bool HasZeroPointerIndex = false;
7081 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
7082 HasZeroPointerIndex = C->isNullValue();
7083
7084 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +00007085 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +00007086
Chris Lattner28977af2004-04-05 01:30:19 +00007087 // Eliminate unneeded casts for indices.
7088 bool MadeChange = false;
Chris Lattnercb69a4e2004-04-07 18:38:20 +00007089 gep_type_iterator GTI = gep_type_begin(GEP);
7090 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
7091 if (isa<SequentialType>(*GTI)) {
7092 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
7093 Value *Src = CI->getOperand(0);
7094 const Type *SrcTy = Src->getType();
7095 const Type *DestTy = CI->getType();
7096 if (Src->getType()->isInteger()) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00007097 if (SrcTy->getPrimitiveSizeInBits() ==
7098 DestTy->getPrimitiveSizeInBits()) {
Chris Lattnercb69a4e2004-04-07 18:38:20 +00007099 // We can always eliminate a cast from ulong or long to the other.
7100 // We can always eliminate a cast from uint to int or the other on
7101 // 32-bit pointer platforms.
Chris Lattner484d3cf2005-04-24 06:59:08 +00007102 if (DestTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()){
Chris Lattnercb69a4e2004-04-07 18:38:20 +00007103 MadeChange = true;
7104 GEP.setOperand(i, Src);
7105 }
7106 } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
7107 SrcTy->getPrimitiveSize() == 4) {
7108 // We can always eliminate a cast from int to [u]long. We can
7109 // eliminate a cast from uint to [u]long iff the target is a 32-bit
7110 // pointer target.
Misha Brukmanfd939082005-04-21 23:48:37 +00007111 if (SrcTy->isSigned() ||
Chris Lattner484d3cf2005-04-24 06:59:08 +00007112 SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
Chris Lattnercb69a4e2004-04-07 18:38:20 +00007113 MadeChange = true;
7114 GEP.setOperand(i, Src);
7115 }
Chris Lattner28977af2004-04-05 01:30:19 +00007116 }
7117 }
7118 }
Chris Lattnercb69a4e2004-04-07 18:38:20 +00007119 // If we are using a wider index than needed for this platform, shrink it
7120 // to what we need. If the incoming value needs a cast instruction,
7121 // insert it. This explicit cast can make subsequent optimizations more
7122 // obvious.
7123 Value *Op = GEP.getOperand(i);
7124 if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
Chris Lattner4f1134e2004-04-17 18:16:10 +00007125 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner67769e52004-07-20 01:48:15 +00007126 GEP.setOperand(i, ConstantExpr::getCast(C,
7127 TD->getIntPtrType()->getSignedVersion()));
Chris Lattner4f1134e2004-04-17 18:16:10 +00007128 MadeChange = true;
7129 } else {
Reid Spencer811b0cb2006-10-26 19:19:06 +00007130 Op = InsertCastBefore(Op, TD->getIntPtrType(), GEP);
Chris Lattnercb69a4e2004-04-07 18:38:20 +00007131 GEP.setOperand(i, Op);
7132 MadeChange = true;
7133 }
Chris Lattner67769e52004-07-20 01:48:15 +00007134
7135 // If this is a constant idx, make sure to canonicalize it to be a signed
7136 // operand, otherwise CSE and other optimizations are pessimized.
Reid Spencerb83eb642006-10-20 07:07:24 +00007137 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op))
7138 if (CUI->getType()->isUnsigned()) {
7139 GEP.setOperand(i,
7140 ConstantExpr::getCast(CUI, CUI->getType()->getSignedVersion()));
7141 MadeChange = true;
7142 }
Chris Lattner28977af2004-04-05 01:30:19 +00007143 }
7144 if (MadeChange) return &GEP;
7145
Chris Lattner90ac28c2002-08-02 19:29:35 +00007146 // Combine Indices - If the source pointer to this getelementptr instruction
7147 // is a getelementptr instruction, combine the indices of the two
7148 // getelementptr instructions into a single instruction.
7149 //
Chris Lattnerebd985c2004-03-25 22:59:29 +00007150 std::vector<Value*> SrcGEPOperands;
Chris Lattner574da9b2005-01-13 20:14:25 +00007151 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattnerebd985c2004-03-25 22:59:29 +00007152 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
Chris Lattnerebd985c2004-03-25 22:59:29 +00007153
7154 if (!SrcGEPOperands.empty()) {
Chris Lattner620ce142004-05-07 22:09:22 +00007155 // Note that if our source is a gep chain itself that we wait for that
7156 // chain to be resolved before we perform this transformation. This
7157 // avoids us creating a TON of code in some cases.
7158 //
7159 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
7160 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
7161 return 0; // Wait until our source is folded to completion.
7162
Chris Lattner90ac28c2002-08-02 19:29:35 +00007163 std::vector<Value *> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +00007164
7165 // Find out whether the last index in the source GEP is a sequential idx.
7166 bool EndsWithSequential = false;
7167 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
7168 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +00007169 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +00007170
Chris Lattner90ac28c2002-08-02 19:29:35 +00007171 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +00007172 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +00007173 // Replace: gep (gep %P, long B), long A, ...
7174 // With: T = long A+B; gep %P, T, ...
7175 //
Chris Lattner620ce142004-05-07 22:09:22 +00007176 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner28977af2004-04-05 01:30:19 +00007177 if (SO1 == Constant::getNullValue(SO1->getType())) {
7178 Sum = GO1;
7179 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
7180 Sum = SO1;
7181 } else {
7182 // If they aren't the same type, convert both to an integer of the
7183 // target's pointer size.
7184 if (SO1->getType() != GO1->getType()) {
7185 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
7186 SO1 = ConstantExpr::getCast(SO1C, GO1->getType());
7187 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
7188 GO1 = ConstantExpr::getCast(GO1C, SO1->getType());
7189 } else {
7190 unsigned PS = TD->getPointerSize();
Chris Lattner28977af2004-04-05 01:30:19 +00007191 if (SO1->getType()->getPrimitiveSize() == PS) {
7192 // Convert GO1 to SO1's type.
7193 GO1 = InsertSignExtendToPtrTy(GO1, SO1->getType(), &GEP, this);
7194
7195 } else if (GO1->getType()->getPrimitiveSize() == PS) {
7196 // Convert SO1 to GO1's type.
7197 SO1 = InsertSignExtendToPtrTy(SO1, GO1->getType(), &GEP, this);
7198 } else {
7199 const Type *PT = TD->getIntPtrType();
7200 SO1 = InsertSignExtendToPtrTy(SO1, PT, &GEP, this);
7201 GO1 = InsertSignExtendToPtrTy(GO1, PT, &GEP, this);
7202 }
7203 }
7204 }
Chris Lattner620ce142004-05-07 22:09:22 +00007205 if (isa<Constant>(SO1) && isa<Constant>(GO1))
7206 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
7207 else {
Chris Lattner48595f12004-06-10 02:07:29 +00007208 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
7209 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner620ce142004-05-07 22:09:22 +00007210 }
Chris Lattner28977af2004-04-05 01:30:19 +00007211 }
Chris Lattner620ce142004-05-07 22:09:22 +00007212
7213 // Recycle the GEP we already have if possible.
7214 if (SrcGEPOperands.size() == 2) {
7215 GEP.setOperand(0, SrcGEPOperands[0]);
7216 GEP.setOperand(1, Sum);
7217 return &GEP;
7218 } else {
7219 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
7220 SrcGEPOperands.end()-1);
7221 Indices.push_back(Sum);
7222 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
7223 }
Misha Brukmanfd939082005-04-21 23:48:37 +00007224 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +00007225 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanfd939082005-04-21 23:48:37 +00007226 SrcGEPOperands.size() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +00007227 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerebd985c2004-03-25 22:59:29 +00007228 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
7229 SrcGEPOperands.end());
Chris Lattner90ac28c2002-08-02 19:29:35 +00007230 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
7231 }
7232
7233 if (!Indices.empty())
Chris Lattnerebd985c2004-03-25 22:59:29 +00007234 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
Chris Lattner9b761232002-08-17 22:21:59 +00007235
Chris Lattner620ce142004-05-07 22:09:22 +00007236 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattner9b761232002-08-17 22:21:59 +00007237 // GEP of global variable. If all of the indices for this GEP are
7238 // constants, we can promote this to a constexpr instead of an instruction.
7239
7240 // Scan for nonconstants...
7241 std::vector<Constant*> Indices;
7242 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
7243 for (; I != E && isa<Constant>(*I); ++I)
7244 Indices.push_back(cast<Constant>(*I));
7245
7246 if (I == E) { // If they are all constants...
Chris Lattner9db07b92004-07-18 18:59:44 +00007247 Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
Chris Lattner9b761232002-08-17 22:21:59 +00007248
7249 // Replace all uses of the GEP with the new constexpr...
7250 return ReplaceInstUsesWith(GEP, CE);
7251 }
Chris Lattnereed48272005-09-13 00:40:14 +00007252 } else if (Value *X = isCast(PtrOp)) { // Is the operand a cast?
7253 if (!isa<PointerType>(X->getType())) {
7254 // Not interesting. Source pointer must be a cast from pointer.
7255 } else if (HasZeroPointerIndex) {
7256 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
7257 // into : GEP [10 x ubyte]* X, long 0, ...
7258 //
7259 // This occurs when the program declares an array extern like "int X[];"
7260 //
7261 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
7262 const PointerType *XTy = cast<PointerType>(X->getType());
7263 if (const ArrayType *XATy =
7264 dyn_cast<ArrayType>(XTy->getElementType()))
7265 if (const ArrayType *CATy =
7266 dyn_cast<ArrayType>(CPTy->getElementType()))
7267 if (CATy->getElementType() == XATy->getElementType()) {
7268 // At this point, we know that the cast source type is a pointer
7269 // to an array of the same type as the destination pointer
7270 // array. Because the array type is never stepped over (there
7271 // is a leading zero) we can fold the cast into this GEP.
7272 GEP.setOperand(0, X);
7273 return &GEP;
7274 }
7275 } else if (GEP.getNumOperands() == 2) {
7276 // Transform things like:
Chris Lattner7835cdd2005-09-13 18:36:04 +00007277 // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
7278 // into: %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
Chris Lattnereed48272005-09-13 00:40:14 +00007279 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
7280 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
7281 if (isa<ArrayType>(SrcElTy) &&
7282 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
7283 TD->getTypeSize(ResElTy)) {
7284 Value *V = InsertNewInstBefore(
7285 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
7286 GEP.getOperand(1), GEP.getName()), GEP);
7287 return new CastInst(V, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +00007288 }
Chris Lattner7835cdd2005-09-13 18:36:04 +00007289
7290 // Transform things like:
7291 // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
7292 // (where tmp = 8*tmp2) into:
7293 // getelementptr [100 x double]* %arr, int 0, int %tmp.2
7294
7295 if (isa<ArrayType>(SrcElTy) &&
7296 (ResElTy == Type::SByteTy || ResElTy == Type::UByteTy)) {
7297 uint64_t ArrayEltSize =
7298 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
7299
7300 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
7301 // allow either a mul, shift, or constant here.
7302 Value *NewIdx = 0;
7303 ConstantInt *Scale = 0;
7304 if (ArrayEltSize == 1) {
7305 NewIdx = GEP.getOperand(1);
7306 Scale = ConstantInt::get(NewIdx->getType(), 1);
7307 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattner6e2f8432005-09-14 17:32:56 +00007308 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +00007309 Scale = CI;
7310 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
7311 if (Inst->getOpcode() == Instruction::Shl &&
7312 isa<ConstantInt>(Inst->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00007313 unsigned ShAmt =
7314 cast<ConstantInt>(Inst->getOperand(1))->getZExtValue();
Chris Lattner7835cdd2005-09-13 18:36:04 +00007315 if (Inst->getType()->isSigned())
Reid Spencerb83eb642006-10-20 07:07:24 +00007316 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmt);
Chris Lattner7835cdd2005-09-13 18:36:04 +00007317 else
Reid Spencerb83eb642006-10-20 07:07:24 +00007318 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmt);
Chris Lattner7835cdd2005-09-13 18:36:04 +00007319 NewIdx = Inst->getOperand(0);
7320 } else if (Inst->getOpcode() == Instruction::Mul &&
7321 isa<ConstantInt>(Inst->getOperand(1))) {
7322 Scale = cast<ConstantInt>(Inst->getOperand(1));
7323 NewIdx = Inst->getOperand(0);
7324 }
7325 }
7326
7327 // If the index will be to exactly the right offset with the scale taken
7328 // out, perform the transformation.
Reid Spencerb83eb642006-10-20 07:07:24 +00007329 if (Scale && Scale->getZExtValue() % ArrayEltSize == 0) {
7330 if (ConstantInt *C = dyn_cast<ConstantInt>(Scale))
7331 Scale = ConstantInt::get(Scale->getType(),
7332 Scale->getZExtValue() / ArrayEltSize);
7333 if (Scale->getZExtValue() != 1) {
Chris Lattner7835cdd2005-09-13 18:36:04 +00007334 Constant *C = ConstantExpr::getCast(Scale, NewIdx->getType());
7335 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
7336 NewIdx = InsertNewInstBefore(Sc, GEP);
7337 }
7338
7339 // Insert the new GEP instruction.
7340 Instruction *Idx =
7341 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
7342 NewIdx, GEP.getName());
7343 Idx = InsertNewInstBefore(Idx, GEP);
7344 return new CastInst(Idx, GEP.getType());
7345 }
7346 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +00007347 }
Chris Lattner8a2a3112001-12-14 16:52:21 +00007348 }
7349
Chris Lattner8a2a3112001-12-14 16:52:21 +00007350 return 0;
7351}
7352
Chris Lattner0864acf2002-11-04 16:18:53 +00007353Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
7354 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
7355 if (AI.isArrayAllocation()) // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +00007356 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
7357 const Type *NewTy =
7358 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattner0006bd72002-11-09 00:49:43 +00007359 AllocationInst *New = 0;
Chris Lattner0864acf2002-11-04 16:18:53 +00007360
7361 // Create and insert the replacement instruction...
7362 if (isa<MallocInst>(AI))
Nate Begeman14b05292005-11-05 09:21:28 +00007363 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +00007364 else {
7365 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman14b05292005-11-05 09:21:28 +00007366 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +00007367 }
Chris Lattner7c881df2004-03-19 06:08:10 +00007368
7369 InsertNewInstBefore(New, AI);
Misha Brukmanfd939082005-04-21 23:48:37 +00007370
Chris Lattner0864acf2002-11-04 16:18:53 +00007371 // Scan to the end of the allocation instructions, to skip over a block of
7372 // allocas if possible...
7373 //
7374 BasicBlock::iterator It = New;
7375 while (isa<AllocationInst>(*It)) ++It;
7376
7377 // Now that I is pointing to the first non-allocation-inst in the block,
7378 // insert our getelementptr instruction...
7379 //
Chris Lattner693787a2005-05-04 19:10:26 +00007380 Value *NullIdx = Constant::getNullValue(Type::IntTy);
7381 Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
7382 New->getName()+".sub", It);
Chris Lattner0864acf2002-11-04 16:18:53 +00007383
7384 // Now make everything use the getelementptr instead of the original
7385 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +00007386 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +00007387 } else if (isa<UndefValue>(AI.getArraySize())) {
7388 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +00007389 }
Chris Lattner7c881df2004-03-19 06:08:10 +00007390
7391 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
7392 // Note that we only do this for alloca's, because malloc should allocate and
7393 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanfd939082005-04-21 23:48:37 +00007394 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Chris Lattnercf27afb2004-07-02 22:55:47 +00007395 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattner7c881df2004-03-19 06:08:10 +00007396 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
7397
Chris Lattner0864acf2002-11-04 16:18:53 +00007398 return 0;
7399}
7400
Chris Lattner67b1e1b2003-12-07 01:24:23 +00007401Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
7402 Value *Op = FI.getOperand(0);
7403
7404 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
7405 if (CastInst *CI = dyn_cast<CastInst>(Op))
7406 if (isa<PointerType>(CI->getOperand(0)->getType())) {
7407 FI.setOperand(0, CI->getOperand(0));
7408 return &FI;
7409 }
7410
Chris Lattner17be6352004-10-18 02:59:09 +00007411 // free undef -> unreachable.
7412 if (isa<UndefValue>(Op)) {
7413 // Insert a new store to null because we cannot modify the CFG here.
Chris Lattner47811b72006-09-28 23:35:22 +00007414 new StoreInst(ConstantBool::getTrue(),
Chris Lattner17be6352004-10-18 02:59:09 +00007415 UndefValue::get(PointerType::get(Type::BoolTy)), &FI);
7416 return EraseInstFromFunction(FI);
7417 }
7418
Chris Lattner6160e852004-02-28 04:57:37 +00007419 // If we have 'free null' delete the instruction. This can happen in stl code
7420 // when lots of inlining happens.
Chris Lattner17be6352004-10-18 02:59:09 +00007421 if (isa<ConstantPointerNull>(Op))
Chris Lattner7bcc0e72004-02-28 05:22:00 +00007422 return EraseInstFromFunction(FI);
Chris Lattner6160e852004-02-28 04:57:37 +00007423
Chris Lattner67b1e1b2003-12-07 01:24:23 +00007424 return 0;
7425}
7426
7427
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00007428/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Chris Lattnerb89e0712004-07-13 01:49:43 +00007429static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
7430 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +00007431 Value *CastOp = CI->getOperand(0);
Chris Lattnerb89e0712004-07-13 01:49:43 +00007432
7433 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +00007434 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattnerb89e0712004-07-13 01:49:43 +00007435 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +00007436
Chris Lattnera1c35382006-04-02 05:37:12 +00007437 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
7438 isa<PackedType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +00007439 // If the source is an array, the code below will not succeed. Check to
7440 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
7441 // constants.
7442 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
7443 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
7444 if (ASrcTy->getNumElements() != 0) {
7445 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
7446 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
7447 SrcTy = cast<PointerType>(CastOp->getType());
7448 SrcPTy = SrcTy->getElementType();
7449 }
7450
Chris Lattnera1c35382006-04-02 05:37:12 +00007451 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
7452 isa<PackedType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +00007453 // Do not allow turning this into a load of an integer, which is then
7454 // casted to a pointer, this pessimizes pointer analysis a lot.
7455 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Misha Brukmanfd939082005-04-21 23:48:37 +00007456 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattnerf9527852005-01-31 04:50:46 +00007457 IC.getTargetData().getTypeSize(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +00007458
Chris Lattnerf9527852005-01-31 04:50:46 +00007459 // Okay, we are casting from one integer or pointer type to another of
7460 // the same size. Instead of casting the pointer before the load, cast
7461 // the result of the loaded value.
7462 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
7463 CI->getName(),
7464 LI.isVolatile()),LI);
7465 // Now cast the result of the load.
7466 return new CastInst(NewLoad, LI.getType());
7467 }
Chris Lattnerb89e0712004-07-13 01:49:43 +00007468 }
7469 }
7470 return 0;
7471}
7472
Chris Lattnerc10aced2004-09-19 18:43:46 +00007473/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattner8a375202004-09-19 19:18:10 +00007474/// from this value cannot trap. If it is not obviously safe to load from the
7475/// specified pointer, we do a quick local scan of the basic block containing
7476/// ScanFrom, to determine if the address is already accessed.
7477static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
7478 // If it is an alloca or global variable, it is always safe to load from.
7479 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
7480
7481 // Otherwise, be a little bit agressive by scanning the local block where we
7482 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00007483 // from/to. If so, the previous load or store would have already trapped,
7484 // so there is no harm doing an extra load (also, CSE will later eliminate
7485 // the load entirely).
Chris Lattner8a375202004-09-19 19:18:10 +00007486 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
7487
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00007488 while (BBI != E) {
Chris Lattner8a375202004-09-19 19:18:10 +00007489 --BBI;
7490
7491 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
7492 if (LI->getOperand(0) == V) return true;
7493 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
7494 if (SI->getOperand(1) == V) return true;
Misha Brukmanfd939082005-04-21 23:48:37 +00007495
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00007496 }
Chris Lattner8a375202004-09-19 19:18:10 +00007497 return false;
Chris Lattnerc10aced2004-09-19 18:43:46 +00007498}
7499
Chris Lattner833b8a42003-06-26 05:06:25 +00007500Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
7501 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +00007502
Chris Lattner37366c12005-05-01 04:24:53 +00007503 // load (cast X) --> cast (load X) iff safe
7504 if (CastInst *CI = dyn_cast<CastInst>(Op))
7505 if (Instruction *Res = InstCombineLoadCast(*this, LI))
7506 return Res;
7507
7508 // None of the following transforms are legal for volatile loads.
7509 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +00007510
Chris Lattner62f254d2005-09-12 22:00:15 +00007511 if (&LI.getParent()->front() != &LI) {
7512 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattner9c1f0fd2005-09-12 22:21:03 +00007513 // If the instruction immediately before this is a store to the same
7514 // address, do a simple form of store->load forwarding.
Chris Lattner62f254d2005-09-12 22:00:15 +00007515 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
7516 if (SI->getOperand(1) == LI.getOperand(0))
7517 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattner9c1f0fd2005-09-12 22:21:03 +00007518 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
7519 if (LIB->getOperand(0) == LI.getOperand(0))
7520 return ReplaceInstUsesWith(LI, LIB);
Chris Lattner62f254d2005-09-12 22:00:15 +00007521 }
Chris Lattner37366c12005-05-01 04:24:53 +00007522
7523 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
7524 if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
7525 isa<UndefValue>(GEPI->getOperand(0))) {
7526 // Insert a new store to null instruction before the load to indicate
7527 // that this code is not reachable. We do this instead of inserting
7528 // an unreachable instruction directly because we cannot modify the
7529 // CFG.
7530 new StoreInst(UndefValue::get(LI.getType()),
7531 Constant::getNullValue(Op->getType()), &LI);
7532 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
7533 }
7534
Chris Lattnere87597f2004-10-16 18:11:37 +00007535 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner37366c12005-05-01 04:24:53 +00007536 // load null/undef -> undef
7537 if ((C->isNullValue() || isa<UndefValue>(C))) {
Chris Lattner17be6352004-10-18 02:59:09 +00007538 // Insert a new store to null instruction before the load to indicate that
7539 // this code is not reachable. We do this instead of inserting an
7540 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattner37366c12005-05-01 04:24:53 +00007541 new StoreInst(UndefValue::get(LI.getType()),
7542 Constant::getNullValue(Op->getType()), &LI);
Chris Lattnere87597f2004-10-16 18:11:37 +00007543 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner17be6352004-10-18 02:59:09 +00007544 }
Chris Lattner833b8a42003-06-26 05:06:25 +00007545
Chris Lattnere87597f2004-10-16 18:11:37 +00007546 // Instcombine load (constant global) into the value loaded.
7547 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
7548 if (GV->isConstant() && !GV->isExternal())
7549 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +00007550
Chris Lattnere87597f2004-10-16 18:11:37 +00007551 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
7552 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
7553 if (CE->getOpcode() == Instruction::GetElementPtr) {
7554 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
7555 if (GV->isConstant() && !GV->isExternal())
Chris Lattner363f2a22005-09-26 05:28:06 +00007556 if (Constant *V =
7557 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattnere87597f2004-10-16 18:11:37 +00007558 return ReplaceInstUsesWith(LI, V);
Chris Lattner37366c12005-05-01 04:24:53 +00007559 if (CE->getOperand(0)->isNullValue()) {
7560 // Insert a new store to null instruction before the load to indicate
7561 // that this code is not reachable. We do this instead of inserting
7562 // an unreachable instruction directly because we cannot modify the
7563 // CFG.
7564 new StoreInst(UndefValue::get(LI.getType()),
7565 Constant::getNullValue(Op->getType()), &LI);
7566 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
7567 }
7568
Chris Lattnere87597f2004-10-16 18:11:37 +00007569 } else if (CE->getOpcode() == Instruction::Cast) {
7570 if (Instruction *Res = InstCombineLoadCast(*this, LI))
7571 return Res;
7572 }
7573 }
Chris Lattnerf499eac2004-04-08 20:39:49 +00007574
Chris Lattner37366c12005-05-01 04:24:53 +00007575 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +00007576 // Change select and PHI nodes to select values instead of addresses: this
7577 // helps alias analysis out a lot, allows many others simplifications, and
7578 // exposes redundancy in the code.
7579 //
7580 // Note that we cannot do the transformation unless we know that the
7581 // introduced loads cannot trap! Something like this is valid as long as
7582 // the condition is always false: load (select bool %C, int* null, int* %G),
7583 // but it would not be valid if we transformed it to load from null
7584 // unconditionally.
7585 //
7586 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
7587 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +00007588 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
7589 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerc10aced2004-09-19 18:43:46 +00007590 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner79f0c8e2004-09-20 10:15:10 +00007591 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +00007592 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner79f0c8e2004-09-20 10:15:10 +00007593 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +00007594 return new SelectInst(SI->getCondition(), V1, V2);
7595 }
7596
Chris Lattner684fe212004-09-23 15:46:00 +00007597 // load (select (cond, null, P)) -> load P
7598 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
7599 if (C->isNullValue()) {
7600 LI.setOperand(0, SI->getOperand(2));
7601 return &LI;
7602 }
7603
7604 // load (select (cond, P, null)) -> load P
7605 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
7606 if (C->isNullValue()) {
7607 LI.setOperand(0, SI->getOperand(1));
7608 return &LI;
7609 }
Chris Lattnerc10aced2004-09-19 18:43:46 +00007610 }
7611 }
Chris Lattner833b8a42003-06-26 05:06:25 +00007612 return 0;
7613}
7614
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00007615/// InstCombineStoreToCast - Fold 'store V, (cast P)' -> store (cast V), P'
7616/// when possible.
7617static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
7618 User *CI = cast<User>(SI.getOperand(1));
7619 Value *CastOp = CI->getOperand(0);
7620
7621 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
7622 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
7623 const Type *SrcPTy = SrcTy->getElementType();
7624
7625 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
7626 // If the source is an array, the code below will not succeed. Check to
7627 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
7628 // constants.
7629 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
7630 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
7631 if (ASrcTy->getNumElements() != 0) {
7632 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
7633 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
7634 SrcTy = cast<PointerType>(CastOp->getType());
7635 SrcPTy = SrcTy->getElementType();
7636 }
7637
7638 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
Misha Brukmanfd939082005-04-21 23:48:37 +00007639 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00007640 IC.getTargetData().getTypeSize(DestPTy)) {
7641
7642 // Okay, we are casting from one integer or pointer type to another of
7643 // the same size. Instead of casting the pointer before the store, cast
7644 // the value to be stored.
7645 Value *NewCast;
7646 if (Constant *C = dyn_cast<Constant>(SI.getOperand(0)))
7647 NewCast = ConstantExpr::getCast(C, SrcPTy);
7648 else
7649 NewCast = IC.InsertNewInstBefore(new CastInst(SI.getOperand(0),
7650 SrcPTy,
7651 SI.getOperand(0)->getName()+".c"), SI);
7652
7653 return new StoreInst(NewCast, CastOp);
7654 }
7655 }
7656 }
7657 return 0;
7658}
7659
Chris Lattner2f503e62005-01-31 05:36:43 +00007660Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
7661 Value *Val = SI.getOperand(0);
7662 Value *Ptr = SI.getOperand(1);
7663
7664 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner9ca96412006-02-08 03:25:32 +00007665 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +00007666 ++NumCombined;
7667 return 0;
7668 }
7669
Chris Lattner9ca96412006-02-08 03:25:32 +00007670 // Do really simple DSE, to catch cases where there are several consequtive
7671 // stores to the same location, separated by a few arithmetic operations. This
7672 // situation often occurs with bitfield accesses.
7673 BasicBlock::iterator BBI = &SI;
7674 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
7675 --ScanInsts) {
7676 --BBI;
7677
7678 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
7679 // Prev store isn't volatile, and stores to the same location?
7680 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
7681 ++NumDeadStore;
7682 ++BBI;
7683 EraseInstFromFunction(*PrevSI);
7684 continue;
7685 }
7686 break;
7687 }
7688
Chris Lattnerb4db97f2006-05-26 19:19:20 +00007689 // If this is a load, we have to stop. However, if the loaded value is from
7690 // the pointer we're loading and is producing the pointer we're storing,
7691 // then *this* store is dead (X = load P; store X -> P).
7692 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
7693 if (LI == Val && LI->getOperand(0) == Ptr) {
7694 EraseInstFromFunction(SI);
7695 ++NumCombined;
7696 return 0;
7697 }
7698 // Otherwise, this is a load from some other location. Stores before it
7699 // may not be dead.
7700 break;
7701 }
7702
Chris Lattner9ca96412006-02-08 03:25:32 +00007703 // Don't skip over loads or things that can modify memory.
Chris Lattnerb4db97f2006-05-26 19:19:20 +00007704 if (BBI->mayWriteToMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +00007705 break;
7706 }
7707
7708
7709 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +00007710
7711 // store X, null -> turns into 'unreachable' in SimplifyCFG
7712 if (isa<ConstantPointerNull>(Ptr)) {
7713 if (!isa<UndefValue>(Val)) {
7714 SI.setOperand(0, UndefValue::get(Val->getType()));
7715 if (Instruction *U = dyn_cast<Instruction>(Val))
7716 WorkList.push_back(U); // Dropped a use.
7717 ++NumCombined;
7718 }
7719 return 0; // Do not modify these!
7720 }
7721
7722 // store undef, Ptr -> noop
7723 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +00007724 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +00007725 ++NumCombined;
7726 return 0;
7727 }
7728
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00007729 // If the pointer destination is a cast, see if we can fold the cast into the
7730 // source instead.
7731 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
7732 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
7733 return Res;
7734 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
7735 if (CE->getOpcode() == Instruction::Cast)
7736 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
7737 return Res;
7738
Chris Lattner408902b2005-09-12 23:23:25 +00007739
7740 // If this store is the last instruction in the basic block, and if the block
7741 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner9ca96412006-02-08 03:25:32 +00007742 BBI = &SI; ++BBI;
Chris Lattner408902b2005-09-12 23:23:25 +00007743 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
7744 if (BI->isUnconditional()) {
7745 // Check to see if the successor block has exactly two incoming edges. If
7746 // so, see if the other predecessor contains a store to the same location.
7747 // if so, insert a PHI node (if needed) and move the stores down.
7748 BasicBlock *Dest = BI->getSuccessor(0);
7749
7750 pred_iterator PI = pred_begin(Dest);
7751 BasicBlock *Other = 0;
7752 if (*PI != BI->getParent())
7753 Other = *PI;
7754 ++PI;
7755 if (PI != pred_end(Dest)) {
7756 if (*PI != BI->getParent())
7757 if (Other)
7758 Other = 0;
7759 else
7760 Other = *PI;
7761 if (++PI != pred_end(Dest))
7762 Other = 0;
7763 }
7764 if (Other) { // If only one other pred...
7765 BBI = Other->getTerminator();
7766 // Make sure this other block ends in an unconditional branch and that
7767 // there is an instruction before the branch.
7768 if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
7769 BBI != Other->begin()) {
7770 --BBI;
7771 StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
7772
7773 // If this instruction is a store to the same location.
7774 if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
7775 // Okay, we know we can perform this transformation. Insert a PHI
7776 // node now if we need it.
7777 Value *MergedVal = OtherStore->getOperand(0);
7778 if (MergedVal != SI.getOperand(0)) {
7779 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
7780 PN->reserveOperandSpace(2);
7781 PN->addIncoming(SI.getOperand(0), SI.getParent());
7782 PN->addIncoming(OtherStore->getOperand(0), Other);
7783 MergedVal = InsertNewInstBefore(PN, Dest->front());
7784 }
7785
7786 // Advance to a place where it is safe to insert the new store and
7787 // insert it.
7788 BBI = Dest->begin();
7789 while (isa<PHINode>(BBI)) ++BBI;
7790 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
7791 OtherStore->isVolatile()), *BBI);
7792
7793 // Nuke the old stores.
Chris Lattner9ca96412006-02-08 03:25:32 +00007794 EraseInstFromFunction(SI);
7795 EraseInstFromFunction(*OtherStore);
Chris Lattner408902b2005-09-12 23:23:25 +00007796 ++NumCombined;
7797 return 0;
7798 }
7799 }
7800 }
7801 }
7802
Chris Lattner2f503e62005-01-31 05:36:43 +00007803 return 0;
7804}
7805
7806
Chris Lattnerc4d10eb2003-06-04 04:46:00 +00007807Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
7808 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +00007809 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00007810 BasicBlock *TrueDest;
7811 BasicBlock *FalseDest;
7812 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
7813 !isa<Constant>(X)) {
7814 // Swap Destinations and condition...
7815 BI.setCondition(X);
7816 BI.setSuccessor(0, FalseDest);
7817 BI.setSuccessor(1, TrueDest);
7818 return &BI;
7819 }
7820
7821 // Cannonicalize setne -> seteq
7822 Instruction::BinaryOps Op; Value *Y;
7823 if (match(&BI, m_Br(m_SetCond(Op, m_Value(X), m_Value(Y)),
7824 TrueDest, FalseDest)))
7825 if ((Op == Instruction::SetNE || Op == Instruction::SetLE ||
7826 Op == Instruction::SetGE) && BI.getCondition()->hasOneUse()) {
7827 SetCondInst *I = cast<SetCondInst>(BI.getCondition());
7828 std::string Name = I->getName(); I->setName("");
7829 Instruction::BinaryOps NewOpcode = SetCondInst::getInverseCondition(Op);
7830 Value *NewSCC = BinaryOperator::create(NewOpcode, X, Y, Name, I);
Chris Lattner40f5d702003-06-04 05:10:11 +00007831 // Swap Destinations and condition...
Chris Lattneracd1f0f2004-07-30 07:50:03 +00007832 BI.setCondition(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +00007833 BI.setSuccessor(0, FalseDest);
7834 BI.setSuccessor(1, TrueDest);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00007835 removeFromWorkList(I);
7836 I->getParent()->getInstList().erase(I);
7837 WorkList.push_back(cast<Instruction>(NewSCC));
Chris Lattner40f5d702003-06-04 05:10:11 +00007838 return &BI;
7839 }
Misha Brukmanfd939082005-04-21 23:48:37 +00007840
Chris Lattnerc4d10eb2003-06-04 04:46:00 +00007841 return 0;
7842}
Chris Lattner0864acf2002-11-04 16:18:53 +00007843
Chris Lattner46238a62004-07-03 00:26:11 +00007844Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
7845 Value *Cond = SI.getCondition();
7846 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
7847 if (I->getOpcode() == Instruction::Add)
7848 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7849 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
7850 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattnere87597f2004-10-16 18:11:37 +00007851 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +00007852 AddRHS));
7853 SI.setOperand(0, I->getOperand(0));
7854 WorkList.push_back(I);
7855 return &SI;
7856 }
7857 }
7858 return 0;
7859}
7860
Chris Lattner220b0cf2006-03-05 00:22:33 +00007861/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
7862/// is to leave as a vector operation.
7863static bool CheapToScalarize(Value *V, bool isConstant) {
7864 if (isa<ConstantAggregateZero>(V))
7865 return true;
7866 if (ConstantPacked *C = dyn_cast<ConstantPacked>(V)) {
7867 if (isConstant) return true;
7868 // If all elts are the same, we can extract.
7869 Constant *Op0 = C->getOperand(0);
7870 for (unsigned i = 1; i < C->getNumOperands(); ++i)
7871 if (C->getOperand(i) != Op0)
7872 return false;
7873 return true;
7874 }
7875 Instruction *I = dyn_cast<Instruction>(V);
7876 if (!I) return false;
7877
7878 // Insert element gets simplified to the inserted element or is deleted if
7879 // this is constant idx extract element and its a constant idx insertelt.
7880 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
7881 isa<ConstantInt>(I->getOperand(2)))
7882 return true;
7883 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
7884 return true;
7885 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
7886 if (BO->hasOneUse() &&
7887 (CheapToScalarize(BO->getOperand(0), isConstant) ||
7888 CheapToScalarize(BO->getOperand(1), isConstant)))
7889 return true;
7890
7891 return false;
7892}
7893
Chris Lattner863bcff2006-05-25 23:48:38 +00007894/// getShuffleMask - Read and decode a shufflevector mask. It turns undef
7895/// elements into values that are larger than the #elts in the input.
7896static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
7897 unsigned NElts = SVI->getType()->getNumElements();
7898 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
7899 return std::vector<unsigned>(NElts, 0);
7900 if (isa<UndefValue>(SVI->getOperand(2)))
7901 return std::vector<unsigned>(NElts, 2*NElts);
7902
7903 std::vector<unsigned> Result;
7904 const ConstantPacked *CP = cast<ConstantPacked>(SVI->getOperand(2));
7905 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
7906 if (isa<UndefValue>(CP->getOperand(i)))
7907 Result.push_back(NElts*2); // undef -> 8
7908 else
Reid Spencerb83eb642006-10-20 07:07:24 +00007909 Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
Chris Lattner863bcff2006-05-25 23:48:38 +00007910 return Result;
7911}
7912
Chris Lattner6e6b0da2006-03-31 23:01:56 +00007913/// FindScalarElement - Given a vector and an element number, see if the scalar
7914/// value is already around as a register, for example if it were inserted then
7915/// extracted from the vector.
7916static Value *FindScalarElement(Value *V, unsigned EltNo) {
7917 assert(isa<PackedType>(V->getType()) && "Not looking at a vector?");
7918 const PackedType *PTy = cast<PackedType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +00007919 unsigned Width = PTy->getNumElements();
7920 if (EltNo >= Width) // Out of range access.
Chris Lattner6e6b0da2006-03-31 23:01:56 +00007921 return UndefValue::get(PTy->getElementType());
7922
7923 if (isa<UndefValue>(V))
7924 return UndefValue::get(PTy->getElementType());
7925 else if (isa<ConstantAggregateZero>(V))
7926 return Constant::getNullValue(PTy->getElementType());
7927 else if (ConstantPacked *CP = dyn_cast<ConstantPacked>(V))
7928 return CP->getOperand(EltNo);
7929 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
7930 // If this is an insert to a variable element, we don't know what it is.
Reid Spencerb83eb642006-10-20 07:07:24 +00007931 if (!isa<ConstantInt>(III->getOperand(2)))
7932 return 0;
7933 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner6e6b0da2006-03-31 23:01:56 +00007934
7935 // If this is an insert to the element we are looking for, return the
7936 // inserted value.
Reid Spencerb83eb642006-10-20 07:07:24 +00007937 if (EltNo == IIElt)
7938 return III->getOperand(1);
Chris Lattner6e6b0da2006-03-31 23:01:56 +00007939
7940 // Otherwise, the insertelement doesn't modify the value, recurse on its
7941 // vector input.
7942 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner389a6f52006-04-10 23:06:36 +00007943 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Chris Lattner863bcff2006-05-25 23:48:38 +00007944 unsigned InEl = getShuffleMask(SVI)[EltNo];
7945 if (InEl < Width)
7946 return FindScalarElement(SVI->getOperand(0), InEl);
7947 else if (InEl < Width*2)
7948 return FindScalarElement(SVI->getOperand(1), InEl - Width);
7949 else
7950 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +00007951 }
7952
7953 // Otherwise, we don't know.
7954 return 0;
7955}
7956
Robert Bocchino1d7456d2006-01-13 22:48:06 +00007957Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Chris Lattner6e6b0da2006-03-31 23:01:56 +00007958
Chris Lattner1f13c882006-03-31 18:25:14 +00007959 // If packed val is undef, replace extract with scalar undef.
7960 if (isa<UndefValue>(EI.getOperand(0)))
7961 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
7962
7963 // If packed val is constant 0, replace extract with scalar 0.
7964 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
7965 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
7966
Robert Bocchino1d7456d2006-01-13 22:48:06 +00007967 if (ConstantPacked *C = dyn_cast<ConstantPacked>(EI.getOperand(0))) {
7968 // If packed val is constant with uniform operands, replace EI
7969 // with that operand
Chris Lattner220b0cf2006-03-05 00:22:33 +00007970 Constant *op0 = C->getOperand(0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +00007971 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +00007972 if (C->getOperand(i) != op0) {
7973 op0 = 0;
7974 break;
7975 }
7976 if (op0)
7977 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +00007978 }
Chris Lattner220b0cf2006-03-05 00:22:33 +00007979
Chris Lattner6e6b0da2006-03-31 23:01:56 +00007980 // If extracting a specified index from the vector, see if we can recursively
7981 // find a previously computed scalar that was inserted into the vector.
Reid Spencerb83eb642006-10-20 07:07:24 +00007982 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner867b99f2006-10-05 06:55:50 +00007983 // This instruction only demands the single element from the input vector.
7984 // If the input vector has a single use, simplify it based on this use
7985 // property.
Reid Spencerb83eb642006-10-20 07:07:24 +00007986 uint64_t IndexVal = IdxC->getZExtValue();
Chris Lattner867b99f2006-10-05 06:55:50 +00007987 if (EI.getOperand(0)->hasOneUse()) {
7988 uint64_t UndefElts;
7989 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Reid Spencerb83eb642006-10-20 07:07:24 +00007990 1 << IndexVal,
Chris Lattner867b99f2006-10-05 06:55:50 +00007991 UndefElts)) {
7992 EI.setOperand(0, V);
7993 return &EI;
7994 }
7995 }
7996
Reid Spencerb83eb642006-10-20 07:07:24 +00007997 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
Chris Lattner6e6b0da2006-03-31 23:01:56 +00007998 return ReplaceInstUsesWith(EI, Elt);
Chris Lattner389a6f52006-04-10 23:06:36 +00007999 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +00008000
Chris Lattner73fa49d2006-05-25 22:53:38 +00008001 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchino1d7456d2006-01-13 22:48:06 +00008002 if (I->hasOneUse()) {
8003 // Push extractelement into predecessor operation if legal and
8004 // profitable to do so
8005 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +00008006 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
8007 if (CheapToScalarize(BO, isConstantElt)) {
8008 ExtractElementInst *newEI0 =
8009 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
8010 EI.getName()+".lhs");
8011 ExtractElementInst *newEI1 =
8012 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
8013 EI.getName()+".rhs");
8014 InsertNewInstBefore(newEI0, EI);
8015 InsertNewInstBefore(newEI1, EI);
8016 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
8017 }
8018 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Robert Bocchino1d7456d2006-01-13 22:48:06 +00008019 Value *Ptr = InsertCastBefore(I->getOperand(0),
8020 PointerType::get(EI.getType()), EI);
8021 GetElementPtrInst *GEP =
8022 new GetElementPtrInst(Ptr, EI.getOperand(1),
8023 I->getName() + ".gep");
8024 InsertNewInstBefore(GEP, EI);
8025 return new LoadInst(GEP);
Chris Lattner73fa49d2006-05-25 22:53:38 +00008026 }
8027 }
8028 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
8029 // Extracting the inserted element?
8030 if (IE->getOperand(2) == EI.getOperand(1))
8031 return ReplaceInstUsesWith(EI, IE->getOperand(1));
8032 // If the inserted and extracted elements are constants, they must not
8033 // be the same value, extract from the pre-inserted value instead.
8034 if (isa<Constant>(IE->getOperand(2)) &&
8035 isa<Constant>(EI.getOperand(1))) {
8036 AddUsesToWorkList(EI);
8037 EI.setOperand(0, IE->getOperand(0));
8038 return &EI;
8039 }
8040 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
8041 // If this is extracting an element from a shufflevector, figure out where
8042 // it came from and extract from the appropriate input element instead.
Reid Spencerb83eb642006-10-20 07:07:24 +00008043 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
8044 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner863bcff2006-05-25 23:48:38 +00008045 Value *Src;
8046 if (SrcIdx < SVI->getType()->getNumElements())
8047 Src = SVI->getOperand(0);
8048 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
8049 SrcIdx -= SVI->getType()->getNumElements();
8050 Src = SVI->getOperand(1);
8051 } else {
8052 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +00008053 }
Chris Lattner867b99f2006-10-05 06:55:50 +00008054 return new ExtractElementInst(Src, SrcIdx);
Robert Bocchino1d7456d2006-01-13 22:48:06 +00008055 }
8056 }
Chris Lattner73fa49d2006-05-25 22:53:38 +00008057 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +00008058 return 0;
8059}
8060
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00008061/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
8062/// elements from either LHS or RHS, return the shuffle mask and true.
8063/// Otherwise, return false.
8064static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
8065 std::vector<Constant*> &Mask) {
8066 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
8067 "Invalid CollectSingleShuffleElements");
8068 unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
8069
8070 if (isa<UndefValue>(V)) {
8071 Mask.assign(NumElts, UndefValue::get(Type::UIntTy));
8072 return true;
8073 } else if (V == LHS) {
8074 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerb83eb642006-10-20 07:07:24 +00008075 Mask.push_back(ConstantInt::get(Type::UIntTy, i));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00008076 return true;
8077 } else if (V == RHS) {
8078 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerb83eb642006-10-20 07:07:24 +00008079 Mask.push_back(ConstantInt::get(Type::UIntTy, i+NumElts));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00008080 return true;
8081 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
8082 // If this is an insert of an extract from some other vector, include it.
8083 Value *VecOp = IEI->getOperand(0);
8084 Value *ScalarOp = IEI->getOperand(1);
8085 Value *IdxOp = IEI->getOperand(2);
8086
Chris Lattnerd929f062006-04-27 21:14:21 +00008087 if (!isa<ConstantInt>(IdxOp))
8088 return false;
Reid Spencerb83eb642006-10-20 07:07:24 +00008089 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerd929f062006-04-27 21:14:21 +00008090
8091 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
8092 // Okay, we can handle this if the vector we are insertinting into is
8093 // transitively ok.
8094 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
8095 // If so, update the mask to reflect the inserted undef.
8096 Mask[InsertedIdx] = UndefValue::get(Type::UIntTy);
8097 return true;
8098 }
8099 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
8100 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00008101 EI->getOperand(0)->getType() == V->getType()) {
8102 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +00008103 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00008104
8105 // This must be extracting from either LHS or RHS.
8106 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
8107 // Okay, we can handle this if the vector we are insertinting into is
8108 // transitively ok.
8109 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
8110 // If so, update the mask to reflect the inserted value.
8111 if (EI->getOperand(0) == LHS) {
8112 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerb83eb642006-10-20 07:07:24 +00008113 ConstantInt::get(Type::UIntTy, ExtractedIdx);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00008114 } else {
8115 assert(EI->getOperand(0) == RHS);
8116 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerb83eb642006-10-20 07:07:24 +00008117 ConstantInt::get(Type::UIntTy, ExtractedIdx+NumElts);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00008118
8119 }
8120 return true;
8121 }
8122 }
8123 }
8124 }
8125 }
8126 // TODO: Handle shufflevector here!
8127
8128 return false;
8129}
8130
8131/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
8132/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
8133/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +00008134static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00008135 Value *&RHS) {
8136 assert(isa<PackedType>(V->getType()) &&
8137 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +00008138 "Invalid shuffle!");
8139 unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
8140
8141 if (isa<UndefValue>(V)) {
8142 Mask.assign(NumElts, UndefValue::get(Type::UIntTy));
8143 return V;
8144 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00008145 Mask.assign(NumElts, ConstantInt::get(Type::UIntTy, 0));
Chris Lattnerefb47352006-04-15 01:39:45 +00008146 return V;
8147 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
8148 // If this is an insert of an extract from some other vector, include it.
8149 Value *VecOp = IEI->getOperand(0);
8150 Value *ScalarOp = IEI->getOperand(1);
8151 Value *IdxOp = IEI->getOperand(2);
8152
8153 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
8154 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
8155 EI->getOperand(0)->getType() == V->getType()) {
8156 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +00008157 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8158 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +00008159
8160 // Either the extracted from or inserted into vector must be RHSVec,
8161 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00008162 if (EI->getOperand(0) == RHS || RHS == 0) {
8163 RHS = EI->getOperand(0);
8164 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +00008165 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerb83eb642006-10-20 07:07:24 +00008166 ConstantInt::get(Type::UIntTy, NumElts+ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +00008167 return V;
8168 }
8169
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00008170 if (VecOp == RHS) {
8171 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +00008172 // Everything but the extracted element is replaced with the RHS.
8173 for (unsigned i = 0; i != NumElts; ++i) {
8174 if (i != InsertedIdx)
Reid Spencerb83eb642006-10-20 07:07:24 +00008175 Mask[i] = ConstantInt::get(Type::UIntTy, NumElts+i);
Chris Lattnerefb47352006-04-15 01:39:45 +00008176 }
8177 return V;
8178 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00008179
8180 // If this insertelement is a chain that comes from exactly these two
8181 // vectors, return the vector and the effective shuffle.
8182 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
8183 return EI->getOperand(0);
8184
Chris Lattnerefb47352006-04-15 01:39:45 +00008185 }
8186 }
8187 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00008188 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +00008189
8190 // Otherwise, can't do anything fancy. Return an identity vector.
8191 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerb83eb642006-10-20 07:07:24 +00008192 Mask.push_back(ConstantInt::get(Type::UIntTy, i));
Chris Lattnerefb47352006-04-15 01:39:45 +00008193 return V;
8194}
8195
8196Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
8197 Value *VecOp = IE.getOperand(0);
8198 Value *ScalarOp = IE.getOperand(1);
8199 Value *IdxOp = IE.getOperand(2);
8200
8201 // If the inserted element was extracted from some other vector, and if the
8202 // indexes are constant, try to turn this into a shufflevector operation.
8203 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
8204 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
8205 EI->getOperand(0)->getType() == IE.getType()) {
8206 unsigned NumVectorElts = IE.getType()->getNumElements();
Reid Spencerb83eb642006-10-20 07:07:24 +00008207 unsigned ExtractedIdx=cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8208 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +00008209
8210 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
8211 return ReplaceInstUsesWith(IE, VecOp);
8212
8213 if (InsertedIdx >= NumVectorElts) // Out of range insert.
8214 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
8215
8216 // If we are extracting a value from a vector, then inserting it right
8217 // back into the same place, just use the input vector.
8218 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
8219 return ReplaceInstUsesWith(IE, VecOp);
8220
8221 // We could theoretically do this for ANY input. However, doing so could
8222 // turn chains of insertelement instructions into a chain of shufflevector
8223 // instructions, and right now we do not merge shufflevectors. As such,
8224 // only do this in a situation where it is clear that there is benefit.
8225 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
8226 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
8227 // the values of VecOp, except then one read from EIOp0.
8228 // Build a new shuffle mask.
8229 std::vector<Constant*> Mask;
8230 if (isa<UndefValue>(VecOp))
8231 Mask.assign(NumVectorElts, UndefValue::get(Type::UIntTy));
8232 else {
8233 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Reid Spencerb83eb642006-10-20 07:07:24 +00008234 Mask.assign(NumVectorElts, ConstantInt::get(Type::UIntTy,
Chris Lattnerefb47352006-04-15 01:39:45 +00008235 NumVectorElts));
8236 }
Reid Spencerb83eb642006-10-20 07:07:24 +00008237 Mask[InsertedIdx] = ConstantInt::get(Type::UIntTy, ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +00008238 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
8239 ConstantPacked::get(Mask));
8240 }
8241
8242 // If this insertelement isn't used by some other insertelement, turn it
8243 // (and any insertelements it points to), into one big shuffle.
8244 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
8245 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00008246 Value *RHS = 0;
8247 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
8248 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
8249 // We now have a shuffle of LHS, RHS, Mask.
8250 return new ShuffleVectorInst(LHS, RHS, ConstantPacked::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +00008251 }
8252 }
8253 }
8254
8255 return 0;
8256}
8257
8258
Chris Lattnera844fc4c2006-04-10 22:45:52 +00008259Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
8260 Value *LHS = SVI.getOperand(0);
8261 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +00008262 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +00008263
8264 bool MadeChange = false;
8265
Chris Lattner867b99f2006-10-05 06:55:50 +00008266 // Undefined shuffle mask -> undefined value.
Chris Lattner863bcff2006-05-25 23:48:38 +00008267 if (isa<UndefValue>(SVI.getOperand(2)))
Chris Lattnera844fc4c2006-04-10 22:45:52 +00008268 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
8269
Chris Lattnerefb47352006-04-15 01:39:45 +00008270 // TODO: If we have shuffle(x, undef, mask) and any elements of mask refer to
8271 // the undef, change them to undefs.
8272
Chris Lattner863bcff2006-05-25 23:48:38 +00008273 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
8274 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
8275 if (LHS == RHS || isa<UndefValue>(LHS)) {
8276 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +00008277 // shuffle(undef,undef,mask) -> undef.
8278 return ReplaceInstUsesWith(SVI, LHS);
8279 }
8280
Chris Lattner863bcff2006-05-25 23:48:38 +00008281 // Remap any references to RHS to use LHS.
8282 std::vector<Constant*> Elts;
8283 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +00008284 if (Mask[i] >= 2*e)
Chris Lattner863bcff2006-05-25 23:48:38 +00008285 Elts.push_back(UndefValue::get(Type::UIntTy));
Chris Lattner7b2e27922006-05-26 00:29:06 +00008286 else {
8287 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
8288 (Mask[i] < e && isa<UndefValue>(LHS)))
8289 Mask[i] = 2*e; // Turn into undef.
8290 else
8291 Mask[i] &= (e-1); // Force to LHS.
Reid Spencerb83eb642006-10-20 07:07:24 +00008292 Elts.push_back(ConstantInt::get(Type::UIntTy, Mask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +00008293 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +00008294 }
Chris Lattner863bcff2006-05-25 23:48:38 +00008295 SVI.setOperand(0, SVI.getOperand(1));
Chris Lattnera844fc4c2006-04-10 22:45:52 +00008296 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Chris Lattner863bcff2006-05-25 23:48:38 +00008297 SVI.setOperand(2, ConstantPacked::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +00008298 LHS = SVI.getOperand(0);
8299 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +00008300 MadeChange = true;
8301 }
8302
Chris Lattner7b2e27922006-05-26 00:29:06 +00008303 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +00008304 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +00008305
Chris Lattner863bcff2006-05-25 23:48:38 +00008306 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
8307 if (Mask[i] >= e*2) continue; // Ignore undef values.
8308 // Is this an identity shuffle of the LHS value?
8309 isLHSID &= (Mask[i] == i);
8310
8311 // Is this an identity shuffle of the RHS value?
8312 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +00008313 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +00008314
Chris Lattner863bcff2006-05-25 23:48:38 +00008315 // Eliminate identity shuffles.
8316 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
8317 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +00008318
Chris Lattner7b2e27922006-05-26 00:29:06 +00008319 // If the LHS is a shufflevector itself, see if we can combine it with this
8320 // one without producing an unusual shuffle. Here we are really conservative:
8321 // we are absolutely afraid of producing a shuffle mask not in the input
8322 // program, because the code gen may not be smart enough to turn a merged
8323 // shuffle into two specific shuffles: it may produce worse code. As such,
8324 // we only merge two shuffles if the result is one of the two input shuffle
8325 // masks. In this case, merging the shuffles just removes one instruction,
8326 // which we know is safe. This is good for things like turning:
8327 // (splat(splat)) -> splat.
8328 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
8329 if (isa<UndefValue>(RHS)) {
8330 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
8331
8332 std::vector<unsigned> NewMask;
8333 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
8334 if (Mask[i] >= 2*e)
8335 NewMask.push_back(2*e);
8336 else
8337 NewMask.push_back(LHSMask[Mask[i]]);
8338
8339 // If the result mask is equal to the src shuffle or this shuffle mask, do
8340 // the replacement.
8341 if (NewMask == LHSMask || NewMask == Mask) {
8342 std::vector<Constant*> Elts;
8343 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
8344 if (NewMask[i] >= e*2) {
8345 Elts.push_back(UndefValue::get(Type::UIntTy));
8346 } else {
Reid Spencerb83eb642006-10-20 07:07:24 +00008347 Elts.push_back(ConstantInt::get(Type::UIntTy, NewMask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +00008348 }
8349 }
8350 return new ShuffleVectorInst(LHSSVI->getOperand(0),
8351 LHSSVI->getOperand(1),
8352 ConstantPacked::get(Elts));
8353 }
8354 }
8355 }
8356
Chris Lattnera844fc4c2006-04-10 22:45:52 +00008357 return MadeChange ? &SVI : 0;
8358}
8359
8360
Robert Bocchino1d7456d2006-01-13 22:48:06 +00008361
Chris Lattner62b14df2002-09-02 04:59:56 +00008362void InstCombiner::removeFromWorkList(Instruction *I) {
8363 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
8364 WorkList.end());
8365}
8366
Chris Lattnerea1c4542004-12-08 23:43:58 +00008367
8368/// TryToSinkInstruction - Try to move the specified instruction from its
8369/// current block into the beginning of DestBlock, which can only happen if it's
8370/// safe to move the instruction past all of the instructions between it and the
8371/// end of its block.
8372static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
8373 assert(I->hasOneUse() && "Invariants didn't hold!");
8374
Chris Lattner108e9022005-10-27 17:13:11 +00008375 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
8376 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
Misha Brukmanfd939082005-04-21 23:48:37 +00008377
Chris Lattnerea1c4542004-12-08 23:43:58 +00008378 // Do not sink alloca instructions out of the entry block.
8379 if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
8380 return false;
8381
Chris Lattner96a52a62004-12-09 07:14:34 +00008382 // We can only sink load instructions if there is nothing between the load and
8383 // the end of block that could change the value.
8384 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattner96a52a62004-12-09 07:14:34 +00008385 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
8386 Scan != E; ++Scan)
8387 if (Scan->mayWriteToMemory())
8388 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +00008389 }
Chris Lattnerea1c4542004-12-08 23:43:58 +00008390
8391 BasicBlock::iterator InsertPos = DestBlock->begin();
8392 while (isa<PHINode>(InsertPos)) ++InsertPos;
8393
Chris Lattner4bc5f802005-08-08 19:11:57 +00008394 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +00008395 ++NumSunkInst;
8396 return true;
8397}
8398
Chris Lattner8c8c66a2006-05-11 17:11:52 +00008399/// OptimizeConstantExpr - Given a constant expression and target data layout
8400/// information, symbolically evaluation the constant expr to something simpler
8401/// if possible.
8402static Constant *OptimizeConstantExpr(ConstantExpr *CE, const TargetData *TD) {
8403 if (!TD) return CE;
8404
8405 Constant *Ptr = CE->getOperand(0);
8406 if (CE->getOpcode() == Instruction::GetElementPtr && Ptr->isNullValue() &&
8407 cast<PointerType>(Ptr->getType())->getElementType()->isSized()) {
8408 // If this is a constant expr gep that is effectively computing an
8409 // "offsetof", fold it into 'cast int Size to T*' instead of 'gep 0, 0, 12'
8410 bool isFoldableGEP = true;
8411 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
8412 if (!isa<ConstantInt>(CE->getOperand(i)))
8413 isFoldableGEP = false;
8414 if (isFoldableGEP) {
8415 std::vector<Value*> Ops(CE->op_begin()+1, CE->op_end());
8416 uint64_t Offset = TD->getIndexedOffset(Ptr->getType(), Ops);
Reid Spencerb83eb642006-10-20 07:07:24 +00008417 Constant *C = ConstantInt::get(Type::ULongTy, Offset);
Chris Lattner8c8c66a2006-05-11 17:11:52 +00008418 C = ConstantExpr::getCast(C, TD->getIntPtrType());
8419 return ConstantExpr::getCast(C, CE->getType());
8420 }
8421 }
8422
8423 return CE;
8424}
8425
Chris Lattnerf4f5a772006-05-10 19:00:36 +00008426
8427/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
8428/// all reachable code to the worklist.
8429///
8430/// This has a couple of tricks to make the code faster and more powerful. In
8431/// particular, we constant fold and DCE instructions as we go, to avoid adding
8432/// them to the worklist (this significantly speeds up instcombine on code where
8433/// many instructions are dead or constant). Additionally, if we find a branch
8434/// whose condition is a known constant, we only visit the reachable successors.
8435///
8436static void AddReachableCodeToWorklist(BasicBlock *BB,
8437 std::set<BasicBlock*> &Visited,
Chris Lattner8c8c66a2006-05-11 17:11:52 +00008438 std::vector<Instruction*> &WorkList,
8439 const TargetData *TD) {
Chris Lattnerf4f5a772006-05-10 19:00:36 +00008440 // We have now visited this block! If we've already been here, bail out.
8441 if (!Visited.insert(BB).second) return;
8442
8443 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
8444 Instruction *Inst = BBI++;
8445
8446 // DCE instruction if trivially dead.
8447 if (isInstructionTriviallyDead(Inst)) {
8448 ++NumDeadInst;
8449 DEBUG(std::cerr << "IC: DCE: " << *Inst);
8450 Inst->eraseFromParent();
8451 continue;
8452 }
8453
8454 // ConstantProp instruction if trivially constant.
8455 if (Constant *C = ConstantFoldInstruction(Inst)) {
Chris Lattner8c8c66a2006-05-11 17:11:52 +00008456 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
8457 C = OptimizeConstantExpr(CE, TD);
Chris Lattnerf4f5a772006-05-10 19:00:36 +00008458 DEBUG(std::cerr << "IC: ConstFold to: " << *C << " from: " << *Inst);
8459 Inst->replaceAllUsesWith(C);
8460 ++NumConstProp;
8461 Inst->eraseFromParent();
8462 continue;
8463 }
8464
8465 WorkList.push_back(Inst);
8466 }
8467
8468 // Recursively visit successors. If this is a branch or switch on a constant,
8469 // only visit the reachable successor.
8470 TerminatorInst *TI = BB->getTerminator();
8471 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
8472 if (BI->isConditional() && isa<ConstantBool>(BI->getCondition())) {
8473 bool CondVal = cast<ConstantBool>(BI->getCondition())->getValue();
Chris Lattner8c8c66a2006-05-11 17:11:52 +00008474 AddReachableCodeToWorklist(BI->getSuccessor(!CondVal), Visited, WorkList,
8475 TD);
Chris Lattnerf4f5a772006-05-10 19:00:36 +00008476 return;
8477 }
8478 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
8479 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
8480 // See if this is an explicit destination.
8481 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
8482 if (SI->getCaseValue(i) == Cond) {
Chris Lattner8c8c66a2006-05-11 17:11:52 +00008483 AddReachableCodeToWorklist(SI->getSuccessor(i), Visited, WorkList,TD);
Chris Lattnerf4f5a772006-05-10 19:00:36 +00008484 return;
8485 }
8486
8487 // Otherwise it is the default destination.
Chris Lattner8c8c66a2006-05-11 17:11:52 +00008488 AddReachableCodeToWorklist(SI->getSuccessor(0), Visited, WorkList, TD);
Chris Lattnerf4f5a772006-05-10 19:00:36 +00008489 return;
8490 }
8491 }
8492
8493 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
Chris Lattner8c8c66a2006-05-11 17:11:52 +00008494 AddReachableCodeToWorklist(TI->getSuccessor(i), Visited, WorkList, TD);
Chris Lattnerf4f5a772006-05-10 19:00:36 +00008495}
8496
Chris Lattner7e708292002-06-25 16:13:24 +00008497bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerdd841ae2002-04-18 17:39:14 +00008498 bool Changed = false;
Chris Lattnerbc61e662003-11-02 05:57:39 +00008499 TD = &getAnalysis<TargetData>();
Chris Lattner8a2a3112001-12-14 16:52:21 +00008500
Chris Lattnerb3d59702005-07-07 20:40:38 +00008501 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +00008502 // Do a depth-first traversal of the function, populate the worklist with
8503 // the reachable instructions. Ignore blocks that are not reachable. Keep
8504 // track of which blocks we visit.
Chris Lattnerb3d59702005-07-07 20:40:38 +00008505 std::set<BasicBlock*> Visited;
Chris Lattner8c8c66a2006-05-11 17:11:52 +00008506 AddReachableCodeToWorklist(F.begin(), Visited, WorkList, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +00008507
Chris Lattnerb3d59702005-07-07 20:40:38 +00008508 // Do a quick scan over the function. If we find any blocks that are
8509 // unreachable, remove any instructions inside of them. This prevents
8510 // the instcombine code from having to deal with some bad special cases.
8511 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
8512 if (!Visited.count(BB)) {
8513 Instruction *Term = BB->getTerminator();
8514 while (Term != BB->begin()) { // Remove instrs bottom-up
8515 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +00008516
Chris Lattnerb3d59702005-07-07 20:40:38 +00008517 DEBUG(std::cerr << "IC: DCE: " << *I);
8518 ++NumDeadInst;
8519
8520 if (!I->use_empty())
8521 I->replaceAllUsesWith(UndefValue::get(I->getType()));
8522 I->eraseFromParent();
8523 }
8524 }
8525 }
Chris Lattner8a2a3112001-12-14 16:52:21 +00008526
8527 while (!WorkList.empty()) {
8528 Instruction *I = WorkList.back(); // Get an instruction from the worklist
8529 WorkList.pop_back();
8530
Chris Lattner8c8c66a2006-05-11 17:11:52 +00008531 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +00008532 if (isInstructionTriviallyDead(I)) {
Chris Lattner8c8c66a2006-05-11 17:11:52 +00008533 // Add operands to the worklist.
Chris Lattner4bb7c022003-10-06 17:11:01 +00008534 if (I->getNumOperands() < 4)
Chris Lattner7bcc0e72004-02-28 05:22:00 +00008535 AddUsesToWorkList(*I);
Chris Lattner62b14df2002-09-02 04:59:56 +00008536 ++NumDeadInst;
Chris Lattner4bb7c022003-10-06 17:11:01 +00008537
Chris Lattnerad5fec12005-01-28 19:32:01 +00008538 DEBUG(std::cerr << "IC: DCE: " << *I);
8539
8540 I->eraseFromParent();
Chris Lattner4bb7c022003-10-06 17:11:01 +00008541 removeFromWorkList(I);
8542 continue;
8543 }
Chris Lattner62b14df2002-09-02 04:59:56 +00008544
Chris Lattner8c8c66a2006-05-11 17:11:52 +00008545 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattner62b14df2002-09-02 04:59:56 +00008546 if (Constant *C = ConstantFoldInstruction(I)) {
Chris Lattner8c8c66a2006-05-11 17:11:52 +00008547 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
8548 C = OptimizeConstantExpr(CE, TD);
Chris Lattnerad5fec12005-01-28 19:32:01 +00008549 DEBUG(std::cerr << "IC: ConstFold to: " << *C << " from: " << *I);
8550
Chris Lattner8c8c66a2006-05-11 17:11:52 +00008551 // Add operands to the worklist.
Chris Lattner7bcc0e72004-02-28 05:22:00 +00008552 AddUsesToWorkList(*I);
Chris Lattnerc736d562002-12-05 22:41:53 +00008553 ReplaceInstUsesWith(*I, C);
8554
Chris Lattner62b14df2002-09-02 04:59:56 +00008555 ++NumConstProp;
Chris Lattnerf4f5a772006-05-10 19:00:36 +00008556 I->eraseFromParent();
Chris Lattner60610002003-10-07 15:17:02 +00008557 removeFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +00008558 continue;
Chris Lattner62b14df2002-09-02 04:59:56 +00008559 }
Chris Lattner4bb7c022003-10-06 17:11:01 +00008560
Chris Lattnerea1c4542004-12-08 23:43:58 +00008561 // See if we can trivially sink this instruction to a successor basic block.
8562 if (I->hasOneUse()) {
8563 BasicBlock *BB = I->getParent();
8564 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
8565 if (UserParent != BB) {
8566 bool UserIsSuccessor = false;
8567 // See if the user is one of our successors.
8568 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
8569 if (*SI == UserParent) {
8570 UserIsSuccessor = true;
8571 break;
8572 }
8573
8574 // If the user is one of our immediate successors, and if that successor
8575 // only has us as a predecessors (we'd have to split the critical edge
8576 // otherwise), we can keep going.
8577 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
8578 next(pred_begin(UserParent)) == pred_end(UserParent))
8579 // Okay, the CFG is simple enough, try to sink this instruction.
8580 Changed |= TryToSinkInstruction(I, UserParent);
8581 }
8582 }
8583
Chris Lattner8a2a3112001-12-14 16:52:21 +00008584 // Now that we have an instruction, try combining it to simplify it...
Chris Lattner90ac28c2002-08-02 19:29:35 +00008585 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +00008586 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00008587 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +00008588 if (Result != I) {
Chris Lattner0cea42a2004-03-13 23:54:27 +00008589 DEBUG(std::cerr << "IC: Old = " << *I
8590 << " New = " << *Result);
8591
Chris Lattnerf523d062004-06-09 05:08:07 +00008592 // Everything uses the new instruction now.
8593 I->replaceAllUsesWith(Result);
8594
8595 // Push the new instruction and any users onto the worklist.
8596 WorkList.push_back(Result);
8597 AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +00008598
8599 // Move the name to the new instruction first...
8600 std::string OldName = I->getName(); I->setName("");
Chris Lattnerd558dc32003-10-07 22:58:41 +00008601 Result->setName(OldName);
Chris Lattner4bb7c022003-10-06 17:11:01 +00008602
8603 // Insert the new instruction into the basic block...
8604 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +00008605 BasicBlock::iterator InsertPos = I;
8606
8607 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
8608 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
8609 ++InsertPos;
8610
8611 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +00008612
Chris Lattner00d51312004-05-01 23:27:23 +00008613 // Make sure that we reprocess all operands now that we reduced their
8614 // use counts.
Chris Lattner216d4d82004-05-01 23:19:52 +00008615 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
8616 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
8617 WorkList.push_back(OpI);
8618
Chris Lattnerf523d062004-06-09 05:08:07 +00008619 // Instructions can end up on the worklist more than once. Make sure
8620 // we do not process an instruction that has been deleted.
8621 removeFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +00008622
8623 // Erase the old instruction.
8624 InstParent->getInstList().erase(I);
Chris Lattner7e708292002-06-25 16:13:24 +00008625 } else {
Chris Lattner0cea42a2004-03-13 23:54:27 +00008626 DEBUG(std::cerr << "IC: MOD = " << *I);
8627
Chris Lattner90ac28c2002-08-02 19:29:35 +00008628 // If the instruction was modified, it's possible that it is now dead.
8629 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +00008630 if (isInstructionTriviallyDead(I)) {
8631 // Make sure we process all operands now that we are reducing their
8632 // use counts.
8633 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
8634 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
8635 WorkList.push_back(OpI);
Misha Brukmanfd939082005-04-21 23:48:37 +00008636
Chris Lattner00d51312004-05-01 23:27:23 +00008637 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchino1d7456d2006-01-13 22:48:06 +00008638 // occurrences of this instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +00008639 removeFromWorkList(I);
Chris Lattner2f503e62005-01-31 05:36:43 +00008640 I->eraseFromParent();
Chris Lattnerf523d062004-06-09 05:08:07 +00008641 } else {
8642 WorkList.push_back(Result);
8643 AddUsersToWorkList(*Result);
Chris Lattner90ac28c2002-08-02 19:29:35 +00008644 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +00008645 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00008646 Changed = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +00008647 }
8648 }
8649
Chris Lattnerdd841ae2002-04-18 17:39:14 +00008650 return Changed;
Chris Lattnerbd0ef772002-02-26 21:46:54 +00008651}
8652
Brian Gaeke96d4bf72004-07-27 17:43:21 +00008653FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +00008654 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +00008655}
Brian Gaeked0fde302003-11-11 22:41:34 +00008656