blob: 186d8378a4972cd2323ab101f4eae4545408dca0 [file] [log] [blame]
Chris Lattner233f7dc2002-08-12 21:17:25 +00001//===- InstructionCombining.cpp - Combine multiple instructions -----------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner8a2a3112001-12-14 16:52:21 +00009//
10// InstructionCombining - Combine instructions to form fewer, simple
Dan Gohman844731a2008-05-13 00:00:25 +000011// instructions. This pass does not modify the CFG. This pass is where
12// algebraic simplification happens.
Chris Lattner8a2a3112001-12-14 16:52:21 +000013//
14// This pass combines things like:
Chris Lattner318bf792007-03-18 22:51:34 +000015// %Y = add i32 %X, 1
16// %Z = add i32 %Y, 1
Chris Lattner8a2a3112001-12-14 16:52:21 +000017// into:
Chris Lattner318bf792007-03-18 22:51:34 +000018// %Z = add i32 %X, 2
Chris Lattner8a2a3112001-12-14 16:52:21 +000019//
20// This is a simple worklist driven algorithm.
21//
Chris Lattner065a6162003-09-10 05:29:43 +000022// This pass guarantees that the following canonicalizations are performed on
Chris Lattner2cd91962003-07-23 21:41:57 +000023// the program:
24// 1. If a binary operator has a constant operand, it is moved to the RHS
Chris Lattnerdf17af12003-08-12 21:53:41 +000025// 2. Bitwise operators with constant operands are always grouped so that
26// shifts are performed first, then or's, then and's, then xor's.
Reid Spencere4d87aa2006-12-23 06:05:41 +000027// 3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
28// 4. All cmp instructions on boolean values are replaced with logical ops
Chris Lattnere92d2f42003-08-13 04:18:28 +000029// 5. add X, X is represented as (X*2) => (X << 1)
30// 6. Multiplies with a power-of-two constant argument are transformed into
31// shifts.
Chris Lattnerbac32862004-11-14 19:13:23 +000032// ... etc.
Chris Lattner2cd91962003-07-23 21:41:57 +000033//
Chris Lattner8a2a3112001-12-14 16:52:21 +000034//===----------------------------------------------------------------------===//
35
Chris Lattner0cea42a2004-03-13 23:54:27 +000036#define DEBUG_TYPE "instcombine"
Chris Lattner022103b2002-05-07 20:03:00 +000037#include "llvm/Transforms/Scalar.h"
Chris Lattner35b9e482004-10-12 04:52:52 +000038#include "llvm/IntrinsicInst.h"
Chris Lattnerbd0ef772002-02-26 21:46:54 +000039#include "llvm/Pass.h"
Chris Lattner0864acf2002-11-04 16:18:53 +000040#include "llvm/DerivedTypes.h"
Chris Lattner833b8a42003-06-26 05:06:25 +000041#include "llvm/GlobalVariable.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000042#include "llvm/Analysis/ConstantFolding.h"
Chris Lattner173234a2008-06-02 01:18:21 +000043#include "llvm/Analysis/ValueTracking.h"
Chris Lattnerbc61e662003-11-02 05:57:39 +000044#include "llvm/Target/TargetData.h"
45#include "llvm/Transforms/Utils/BasicBlockUtils.h"
46#include "llvm/Transforms/Utils/Local.h"
Chris Lattner28977af2004-04-05 01:30:19 +000047#include "llvm/Support/CallSite.h"
Nick Lewycky5be29202008-02-03 16:33:09 +000048#include "llvm/Support/ConstantRange.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000049#include "llvm/Support/Debug.h"
Chris Lattner28977af2004-04-05 01:30:19 +000050#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattnerdd841ae2002-04-18 17:39:14 +000051#include "llvm/Support/InstVisitor.h"
Chris Lattnerbcd7db52005-08-02 19:16:58 +000052#include "llvm/Support/MathExtras.h"
Chris Lattneracd1f0f2004-07-30 07:50:03 +000053#include "llvm/Support/PatternMatch.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000054#include "llvm/Support/Compiler.h"
Chris Lattnerdbab3862007-03-02 21:28:56 +000055#include "llvm/ADT/DenseMap.h"
Chris Lattner55eb1c42007-01-31 04:40:53 +000056#include "llvm/ADT/SmallVector.h"
Chris Lattner1f87a582007-02-15 19:41:52 +000057#include "llvm/ADT/SmallPtrSet.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000058#include "llvm/ADT/Statistic.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000059#include "llvm/ADT/STLExtras.h"
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000060#include <algorithm>
Torok Edwin3eaee312008-04-20 08:33:11 +000061#include <climits>
Reid Spencera9b81012007-03-26 17:44:01 +000062#include <sstream>
Chris Lattner67b1e1b2003-12-07 01:24:23 +000063using namespace llvm;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000064using namespace llvm::PatternMatch;
Brian Gaeked0fde302003-11-11 22:41:34 +000065
Chris Lattner0e5f4992006-12-19 21:40:18 +000066STATISTIC(NumCombined , "Number of insts combined");
67STATISTIC(NumConstProp, "Number of constant folds");
68STATISTIC(NumDeadInst , "Number of dead inst eliminated");
69STATISTIC(NumDeadStore, "Number of dead stores eliminated");
70STATISTIC(NumSunkInst , "Number of instructions sunk");
Chris Lattnera92f6962002-10-01 22:38:41 +000071
Chris Lattner0e5f4992006-12-19 21:40:18 +000072namespace {
Chris Lattnerf4b54612006-06-28 22:08:15 +000073 class VISIBILITY_HIDDEN InstCombiner
74 : public FunctionPass,
75 public InstVisitor<InstCombiner, Instruction*> {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000076 // Worklist of all of the instructions that need to be simplified.
Chris Lattner2806dff2008-08-15 04:03:01 +000077 SmallVector<Instruction*, 256> Worklist;
Chris Lattnerdbab3862007-03-02 21:28:56 +000078 DenseMap<Instruction*, unsigned> WorklistMap;
Chris Lattnerbc61e662003-11-02 05:57:39 +000079 TargetData *TD;
Chris Lattnerf964f322007-03-04 04:27:24 +000080 bool MustPreserveLCSSA;
Chris Lattnerdbab3862007-03-02 21:28:56 +000081 public:
Nick Lewyckyecd94c82007-05-06 13:37:16 +000082 static char ID; // Pass identification, replacement for typeid
Dan Gohmanae73dc12008-09-04 17:05:41 +000083 InstCombiner() : FunctionPass(&ID) {}
Devang Patel794fd752007-05-01 21:15:47 +000084
Chris Lattnerdbab3862007-03-02 21:28:56 +000085 /// AddToWorkList - Add the specified instruction to the worklist if it
86 /// isn't already in it.
87 void AddToWorkList(Instruction *I) {
Dan Gohman6b345ee2008-07-07 17:46:23 +000088 if (WorklistMap.insert(std::make_pair(I, Worklist.size())).second)
Chris Lattnerdbab3862007-03-02 21:28:56 +000089 Worklist.push_back(I);
90 }
91
92 // RemoveFromWorkList - remove I from the worklist if it exists.
93 void RemoveFromWorkList(Instruction *I) {
94 DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
95 if (It == WorklistMap.end()) return; // Not in worklist.
96
97 // Don't bother moving everything down, just null out the slot.
98 Worklist[It->second] = 0;
99
100 WorklistMap.erase(It);
101 }
102
103 Instruction *RemoveOneFromWorkList() {
104 Instruction *I = Worklist.back();
105 Worklist.pop_back();
106 WorklistMap.erase(I);
107 return I;
108 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000109
Chris Lattnerdbab3862007-03-02 21:28:56 +0000110
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000111 /// AddUsersToWorkList - When an instruction is simplified, add all users of
112 /// the instruction to the work lists because they might get more simplified
113 /// now.
114 ///
Chris Lattner6dce1a72006-02-07 06:56:34 +0000115 void AddUsersToWorkList(Value &I) {
Chris Lattner7e708292002-06-25 16:13:24 +0000116 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000117 UI != UE; ++UI)
Chris Lattnerdbab3862007-03-02 21:28:56 +0000118 AddToWorkList(cast<Instruction>(*UI));
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000119 }
120
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000121 /// AddUsesToWorkList - When an instruction is simplified, add operands to
122 /// the work lists because they might get more simplified now.
123 ///
124 void AddUsesToWorkList(Instruction &I) {
Gabor Greif177dd3f2008-06-12 21:37:33 +0000125 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
126 if (Instruction *Op = dyn_cast<Instruction>(*i))
Chris Lattnerdbab3862007-03-02 21:28:56 +0000127 AddToWorkList(Op);
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000128 }
Chris Lattner867b99f2006-10-05 06:55:50 +0000129
130 /// AddSoonDeadInstToWorklist - The specified instruction is about to become
131 /// dead. Add all of its operands to the worklist, turning them into
132 /// undef's to reduce the number of uses of those instructions.
133 ///
134 /// Return the specified operand before it is turned into an undef.
135 ///
136 Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
137 Value *R = I.getOperand(op);
138
Gabor Greif177dd3f2008-06-12 21:37:33 +0000139 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
140 if (Instruction *Op = dyn_cast<Instruction>(*i)) {
Chris Lattnerdbab3862007-03-02 21:28:56 +0000141 AddToWorkList(Op);
Chris Lattner867b99f2006-10-05 06:55:50 +0000142 // Set the operand to undef to drop the use.
Gabor Greif177dd3f2008-06-12 21:37:33 +0000143 *i = UndefValue::get(Op->getType());
Chris Lattner867b99f2006-10-05 06:55:50 +0000144 }
145
146 return R;
147 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000148
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000149 public:
Chris Lattner7e708292002-06-25 16:13:24 +0000150 virtual bool runOnFunction(Function &F);
Chris Lattnerec9c3582007-03-03 02:04:50 +0000151
152 bool DoOneIteration(Function &F, unsigned ItNum);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000153
Chris Lattner97e52e42002-04-28 21:27:06 +0000154 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerbc61e662003-11-02 05:57:39 +0000155 AU.addRequired<TargetData>();
Owen Andersond1b78a12006-07-10 19:03:49 +0000156 AU.addPreservedID(LCSSAID);
Chris Lattnercb2610e2002-10-21 20:00:28 +0000157 AU.setPreservesCFG();
Chris Lattner97e52e42002-04-28 21:27:06 +0000158 }
159
Chris Lattner28977af2004-04-05 01:30:19 +0000160 TargetData &getTargetData() const { return *TD; }
161
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000162 // Visitation implementation - Implement instruction combining for different
163 // instruction types. The semantics are as follows:
164 // Return Value:
165 // null - No change was made
Chris Lattner233f7dc2002-08-12 21:17:25 +0000166 // I - Change was made, I is still valid, I may be dead though
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000167 // otherwise - Change was made, replace I with returned instruction
Misha Brukmanfd939082005-04-21 23:48:37 +0000168 //
Chris Lattner7e708292002-06-25 16:13:24 +0000169 Instruction *visitAdd(BinaryOperator &I);
170 Instruction *visitSub(BinaryOperator &I);
171 Instruction *visitMul(BinaryOperator &I);
Reid Spencer0a783f72006-11-02 01:53:59 +0000172 Instruction *visitURem(BinaryOperator &I);
173 Instruction *visitSRem(BinaryOperator &I);
174 Instruction *visitFRem(BinaryOperator &I);
Chris Lattnerfdb19e52008-07-14 00:15:52 +0000175 bool SimplifyDivRemOfSelect(BinaryOperator &I);
Reid Spencer0a783f72006-11-02 01:53:59 +0000176 Instruction *commonRemTransforms(BinaryOperator &I);
177 Instruction *commonIRemTransforms(BinaryOperator &I);
Reid Spencer1628cec2006-10-26 06:15:43 +0000178 Instruction *commonDivTransforms(BinaryOperator &I);
179 Instruction *commonIDivTransforms(BinaryOperator &I);
180 Instruction *visitUDiv(BinaryOperator &I);
181 Instruction *visitSDiv(BinaryOperator &I);
182 Instruction *visitFDiv(BinaryOperator &I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +0000183 Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Chris Lattner7e708292002-06-25 16:13:24 +0000184 Instruction *visitAnd(BinaryOperator &I);
Chris Lattner69d4ced2008-11-16 05:20:07 +0000185 Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Bill Wendlingd54d8602008-12-01 08:32:40 +0000186 Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +0000187 Value *A, Value *B, Value *C);
Chris Lattner7e708292002-06-25 16:13:24 +0000188 Instruction *visitOr (BinaryOperator &I);
189 Instruction *visitXor(BinaryOperator &I);
Reid Spencer832254e2007-02-02 02:16:23 +0000190 Instruction *visitShl(BinaryOperator &I);
191 Instruction *visitAShr(BinaryOperator &I);
192 Instruction *visitLShr(BinaryOperator &I);
193 Instruction *commonShiftTransforms(BinaryOperator &I);
Chris Lattnera5406232008-05-19 20:18:56 +0000194 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
195 Constant *RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000196 Instruction *visitFCmpInst(FCmpInst &I);
197 Instruction *visitICmpInst(ICmpInst &I);
198 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
Chris Lattner01deb9d2007-04-03 17:43:25 +0000199 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
200 Instruction *LHS,
201 ConstantInt *RHS);
Chris Lattner562ef782007-06-20 23:46:26 +0000202 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
203 ConstantInt *DivRHS);
Chris Lattner484d3cf2005-04-24 06:59:08 +0000204
Reid Spencere4d87aa2006-12-23 06:05:41 +0000205 Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
206 ICmpInst::Predicate Cond, Instruction &I);
Reid Spencerb83eb642006-10-20 07:07:24 +0000207 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +0000208 BinaryOperator &I);
Reid Spencer3da59db2006-11-27 01:05:10 +0000209 Instruction *commonCastTransforms(CastInst &CI);
210 Instruction *commonIntCastTransforms(CastInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000211 Instruction *commonPointerCastTransforms(CastInst &CI);
Chris Lattner8a9f5712007-04-11 06:57:46 +0000212 Instruction *visitTrunc(TruncInst &CI);
213 Instruction *visitZExt(ZExtInst &CI);
214 Instruction *visitSExt(SExtInst &CI);
Chris Lattnerb7530652008-01-27 05:29:54 +0000215 Instruction *visitFPTrunc(FPTruncInst &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000216 Instruction *visitFPExt(CastInst &CI);
Chris Lattner0c7a9a02008-05-19 20:25:04 +0000217 Instruction *visitFPToUI(FPToUIInst &FI);
218 Instruction *visitFPToSI(FPToSIInst &FI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000219 Instruction *visitUIToFP(CastInst &CI);
220 Instruction *visitSIToFP(CastInst &CI);
221 Instruction *visitPtrToInt(CastInst &CI);
Chris Lattnerf9d9e452008-01-08 07:23:51 +0000222 Instruction *visitIntToPtr(IntToPtrInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000223 Instruction *visitBitCast(BitCastInst &CI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +0000224 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
225 Instruction *FI);
Dan Gohman81b28ce2008-09-16 18:46:06 +0000226 Instruction *visitSelectInst(SelectInst &SI);
227 Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
Chris Lattner9fe38862003-06-19 17:00:31 +0000228 Instruction *visitCallInst(CallInst &CI);
229 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner7e708292002-06-25 16:13:24 +0000230 Instruction *visitPHINode(PHINode &PN);
231 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner0864acf2002-11-04 16:18:53 +0000232 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner67b1e1b2003-12-07 01:24:23 +0000233 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner833b8a42003-06-26 05:06:25 +0000234 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner2f503e62005-01-31 05:36:43 +0000235 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattnerc4d10eb2003-06-04 04:46:00 +0000236 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner46238a62004-07-03 00:26:11 +0000237 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattnerefb47352006-04-15 01:39:45 +0000238 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchino1d7456d2006-01-13 22:48:06 +0000239 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +0000240 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000241 Instruction *visitExtractValueInst(ExtractValueInst &EV);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000242
243 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner7e708292002-06-25 16:13:24 +0000244 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner8b170942002-08-09 23:47:40 +0000245
Chris Lattner9fe38862003-06-19 17:00:31 +0000246 private:
Chris Lattnera44d8a22003-10-07 22:32:43 +0000247 Instruction *visitCallSite(CallSite CS);
Chris Lattner9fe38862003-06-19 17:00:31 +0000248 bool transformConstExprCastCall(CallSite CS);
Duncan Sandscdb6d922007-09-17 10:26:40 +0000249 Instruction *transformCallThroughTrampoline(CallSite CS);
Evan Chengb98a10e2008-03-24 00:21:34 +0000250 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
251 bool DoXform = true);
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000252 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
Chris Lattner9fe38862003-06-19 17:00:31 +0000253
Chris Lattner28977af2004-04-05 01:30:19 +0000254 public:
Chris Lattner8b170942002-08-09 23:47:40 +0000255 // InsertNewInstBefore - insert an instruction New before instruction Old
256 // in the program. Add the new instruction to the worklist.
257 //
Chris Lattner955f3312004-09-28 21:48:02 +0000258 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattnere6f9a912002-08-23 18:32:43 +0000259 assert(New && New->getParent() == 0 &&
260 "New instruction already inserted into a basic block!");
Chris Lattner8b170942002-08-09 23:47:40 +0000261 BasicBlock *BB = Old.getParent();
262 BB->getInstList().insert(&Old, New); // Insert inst
Chris Lattnerdbab3862007-03-02 21:28:56 +0000263 AddToWorkList(New);
Chris Lattner4cb170c2004-02-23 06:38:22 +0000264 return New;
Chris Lattner8b170942002-08-09 23:47:40 +0000265 }
266
Chris Lattner0c967662004-09-24 15:21:34 +0000267 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
268 /// This also adds the cast to the worklist. Finally, this returns the
269 /// cast.
Reid Spencer17212df2006-12-12 09:18:51 +0000270 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
271 Instruction &Pos) {
Chris Lattner0c967662004-09-24 15:21:34 +0000272 if (V->getType() == Ty) return V;
Misha Brukmanfd939082005-04-21 23:48:37 +0000273
Chris Lattnere2ed0572006-04-06 19:19:17 +0000274 if (Constant *CV = dyn_cast<Constant>(V))
Reid Spencer17212df2006-12-12 09:18:51 +0000275 return ConstantExpr::getCast(opc, CV, Ty);
Chris Lattnere2ed0572006-04-06 19:19:17 +0000276
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000277 Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000278 AddToWorkList(C);
Chris Lattner0c967662004-09-24 15:21:34 +0000279 return C;
280 }
Chris Lattner6d0339d2008-01-13 22:23:22 +0000281
282 Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
283 return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
284 }
285
Chris Lattner0c967662004-09-24 15:21:34 +0000286
Chris Lattner8b170942002-08-09 23:47:40 +0000287 // ReplaceInstUsesWith - This method is to be used when an instruction is
288 // found to be dead, replacable with another preexisting expression. Here
289 // we add all uses of I to the worklist, replace all uses of I with the new
290 // value, then return I, so that the inst combiner will know that I was
291 // modified.
292 //
293 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000294 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner15a76c02004-04-05 02:10:19 +0000295 if (&I != V) {
296 I.replaceAllUsesWith(V);
297 return &I;
298 } else {
299 // If we are replacing the instruction with itself, this must be in a
300 // segment of unreachable code, so just clobber the instruction.
Chris Lattner17be6352004-10-18 02:59:09 +0000301 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +0000302 return &I;
303 }
Chris Lattner8b170942002-08-09 23:47:40 +0000304 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000305
306 // EraseInstFromFunction - When dealing with an instruction that has side
307 // effects or produces a void value, we can't rely on DCE to delete the
308 // instruction. Instead, visit methods should return the value returned by
309 // this function.
310 Instruction *EraseInstFromFunction(Instruction &I) {
311 assert(I.use_empty() && "Cannot erase instruction that is used!");
312 AddUsesToWorkList(I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000313 RemoveFromWorkList(&I);
Chris Lattner954f66a2004-11-18 21:41:39 +0000314 I.eraseFromParent();
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000315 return 0; // Don't do anything with FI
316 }
Chris Lattner173234a2008-06-02 01:18:21 +0000317
318 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
319 APInt &KnownOne, unsigned Depth = 0) const {
320 return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
321 }
322
323 bool MaskedValueIsZero(Value *V, const APInt &Mask,
324 unsigned Depth = 0) const {
325 return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
326 }
327 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
328 return llvm::ComputeNumSignBits(Op, TD, Depth);
329 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000330
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000331 private:
Chris Lattner24c8e382003-07-24 17:35:25 +0000332
Reid Spencere4d87aa2006-12-23 06:05:41 +0000333 /// SimplifyCommutative - This performs a few simplifications for
334 /// commutative operators.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000335 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000336
Reid Spencere4d87aa2006-12-23 06:05:41 +0000337 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
338 /// most-complex to least-complex order.
339 bool SimplifyCompare(CmpInst &I);
340
Chris Lattner886ab6c2009-01-31 08:15:18 +0000341 /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
342 /// based on the demanded bits.
343 Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
344 APInt& KnownZero, APInt& KnownOne,
345 unsigned Depth);
346 bool SimplifyDemandedBits(Use &U, APInt DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +0000347 APInt& KnownZero, APInt& KnownOne,
Chris Lattner886ab6c2009-01-31 08:15:18 +0000348 unsigned Depth=0);
349
350 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
351 /// SimplifyDemandedBits knows about. See if the instruction has any
352 /// properties that allow us to simplify its operands.
353 bool SimplifyDemandedInstructionBits(Instruction &Inst);
354
Chris Lattner867b99f2006-10-05 06:55:50 +0000355 Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
356 uint64_t &UndefElts, unsigned Depth = 0);
357
Chris Lattner4e998b22004-09-29 05:07:12 +0000358 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
359 // PHI node as operand #0, see if we can fold the instruction into the PHI
360 // (which is only possible if all operands to the PHI are constants).
361 Instruction *FoldOpIntoPhi(Instruction &I);
362
Chris Lattnerbac32862004-11-14 19:13:23 +0000363 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
364 // operator and they all are only used by the PHI, PHI together their
365 // inputs, and do the operation once, to the result of the PHI.
366 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
Chris Lattner7da52b22006-11-01 04:51:18 +0000367 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
Chris Lattner05f18922008-12-01 02:34:36 +0000368 Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
369
Chris Lattner7da52b22006-11-01 04:51:18 +0000370
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000371 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
372 ConstantInt *AndRHS, BinaryOperator &TheAnd);
Chris Lattnerc8e77562005-09-18 04:24:45 +0000373
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000374 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
Chris Lattnerc8e77562005-09-18 04:24:45 +0000375 bool isSub, Instruction &I);
Chris Lattnera96879a2004-09-29 17:40:11 +0000376 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000377 bool isSigned, bool Inside, Instruction &IB);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000378 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
Chris Lattnerafe91a52006-06-15 19:07:26 +0000379 Instruction *MatchBSwap(BinaryOperator &I);
Chris Lattner3284d1f2007-04-15 00:07:55 +0000380 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000381 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +0000382 Instruction *SimplifyMemSet(MemSetInst *MI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000383
Chris Lattnerafe91a52006-06-15 19:07:26 +0000384
Reid Spencerc55b2432006-12-13 18:21:21 +0000385 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000386
Dan Gohmaneee962e2008-04-10 18:43:06 +0000387 bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
Evan Cheng4e56ab22009-01-16 02:11:43 +0000388 unsigned CastOpc, int &NumCastsRemoved);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000389 unsigned GetOrEnforceKnownAlignment(Value *V,
390 unsigned PrefAlign = 0);
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000391
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000392 };
393}
394
Dan Gohman844731a2008-05-13 00:00:25 +0000395char InstCombiner::ID = 0;
396static RegisterPass<InstCombiner>
397X("instcombine", "Combine redundant instructions");
398
Chris Lattner4f98c562003-03-10 21:43:22 +0000399// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattnere87597f2004-10-16 18:11:37 +0000400// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattner4f98c562003-03-10 21:43:22 +0000401static unsigned getComplexity(Value *V) {
402 if (isa<Instruction>(V)) {
403 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattnere87597f2004-10-16 18:11:37 +0000404 return 3;
405 return 4;
Chris Lattner4f98c562003-03-10 21:43:22 +0000406 }
Chris Lattnere87597f2004-10-16 18:11:37 +0000407 if (isa<Argument>(V)) return 3;
408 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattner4f98c562003-03-10 21:43:22 +0000409}
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000410
Chris Lattnerc8802d22003-03-11 00:12:48 +0000411// isOnlyUse - Return true if this instruction will be deleted if we stop using
412// it.
413static bool isOnlyUse(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000414 return V->hasOneUse() || isa<Constant>(V);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000415}
416
Chris Lattner4cb170c2004-02-23 06:38:22 +0000417// getPromotedType - Return the specified type promoted as it would be to pass
418// though a va_arg area...
419static const Type *getPromotedType(const Type *Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000420 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
421 if (ITy->getBitWidth() < 32)
422 return Type::Int32Ty;
Chris Lattner2b7e0ad2007-05-23 01:17:04 +0000423 }
Reid Spencera54b7cb2007-01-12 07:05:14 +0000424 return Ty;
Chris Lattner4cb170c2004-02-23 06:38:22 +0000425}
426
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000427/// getBitCastOperand - If the specified operand is a CastInst, a constant
428/// expression bitcast, or a GetElementPtrInst with all zero indices, return the
429/// operand value, otherwise return null.
Reid Spencer3da59db2006-11-27 01:05:10 +0000430static Value *getBitCastOperand(Value *V) {
431 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000432 // BitCastInst?
Chris Lattnereed48272005-09-13 00:40:14 +0000433 return I->getOperand(0);
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000434 else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(V)) {
435 // GetElementPtrInst?
436 if (GEP->hasAllZeroIndices())
437 return GEP->getOperand(0);
438 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
Reid Spencer3da59db2006-11-27 01:05:10 +0000439 if (CE->getOpcode() == Instruction::BitCast)
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000440 // BitCast ConstantExp?
Chris Lattnereed48272005-09-13 00:40:14 +0000441 return CE->getOperand(0);
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000442 else if (CE->getOpcode() == Instruction::GetElementPtr) {
443 // GetElementPtr ConstantExp?
444 for (User::op_iterator I = CE->op_begin() + 1, E = CE->op_end();
445 I != E; ++I) {
446 ConstantInt *CI = dyn_cast<ConstantInt>(I);
447 if (!CI || !CI->isZero())
448 // Any non-zero indices? Not cast-like.
449 return 0;
450 }
451 // All-zero indices? This is just like casting.
452 return CE->getOperand(0);
453 }
454 }
Chris Lattnereed48272005-09-13 00:40:14 +0000455 return 0;
456}
457
Reid Spencer3da59db2006-11-27 01:05:10 +0000458/// This function is a wrapper around CastInst::isEliminableCastPair. It
459/// simply extracts arguments and returns what that function returns.
Reid Spencer3da59db2006-11-27 01:05:10 +0000460static Instruction::CastOps
461isEliminableCastPair(
462 const CastInst *CI, ///< The first cast instruction
463 unsigned opcode, ///< The opcode of the second cast instruction
464 const Type *DstTy, ///< The target type for the second cast instruction
465 TargetData *TD ///< The target data for pointer size
466) {
467
468 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
469 const Type *MidTy = CI->getType(); // B from above
Chris Lattner33a61132006-05-06 09:00:16 +0000470
Reid Spencer3da59db2006-11-27 01:05:10 +0000471 // Get the opcodes of the two Cast instructions
472 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
473 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner33a61132006-05-06 09:00:16 +0000474
Reid Spencer3da59db2006-11-27 01:05:10 +0000475 return Instruction::CastOps(
476 CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
477 DstTy, TD->getIntPtrType()));
Chris Lattner33a61132006-05-06 09:00:16 +0000478}
479
480/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
481/// in any code being generated. It does not require codegen if V is simple
482/// enough or if the cast can be folded into other casts.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000483static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
484 const Type *Ty, TargetData *TD) {
Chris Lattner33a61132006-05-06 09:00:16 +0000485 if (V->getType() == Ty || isa<Constant>(V)) return false;
486
Chris Lattner01575b72006-05-25 23:24:33 +0000487 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner33a61132006-05-06 09:00:16 +0000488 if (const CastInst *CI = dyn_cast<CastInst>(V))
Reid Spencere4d87aa2006-12-23 06:05:41 +0000489 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner33a61132006-05-06 09:00:16 +0000490 return false;
491 return true;
492}
493
Chris Lattner4f98c562003-03-10 21:43:22 +0000494// SimplifyCommutative - This performs a few simplifications for commutative
495// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000496//
Chris Lattner4f98c562003-03-10 21:43:22 +0000497// 1. Order operands such that they are listed from right (least complex) to
498// left (most complex). This puts constants before unary operators before
499// binary operators.
500//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000501// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
502// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000503//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000504bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000505 bool Changed = false;
506 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
507 Changed = !I.swapOperands();
Misha Brukmanfd939082005-04-21 23:48:37 +0000508
Chris Lattner4f98c562003-03-10 21:43:22 +0000509 if (!I.isAssociative()) return Changed;
510 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000511 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
512 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
513 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner2a9c8472003-05-27 16:40:51 +0000514 Constant *Folded = ConstantExpr::get(I.getOpcode(),
515 cast<Constant>(I.getOperand(1)),
516 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000517 I.setOperand(0, Op->getOperand(0));
518 I.setOperand(1, Folded);
519 return true;
520 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
521 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
522 isOnlyUse(Op) && isOnlyUse(Op1)) {
523 Constant *C1 = cast<Constant>(Op->getOperand(1));
524 Constant *C2 = cast<Constant>(Op1->getOperand(1));
525
526 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner2a9c8472003-05-27 16:40:51 +0000527 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000528 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Chris Lattnerc8802d22003-03-11 00:12:48 +0000529 Op1->getOperand(0),
530 Op1->getName(), &I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000531 AddToWorkList(New);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000532 I.setOperand(0, New);
533 I.setOperand(1, Folded);
534 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000535 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000536 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000537 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000538}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000539
Reid Spencere4d87aa2006-12-23 06:05:41 +0000540/// SimplifyCompare - For a CmpInst this function just orders the operands
541/// so that theyare listed from right (least complex) to left (most complex).
542/// This puts constants before unary operators before binary operators.
543bool InstCombiner::SimplifyCompare(CmpInst &I) {
544 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
545 return false;
546 I.swapOperands();
547 // Compare instructions are not associative so there's nothing else we can do.
548 return true;
549}
550
Chris Lattner8d969642003-03-10 23:06:50 +0000551// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
552// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000553//
Chris Lattner8d969642003-03-10 23:06:50 +0000554static inline Value *dyn_castNegVal(Value *V) {
555 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000556 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000557
Chris Lattner0ce85802004-12-14 20:08:06 +0000558 // Constants can be considered to be negated values if they can be folded.
559 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
560 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000561
562 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
563 if (C->getType()->getElementType()->isInteger())
564 return ConstantExpr::getNeg(C);
565
Chris Lattner8d969642003-03-10 23:06:50 +0000566 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000567}
568
Chris Lattner8d969642003-03-10 23:06:50 +0000569static inline Value *dyn_castNotVal(Value *V) {
570 if (BinaryOperator::isNot(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000571 return BinaryOperator::getNotArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000572
573 // Constants can be considered to be not'ed values...
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000574 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Zhou Sheng4a1822a2007-04-02 13:45:30 +0000575 return ConstantInt::get(~C->getValue());
Chris Lattner8d969642003-03-10 23:06:50 +0000576 return 0;
577}
578
Chris Lattnerc8802d22003-03-11 00:12:48 +0000579// dyn_castFoldableMul - If this value is a multiply that can be folded into
580// other computations (because it has a constant operand), return the
Chris Lattner50af16a2004-11-13 19:50:12 +0000581// non-constant operand of the multiply, and set CST to point to the multiplier.
582// Otherwise, return null.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000583//
Chris Lattner50af16a2004-11-13 19:50:12 +0000584static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattner42a75512007-01-15 02:27:26 +0000585 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner50af16a2004-11-13 19:50:12 +0000586 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000587 if (I->getOpcode() == Instruction::Mul)
Chris Lattner50e60c72004-11-15 05:54:07 +0000588 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000589 return I->getOperand(0);
Chris Lattner50af16a2004-11-13 19:50:12 +0000590 if (I->getOpcode() == Instruction::Shl)
Chris Lattner50e60c72004-11-15 05:54:07 +0000591 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000592 // The multiplier is really 1 << CST.
Zhou Sheng97b52c22007-03-29 01:57:21 +0000593 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000594 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Zhou Sheng97b52c22007-03-29 01:57:21 +0000595 CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
Chris Lattner50af16a2004-11-13 19:50:12 +0000596 return I->getOperand(0);
597 }
598 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000599 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000600}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000601
Chris Lattner574da9b2005-01-13 20:14:25 +0000602/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
603/// expression, return it.
604static User *dyn_castGetElementPtr(Value *V) {
605 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
606 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
607 if (CE->getOpcode() == Instruction::GetElementPtr)
608 return cast<User>(V);
609 return false;
610}
611
Dan Gohmaneee962e2008-04-10 18:43:06 +0000612/// getOpcode - If this is an Instruction or a ConstantExpr, return the
613/// opcode value. Otherwise return UserOp1.
Dan Gohmanb99e2e22008-05-29 19:53:46 +0000614static unsigned getOpcode(const Value *V) {
615 if (const Instruction *I = dyn_cast<Instruction>(V))
Dan Gohmaneee962e2008-04-10 18:43:06 +0000616 return I->getOpcode();
Dan Gohmanb99e2e22008-05-29 19:53:46 +0000617 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Dan Gohmaneee962e2008-04-10 18:43:06 +0000618 return CE->getOpcode();
619 // Use UserOp1 to mean there's no opcode.
620 return Instruction::UserOp1;
621}
622
Reid Spencer7177c3a2007-03-25 05:33:51 +0000623/// AddOne - Add one to a ConstantInt
Chris Lattnera96879a2004-09-29 17:40:11 +0000624static ConstantInt *AddOne(ConstantInt *C) {
Reid Spencer2149a9d2007-03-25 19:55:33 +0000625 APInt Val(C->getValue());
626 return ConstantInt::get(++Val);
Chris Lattner955f3312004-09-28 21:48:02 +0000627}
Reid Spencer7177c3a2007-03-25 05:33:51 +0000628/// SubOne - Subtract one from a ConstantInt
Chris Lattnera96879a2004-09-29 17:40:11 +0000629static ConstantInt *SubOne(ConstantInt *C) {
Reid Spencer2149a9d2007-03-25 19:55:33 +0000630 APInt Val(C->getValue());
631 return ConstantInt::get(--Val);
Reid Spencer7177c3a2007-03-25 05:33:51 +0000632}
633/// Add - Add two ConstantInts together
634static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
635 return ConstantInt::get(C1->getValue() + C2->getValue());
636}
637/// And - Bitwise AND two ConstantInts together
638static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
639 return ConstantInt::get(C1->getValue() & C2->getValue());
640}
641/// Subtract - Subtract one ConstantInt from another
642static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
643 return ConstantInt::get(C1->getValue() - C2->getValue());
644}
645/// Multiply - Multiply two ConstantInts together
646static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
647 return ConstantInt::get(C1->getValue() * C2->getValue());
Chris Lattner955f3312004-09-28 21:48:02 +0000648}
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000649/// MultiplyOverflows - True if the multiply can not be expressed in an int
650/// this size.
651static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
652 uint32_t W = C1->getBitWidth();
653 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
654 if (sign) {
655 LHSExt.sext(W * 2);
656 RHSExt.sext(W * 2);
657 } else {
658 LHSExt.zext(W * 2);
659 RHSExt.zext(W * 2);
660 }
661
662 APInt MulExt = LHSExt * RHSExt;
663
664 if (sign) {
665 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
666 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
667 return MulExt.slt(Min) || MulExt.sgt(Max);
668 } else
669 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
670}
Chris Lattner955f3312004-09-28 21:48:02 +0000671
Reid Spencere7816b52007-03-08 01:52:58 +0000672
Chris Lattner255d8912006-02-11 09:31:47 +0000673/// ShrinkDemandedConstant - Check to see if the specified operand of the
674/// specified instruction is a constant integer. If so, check to see if there
675/// are any bits set in the constant that are not demanded. If so, shrink the
676/// constant and return true.
677static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000678 APInt Demanded) {
679 assert(I && "No instruction?");
680 assert(OpNo < I->getNumOperands() && "Operand index too large");
681
682 // If the operand is not a constant integer, nothing to do.
683 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
684 if (!OpC) return false;
685
686 // If there are no bits set that aren't demanded, nothing to do.
687 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
688 if ((~Demanded & OpC->getValue()) == 0)
689 return false;
690
691 // This instruction is producing bits that are not demanded. Shrink the RHS.
692 Demanded &= OpC->getValue();
693 I->setOperand(OpNo, ConstantInt::get(Demanded));
694 return true;
695}
696
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000697// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
698// set of known zero and one bits, compute the maximum and minimum values that
699// could have the specified known zero and known one bits, returning them in
700// min/max.
701static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
Reid Spencer0460fb32007-03-22 20:36:03 +0000702 const APInt& KnownZero,
703 const APInt& KnownOne,
704 APInt& Min, APInt& Max) {
705 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
706 assert(KnownZero.getBitWidth() == BitWidth &&
707 KnownOne.getBitWidth() == BitWidth &&
708 Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
709 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000710 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000711
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000712 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
713 // bit if it is unknown.
714 Min = KnownOne;
715 Max = KnownOne|UnknownBits;
716
Zhou Sheng4acf1552007-03-28 05:15:57 +0000717 if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
Zhou Sheng4a1822a2007-04-02 13:45:30 +0000718 Min.set(BitWidth-1);
719 Max.clear(BitWidth-1);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000720 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000721}
722
723// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
724// a set of known zero and one bits, compute the maximum and minimum values that
725// could have the specified known zero and known one bits, returning them in
726// min/max.
727static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
Chris Lattnera9ff5eb2007-08-05 08:47:58 +0000728 const APInt &KnownZero,
729 const APInt &KnownOne,
730 APInt &Min, APInt &Max) {
731 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth(); BitWidth = BitWidth;
Reid Spencer0460fb32007-03-22 20:36:03 +0000732 assert(KnownZero.getBitWidth() == BitWidth &&
733 KnownOne.getBitWidth() == BitWidth &&
734 Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
735 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000736 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000737
738 // The minimum value is when the unknown bits are all zeros.
739 Min = KnownOne;
740 // The maximum value is when the unknown bits are all ones.
741 Max = KnownOne|UnknownBits;
742}
Chris Lattner255d8912006-02-11 09:31:47 +0000743
Chris Lattner886ab6c2009-01-31 08:15:18 +0000744/// SimplifyDemandedInstructionBits - Inst is an integer instruction that
745/// SimplifyDemandedBits knows about. See if the instruction has any
746/// properties that allow us to simplify its operands.
747bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
748 unsigned BitWidth = cast<IntegerType>(Inst.getType())->getBitWidth();
749 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
750 APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
751
752 Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask,
753 KnownZero, KnownOne, 0);
754 if (V == 0) return false;
755 if (V == &Inst) return true;
756 ReplaceInstUsesWith(Inst, V);
757 return true;
758}
759
760/// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
761/// specified instruction operand if possible, updating it in place. It returns
762/// true if it made any change and false otherwise.
763bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask,
764 APInt &KnownZero, APInt &KnownOne,
765 unsigned Depth) {
766 Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
767 KnownZero, KnownOne, Depth);
768 if (NewVal == 0) return false;
769 U.set(NewVal);
770 return true;
771}
772
773
774/// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
775/// value based on the demanded bits. When this function is called, it is known
Reid Spencer8cb68342007-03-12 17:25:59 +0000776/// that only the bits set in DemandedMask of the result of V are ever used
777/// downstream. Consequently, depending on the mask and V, it may be possible
778/// to replace V with a constant or one of its operands. In such cases, this
779/// function does the replacement and returns true. In all other cases, it
780/// returns false after analyzing the expression and setting KnownOne and known
Chris Lattner886ab6c2009-01-31 08:15:18 +0000781/// to be one in the expression. KnownZero contains all the bits that are known
Reid Spencer8cb68342007-03-12 17:25:59 +0000782/// to be zero in the expression. These are provided to potentially allow the
783/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
784/// the expression. KnownOne and KnownZero always follow the invariant that
785/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
786/// the bits in KnownOne and KnownZero may only be accurate for those bits set
787/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
788/// and KnownOne must all be the same.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000789///
790/// This returns null if it did not change anything and it permits no
791/// simplification. This returns V itself if it did some simplification of V's
792/// operands based on the information about what bits are demanded. This returns
793/// some other non-null value if it found out that V is equal to another value
794/// in the context where the specified bits are demanded, but not for all users.
795Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
796 APInt &KnownZero, APInt &KnownOne,
797 unsigned Depth) {
Reid Spencer8cb68342007-03-12 17:25:59 +0000798 assert(V != 0 && "Null pointer of Value???");
799 assert(Depth <= 6 && "Limit Search Depth");
800 uint32_t BitWidth = DemandedMask.getBitWidth();
801 const IntegerType *VTy = cast<IntegerType>(V->getType());
802 assert(VTy->getBitWidth() == BitWidth &&
803 KnownZero.getBitWidth() == BitWidth &&
804 KnownOne.getBitWidth() == BitWidth &&
805 "Value *V, DemandedMask, KnownZero and KnownOne \
806 must have same BitWidth");
807 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
808 // We know all of the bits for a constant!
809 KnownOne = CI->getValue() & DemandedMask;
810 KnownZero = ~KnownOne & DemandedMask;
Chris Lattner886ab6c2009-01-31 08:15:18 +0000811 return 0;
Reid Spencer8cb68342007-03-12 17:25:59 +0000812 }
813
Chris Lattner08d2cc72009-01-31 07:26:06 +0000814 KnownZero.clear();
Zhou Sheng96704452007-03-14 03:21:24 +0000815 KnownOne.clear();
Chris Lattner886ab6c2009-01-31 08:15:18 +0000816 if (DemandedMask == 0) { // Not demanding any bits from V.
817 if (isa<UndefValue>(V))
818 return 0;
819 return UndefValue::get(VTy);
820 } else if (!V->hasOneUse()) { // Other users may use these bits.
Reid Spencer8cb68342007-03-12 17:25:59 +0000821 if (Depth != 0) { // Not at the root.
822 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
823 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
Chris Lattner886ab6c2009-01-31 08:15:18 +0000824 return 0;
Reid Spencer8cb68342007-03-12 17:25:59 +0000825 }
826 // If this is the root being simplified, allow it to have multiple uses,
827 // just set the DemandedMask to all bits.
828 DemandedMask = APInt::getAllOnesValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +0000829 } else if (Depth == 6) { // Limit search depth.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000830 return 0;
Reid Spencer8cb68342007-03-12 17:25:59 +0000831 }
832
833 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattner886ab6c2009-01-31 08:15:18 +0000834 if (!I) return 0; // Only analyze instructions.
Reid Spencer8cb68342007-03-12 17:25:59 +0000835
Reid Spencer8cb68342007-03-12 17:25:59 +0000836 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
837 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
838 switch (I->getOpcode()) {
Dan Gohman23e8b712008-04-28 17:02:21 +0000839 default:
Chris Lattner886ab6c2009-01-31 08:15:18 +0000840 ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Dan Gohman23e8b712008-04-28 17:02:21 +0000841 break;
Reid Spencer8cb68342007-03-12 17:25:59 +0000842 case Instruction::And:
843 // If either the LHS or the RHS are Zero, the result is zero.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000844 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
845 RHSKnownZero, RHSKnownOne, Depth+1) ||
846 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
Reid Spencer8cb68342007-03-12 17:25:59 +0000847 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000848 return I;
849 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
850 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000851
852 // If all of the demanded bits are known 1 on one side, return the other.
853 // These bits cannot contribute to the result of the 'and'.
854 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
855 (DemandedMask & ~LHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000856 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000857 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
858 (DemandedMask & ~RHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000859 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000860
861 // If all of the demanded bits in the inputs are known zeros, return zero.
862 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +0000863 return Constant::getNullValue(VTy);
Reid Spencer8cb68342007-03-12 17:25:59 +0000864
865 // If the RHS is a constant, see if we can simplify it.
866 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000867 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +0000868
869 // Output known-1 bits are only known if set in both the LHS & RHS.
870 RHSKnownOne &= LHSKnownOne;
871 // Output known-0 are known to be clear if zero in either the LHS | RHS.
872 RHSKnownZero |= LHSKnownZero;
873 break;
874 case Instruction::Or:
875 // If either the LHS or the RHS are One, the result is One.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000876 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
877 RHSKnownZero, RHSKnownOne, Depth+1) ||
878 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne,
Reid Spencer8cb68342007-03-12 17:25:59 +0000879 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000880 return I;
881 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
882 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000883
884 // If all of the demanded bits are known zero on one side, return the other.
885 // These bits cannot contribute to the result of the 'or'.
886 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
887 (DemandedMask & ~LHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000888 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000889 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
890 (DemandedMask & ~RHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000891 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000892
893 // If all of the potentially set bits on one side are known to be set on
894 // the other side, just use the 'other' side.
895 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
896 (DemandedMask & (~RHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000897 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000898 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
899 (DemandedMask & (~LHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000900 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000901
902 // If the RHS is a constant, see if we can simplify it.
903 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000904 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +0000905
906 // Output known-0 bits are only known if clear in both the LHS & RHS.
907 RHSKnownZero &= LHSKnownZero;
908 // Output known-1 are known to be set if set in either the LHS | RHS.
909 RHSKnownOne |= LHSKnownOne;
910 break;
911 case Instruction::Xor: {
Chris Lattner886ab6c2009-01-31 08:15:18 +0000912 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
913 RHSKnownZero, RHSKnownOne, Depth+1) ||
914 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +0000915 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000916 return I;
917 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
918 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000919
920 // If all of the demanded bits are known zero on one side, return the other.
921 // These bits cannot contribute to the result of the 'xor'.
922 if ((DemandedMask & RHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +0000923 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000924 if ((DemandedMask & LHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +0000925 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000926
927 // Output known-0 bits are known if clear or set in both the LHS & RHS.
928 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
929 (RHSKnownOne & LHSKnownOne);
930 // Output known-1 are known to be set if set in only one of the LHS, RHS.
931 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
932 (RHSKnownOne & LHSKnownZero);
933
934 // If all of the demanded bits are known to be zero on one side or the
935 // other, turn this into an *inclusive* or.
936 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
937 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
938 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000939 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +0000940 I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +0000941 return InsertNewInstBefore(Or, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +0000942 }
943
944 // If all of the demanded bits on one side are known, and all of the set
945 // bits on that side are also known to be set on the other side, turn this
946 // into an AND, as we know the bits will be cleared.
947 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
948 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
949 // all known
950 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
951 Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
952 Instruction *And =
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000953 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
Chris Lattner886ab6c2009-01-31 08:15:18 +0000954 return InsertNewInstBefore(And, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +0000955 }
956 }
957
958 // If the RHS is a constant, see if we can simplify it.
959 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
960 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000961 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +0000962
963 RHSKnownZero = KnownZeroOut;
964 RHSKnownOne = KnownOneOut;
965 break;
966 }
967 case Instruction::Select:
Chris Lattner886ab6c2009-01-31 08:15:18 +0000968 if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
969 RHSKnownZero, RHSKnownOne, Depth+1) ||
970 SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +0000971 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000972 return I;
973 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
974 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000975
976 // If the operands are constants, see if we can simplify them.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000977 if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
978 ShrinkDemandedConstant(I, 2, DemandedMask))
979 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +0000980
981 // Only known if known in both the LHS and RHS.
982 RHSKnownOne &= LHSKnownOne;
983 RHSKnownZero &= LHSKnownZero;
984 break;
985 case Instruction::Trunc: {
Chris Lattner886ab6c2009-01-31 08:15:18 +0000986 unsigned truncBf = I->getOperand(0)->getType()->getPrimitiveSizeInBits();
Zhou Sheng01542f32007-03-29 02:26:30 +0000987 DemandedMask.zext(truncBf);
988 RHSKnownZero.zext(truncBf);
989 RHSKnownOne.zext(truncBf);
Chris Lattner886ab6c2009-01-31 08:15:18 +0000990 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +0000991 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000992 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +0000993 DemandedMask.trunc(BitWidth);
994 RHSKnownZero.trunc(BitWidth);
995 RHSKnownOne.trunc(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +0000996 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000997 break;
998 }
999 case Instruction::BitCast:
1000 if (!I->getOperand(0)->getType()->isInteger())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001001 return false; // vector->int or fp->int?
1002 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001003 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001004 return I;
1005 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001006 break;
1007 case Instruction::ZExt: {
1008 // Compute the bits in the result that are not present in the input.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001009 unsigned SrcBitWidth =I->getOperand(0)->getType()->getPrimitiveSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001010
Zhou Shengd48653a2007-03-29 04:45:55 +00001011 DemandedMask.trunc(SrcBitWidth);
1012 RHSKnownZero.trunc(SrcBitWidth);
1013 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001014 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +00001015 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001016 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001017 DemandedMask.zext(BitWidth);
1018 RHSKnownZero.zext(BitWidth);
1019 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001020 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001021 // The top bits are known to be zero.
Zhou Sheng01542f32007-03-29 02:26:30 +00001022 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001023 break;
1024 }
1025 case Instruction::SExt: {
1026 // Compute the bits in the result that are not present in the input.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001027 unsigned SrcBitWidth =I->getOperand(0)->getType()->getPrimitiveSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001028
Reid Spencer8cb68342007-03-12 17:25:59 +00001029 APInt InputDemandedBits = DemandedMask &
Zhou Sheng01542f32007-03-29 02:26:30 +00001030 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001031
Zhou Sheng01542f32007-03-29 02:26:30 +00001032 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
Reid Spencer8cb68342007-03-12 17:25:59 +00001033 // If any of the sign extended bits are demanded, we know that the sign
1034 // bit is demanded.
1035 if ((NewBits & DemandedMask) != 0)
Zhou Sheng4a1822a2007-04-02 13:45:30 +00001036 InputDemandedBits.set(SrcBitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001037
Zhou Shengd48653a2007-03-29 04:45:55 +00001038 InputDemandedBits.trunc(SrcBitWidth);
1039 RHSKnownZero.trunc(SrcBitWidth);
1040 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001041 if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
Zhou Sheng01542f32007-03-29 02:26:30 +00001042 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001043 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001044 InputDemandedBits.zext(BitWidth);
1045 RHSKnownZero.zext(BitWidth);
1046 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001047 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001048
1049 // If the sign bit of the input is known set or clear, then we know the
1050 // top bits of the result.
1051
1052 // If the input sign bit is known zero, or if the NewBits are not demanded
1053 // convert this into a zero extension.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001054 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001055 // Convert to ZExt cast
Chris Lattner886ab6c2009-01-31 08:15:18 +00001056 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1057 return InsertNewInstBefore(NewCast, *I);
Zhou Sheng01542f32007-03-29 02:26:30 +00001058 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
Reid Spencer8cb68342007-03-12 17:25:59 +00001059 RHSKnownOne |= NewBits;
Reid Spencer8cb68342007-03-12 17:25:59 +00001060 }
1061 break;
1062 }
1063 case Instruction::Add: {
1064 // Figure out what the input bits are. If the top bits of the and result
1065 // are not demanded, then the add doesn't demand them from its input
1066 // either.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001067 unsigned NLZ = DemandedMask.countLeadingZeros();
Reid Spencer8cb68342007-03-12 17:25:59 +00001068
1069 // If there is a constant on the RHS, there are a variety of xformations
1070 // we can do.
1071 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1072 // If null, this should be simplified elsewhere. Some of the xforms here
1073 // won't work if the RHS is zero.
1074 if (RHS->isZero())
1075 break;
1076
1077 // If the top bit of the output is demanded, demand everything from the
1078 // input. Otherwise, we demand all the input bits except NLZ top bits.
Zhou Sheng01542f32007-03-29 02:26:30 +00001079 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001080
1081 // Find information about known zero/one bits in the input.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001082 if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits,
Reid Spencer8cb68342007-03-12 17:25:59 +00001083 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001084 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001085
1086 // If the RHS of the add has bits set that can't affect the input, reduce
1087 // the constant.
1088 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001089 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001090
1091 // Avoid excess work.
1092 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1093 break;
1094
1095 // Turn it into OR if input bits are zero.
1096 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1097 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001098 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001099 I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001100 return InsertNewInstBefore(Or, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001101 }
1102
1103 // We can say something about the output known-zero and known-one bits,
1104 // depending on potential carries from the input constant and the
1105 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1106 // bits set and the RHS constant is 0x01001, then we know we have a known
1107 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1108
1109 // To compute this, we first compute the potential carry bits. These are
1110 // the bits which may be modified. I'm not aware of a better way to do
1111 // this scan.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001112 const APInt &RHSVal = RHS->getValue();
Zhou Shengb9cb95f2007-03-31 02:38:39 +00001113 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
Reid Spencer8cb68342007-03-12 17:25:59 +00001114
1115 // Now that we know which bits have carries, compute the known-1/0 sets.
1116
1117 // Bits are known one if they are known zero in one operand and one in the
1118 // other, and there is no input carry.
1119 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1120 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1121
1122 // Bits are known zero if they are known zero in both operands and there
1123 // is no input carry.
1124 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1125 } else {
1126 // If the high-bits of this ADD are not demanded, then it does not demand
1127 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001128 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001129 // Right fill the mask of bits for this ADD to demand the most
1130 // significant bit and all those below it.
Zhou Sheng01542f32007-03-29 02:26:30 +00001131 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001132 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1133 LHSKnownZero, LHSKnownOne, Depth+1) ||
1134 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001135 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001136 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001137 }
1138 }
1139 break;
1140 }
1141 case Instruction::Sub:
1142 // If the high-bits of this SUB are not demanded, then it does not demand
1143 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001144 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001145 // Right fill the mask of bits for this SUB to demand the most
1146 // significant bit and all those below it.
Zhou Sheng4351c642007-04-02 08:20:41 +00001147 uint32_t NLZ = DemandedMask.countLeadingZeros();
Zhou Sheng01542f32007-03-29 02:26:30 +00001148 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001149 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1150 LHSKnownZero, LHSKnownOne, Depth+1) ||
1151 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001152 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001153 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001154 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001155 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1156 // the known zeros and ones.
1157 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001158 break;
1159 case Instruction::Shl:
1160 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001161 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001162 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001163 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001164 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001165 return I;
1166 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001167 RHSKnownZero <<= ShiftAmt;
1168 RHSKnownOne <<= ShiftAmt;
1169 // low bits known zero.
Zhou Shengadc14952007-03-14 09:07:33 +00001170 if (ShiftAmt)
Zhou Shenge9e03f62007-03-28 15:02:20 +00001171 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
Reid Spencer8cb68342007-03-12 17:25:59 +00001172 }
1173 break;
1174 case Instruction::LShr:
1175 // For a logical shift right
1176 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001177 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001178
Reid Spencer8cb68342007-03-12 17:25:59 +00001179 // Unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001180 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001181 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001182 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001183 return I;
1184 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001185 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1186 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
Zhou Shengadc14952007-03-14 09:07:33 +00001187 if (ShiftAmt) {
1188 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001189 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Zhou Shengadc14952007-03-14 09:07:33 +00001190 RHSKnownZero |= HighBits; // high bits known zero.
1191 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001192 }
1193 break;
1194 case Instruction::AShr:
1195 // If this is an arithmetic shift right and only the low-bit is set, we can
1196 // always convert this into a logical shr, even if the shift amount is
1197 // variable. The low bit of the shift cannot be an input sign bit unless
1198 // the shift amount is >= the size of the datatype, which is undefined.
1199 if (DemandedMask == 1) {
1200 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001201 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001202 I->getOperand(0), I->getOperand(1), I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001203 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001204 }
Chris Lattner4241e4d2007-07-15 20:54:51 +00001205
1206 // If the sign bit is the only bit demanded by this ashr, then there is no
1207 // need to do it, the shift doesn't change the high bit.
1208 if (DemandedMask.isSignBit())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001209 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001210
1211 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00001212 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001213
Reid Spencer8cb68342007-03-12 17:25:59 +00001214 // Signed shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001215 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Lauro Ramos Venanciod0499af2007-06-06 17:08:48 +00001216 // If any of the "high bits" are demanded, we should set the sign bit as
1217 // demanded.
1218 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1219 DemandedMaskIn.set(BitWidth-1);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001220 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001221 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001222 return I;
1223 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001224 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001225 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Reid Spencer8cb68342007-03-12 17:25:59 +00001226 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1227 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1228
1229 // Handle the sign bits.
1230 APInt SignBit(APInt::getSignBit(BitWidth));
1231 // Adjust to where it is now in the mask.
1232 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1233
1234 // If the input sign bit is known to be zero, or if none of the top bits
1235 // are demanded, turn this into an unsigned shift right.
Zhou Shengcc419402008-06-06 08:32:05 +00001236 if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] ||
Reid Spencer8cb68342007-03-12 17:25:59 +00001237 (HighBits & ~DemandedMask) == HighBits) {
1238 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001239 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001240 I->getOperand(0), SA, I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001241 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001242 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1243 RHSKnownOne |= HighBits;
1244 }
1245 }
1246 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001247 case Instruction::SRem:
1248 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Nick Lewycky8e394322008-11-02 02:41:50 +00001249 APInt RA = Rem->getValue().abs();
1250 if (RA.isPowerOf2()) {
Nick Lewycky3ac9e102008-07-12 05:04:38 +00001251 if (DemandedMask.ule(RA)) // srem won't affect demanded bits
Chris Lattner886ab6c2009-01-31 08:15:18 +00001252 return I->getOperand(0);
Nick Lewycky3ac9e102008-07-12 05:04:38 +00001253
Nick Lewycky8e394322008-11-02 02:41:50 +00001254 APInt LowBits = RA - 1;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001255 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001256 if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001257 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001258 return I;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001259
1260 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1261 LHSKnownZero |= ~LowBits;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001262
1263 KnownZero |= LHSKnownZero & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001264
Chris Lattner886ab6c2009-01-31 08:15:18 +00001265 assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001266 }
1267 }
1268 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001269 case Instruction::URem: {
Dan Gohman23e8b712008-04-28 17:02:21 +00001270 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1271 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001272 if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1273 KnownZero2, KnownOne2, Depth+1) ||
1274 SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
Dan Gohmane85b7582008-05-01 19:13:24 +00001275 KnownZero2, KnownOne2, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001276 return I;
Dan Gohmane85b7582008-05-01 19:13:24 +00001277
Chris Lattner455e9ab2009-01-21 18:09:24 +00001278 unsigned Leaders = KnownZero2.countLeadingOnes();
Dan Gohman23e8b712008-04-28 17:02:21 +00001279 Leaders = std::max(Leaders,
1280 KnownZero2.countLeadingOnes());
1281 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001282 break;
Reid Spencer8cb68342007-03-12 17:25:59 +00001283 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00001284 case Instruction::Call:
1285 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1286 switch (II->getIntrinsicID()) {
1287 default: break;
1288 case Intrinsic::bswap: {
1289 // If the only bits demanded come from one byte of the bswap result,
1290 // just shift the input byte into position to eliminate the bswap.
1291 unsigned NLZ = DemandedMask.countLeadingZeros();
1292 unsigned NTZ = DemandedMask.countTrailingZeros();
1293
1294 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
1295 // we need all the bits down to bit 8. Likewise, round NLZ. If we
1296 // have 14 leading zeros, round to 8.
1297 NLZ &= ~7;
1298 NTZ &= ~7;
1299 // If we need exactly one byte, we can do this transformation.
1300 if (BitWidth-NLZ-NTZ == 8) {
1301 unsigned ResultBit = NTZ;
1302 unsigned InputBit = BitWidth-NTZ-8;
1303
1304 // Replace this with either a left or right shift to get the byte into
1305 // the right place.
1306 Instruction *NewVal;
1307 if (InputBit > ResultBit)
1308 NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
1309 ConstantInt::get(I->getType(), InputBit-ResultBit));
1310 else
1311 NewVal = BinaryOperator::CreateShl(I->getOperand(1),
1312 ConstantInt::get(I->getType(), ResultBit-InputBit));
1313 NewVal->takeName(I);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001314 return InsertNewInstBefore(NewVal, *I);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001315 }
1316
1317 // TODO: Could compute known zero/one bits based on the input.
1318 break;
1319 }
1320 }
1321 }
Chris Lattner6c3bfba2008-06-18 18:11:55 +00001322 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001323 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001324 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001325
1326 // If the client is only demanding bits that we know, return the known
1327 // constant.
1328 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +00001329 return ConstantInt::get(RHSKnownOne);
Reid Spencer8cb68342007-03-12 17:25:59 +00001330 return false;
1331}
1332
Chris Lattner867b99f2006-10-05 06:55:50 +00001333
Mon P Wangaeb06d22008-11-10 04:46:22 +00001334/// SimplifyDemandedVectorElts - The specified value produces a vector with
Chris Lattner867b99f2006-10-05 06:55:50 +00001335/// 64 or fewer elements. DemandedElts contains the set of elements that are
1336/// actually used by the caller. This method analyzes which elements of the
1337/// operand are undef and returns that information in UndefElts.
1338///
1339/// If the information about demanded elements can be used to simplify the
1340/// operation, the operation is simplified, then the resultant value is
1341/// returned. This returns null if no change was made.
1342Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1343 uint64_t &UndefElts,
1344 unsigned Depth) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001345 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner867b99f2006-10-05 06:55:50 +00001346 assert(VWidth <= 64 && "Vector too wide to analyze!");
1347 uint64_t EltMask = ~0ULL >> (64-VWidth);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001348 assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
Chris Lattner867b99f2006-10-05 06:55:50 +00001349
1350 if (isa<UndefValue>(V)) {
1351 // If the entire vector is undefined, just return this info.
1352 UndefElts = EltMask;
1353 return 0;
1354 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1355 UndefElts = EltMask;
1356 return UndefValue::get(V->getType());
1357 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001358
Chris Lattner867b99f2006-10-05 06:55:50 +00001359 UndefElts = 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001360 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1361 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner867b99f2006-10-05 06:55:50 +00001362 Constant *Undef = UndefValue::get(EltTy);
1363
1364 std::vector<Constant*> Elts;
1365 for (unsigned i = 0; i != VWidth; ++i)
1366 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1367 Elts.push_back(Undef);
1368 UndefElts |= (1ULL << i);
1369 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1370 Elts.push_back(Undef);
1371 UndefElts |= (1ULL << i);
1372 } else { // Otherwise, defined.
1373 Elts.push_back(CP->getOperand(i));
1374 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001375
Chris Lattner867b99f2006-10-05 06:55:50 +00001376 // If we changed the constant, return it.
Reid Spencer9d6565a2007-02-15 02:26:10 +00001377 Constant *NewCP = ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001378 return NewCP != CP ? NewCP : 0;
1379 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001380 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner867b99f2006-10-05 06:55:50 +00001381 // set to undef.
Mon P Wange0b436a2008-11-06 22:52:21 +00001382
1383 // Check if this is identity. If so, return 0 since we are not simplifying
1384 // anything.
1385 if (DemandedElts == ((1ULL << VWidth) -1))
1386 return 0;
1387
Reid Spencer9d6565a2007-02-15 02:26:10 +00001388 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner867b99f2006-10-05 06:55:50 +00001389 Constant *Zero = Constant::getNullValue(EltTy);
1390 Constant *Undef = UndefValue::get(EltTy);
1391 std::vector<Constant*> Elts;
1392 for (unsigned i = 0; i != VWidth; ++i)
1393 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1394 UndefElts = DemandedElts ^ EltMask;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001395 return ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001396 }
1397
Dan Gohman488fbfc2008-09-09 18:11:14 +00001398 // Limit search depth.
1399 if (Depth == 10)
1400 return false;
1401
1402 // If multiple users are using the root value, procede with
1403 // simplification conservatively assuming that all elements
1404 // are needed.
1405 if (!V->hasOneUse()) {
1406 // Quit if we find multiple users of a non-root value though.
1407 // They'll be handled when it's their turn to be visited by
1408 // the main instcombine process.
1409 if (Depth != 0)
Chris Lattner867b99f2006-10-05 06:55:50 +00001410 // TODO: Just compute the UndefElts information recursively.
1411 return false;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001412
1413 // Conservatively assume that all elements are needed.
1414 DemandedElts = EltMask;
Chris Lattner867b99f2006-10-05 06:55:50 +00001415 }
1416
1417 Instruction *I = dyn_cast<Instruction>(V);
1418 if (!I) return false; // Only analyze instructions.
1419
1420 bool MadeChange = false;
1421 uint64_t UndefElts2;
1422 Value *TmpV;
1423 switch (I->getOpcode()) {
1424 default: break;
1425
1426 case Instruction::InsertElement: {
1427 // If this is a variable index, we don't know which element it overwrites.
1428 // demand exactly the same input as we produce.
Reid Spencerb83eb642006-10-20 07:07:24 +00001429 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner867b99f2006-10-05 06:55:50 +00001430 if (Idx == 0) {
1431 // Note that we can't propagate undef elt info, because we don't know
1432 // which elt is getting updated.
1433 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1434 UndefElts2, Depth+1);
1435 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1436 break;
1437 }
1438
1439 // If this is inserting an element that isn't demanded, remove this
1440 // insertelement.
Reid Spencerb83eb642006-10-20 07:07:24 +00001441 unsigned IdxNo = Idx->getZExtValue();
Chris Lattner867b99f2006-10-05 06:55:50 +00001442 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1443 return AddSoonDeadInstToWorklist(*I, 0);
1444
1445 // Otherwise, the element inserted overwrites whatever was there, so the
1446 // input demanded set is simpler than the output set.
1447 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1448 DemandedElts & ~(1ULL << IdxNo),
1449 UndefElts, Depth+1);
1450 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1451
1452 // The inserted element is defined.
Dan Gohman488fbfc2008-09-09 18:11:14 +00001453 UndefElts &= ~(1ULL << IdxNo);
1454 break;
1455 }
1456 case Instruction::ShuffleVector: {
1457 ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001458 uint64_t LHSVWidth =
1459 cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
Dan Gohman488fbfc2008-09-09 18:11:14 +00001460 uint64_t LeftDemanded = 0, RightDemanded = 0;
1461 for (unsigned i = 0; i < VWidth; i++) {
1462 if (DemandedElts & (1ULL << i)) {
1463 unsigned MaskVal = Shuffle->getMaskValue(i);
1464 if (MaskVal != -1u) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00001465 assert(MaskVal < LHSVWidth * 2 &&
Dan Gohman488fbfc2008-09-09 18:11:14 +00001466 "shufflevector mask index out of range!");
Mon P Wangaeb06d22008-11-10 04:46:22 +00001467 if (MaskVal < LHSVWidth)
Dan Gohman488fbfc2008-09-09 18:11:14 +00001468 LeftDemanded |= 1ULL << MaskVal;
1469 else
Mon P Wangaeb06d22008-11-10 04:46:22 +00001470 RightDemanded |= 1ULL << (MaskVal - LHSVWidth);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001471 }
1472 }
1473 }
1474
1475 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
1476 UndefElts2, Depth+1);
1477 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1478
1479 uint64_t UndefElts3;
1480 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1481 UndefElts3, Depth+1);
1482 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1483
1484 bool NewUndefElts = false;
1485 for (unsigned i = 0; i < VWidth; i++) {
1486 unsigned MaskVal = Shuffle->getMaskValue(i);
Dan Gohmancb893092008-09-10 01:09:32 +00001487 if (MaskVal == -1u) {
Dan Gohman488fbfc2008-09-09 18:11:14 +00001488 uint64_t NewBit = 1ULL << i;
1489 UndefElts |= NewBit;
Mon P Wangaeb06d22008-11-10 04:46:22 +00001490 } else if (MaskVal < LHSVWidth) {
Dan Gohman488fbfc2008-09-09 18:11:14 +00001491 uint64_t NewBit = ((UndefElts2 >> MaskVal) & 1) << i;
1492 NewUndefElts |= NewBit;
1493 UndefElts |= NewBit;
1494 } else {
Mon P Wangaeb06d22008-11-10 04:46:22 +00001495 uint64_t NewBit = ((UndefElts3 >> (MaskVal - LHSVWidth)) & 1) << i;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001496 NewUndefElts |= NewBit;
1497 UndefElts |= NewBit;
1498 }
1499 }
1500
1501 if (NewUndefElts) {
1502 // Add additional discovered undefs.
1503 std::vector<Constant*> Elts;
1504 for (unsigned i = 0; i < VWidth; ++i) {
1505 if (UndefElts & (1ULL << i))
1506 Elts.push_back(UndefValue::get(Type::Int32Ty));
1507 else
1508 Elts.push_back(ConstantInt::get(Type::Int32Ty,
1509 Shuffle->getMaskValue(i)));
1510 }
1511 I->setOperand(2, ConstantVector::get(Elts));
1512 MadeChange = true;
1513 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001514 break;
1515 }
Chris Lattner69878332007-04-14 22:29:23 +00001516 case Instruction::BitCast: {
Dan Gohman07a96762007-07-16 14:29:03 +00001517 // Vector->vector casts only.
Chris Lattner69878332007-04-14 22:29:23 +00001518 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1519 if (!VTy) break;
1520 unsigned InVWidth = VTy->getNumElements();
1521 uint64_t InputDemandedElts = 0;
1522 unsigned Ratio;
1523
1524 if (VWidth == InVWidth) {
Dan Gohman07a96762007-07-16 14:29:03 +00001525 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
Chris Lattner69878332007-04-14 22:29:23 +00001526 // elements as are demanded of us.
1527 Ratio = 1;
1528 InputDemandedElts = DemandedElts;
1529 } else if (VWidth > InVWidth) {
1530 // Untested so far.
1531 break;
1532
1533 // If there are more elements in the result than there are in the source,
1534 // then an input element is live if any of the corresponding output
1535 // elements are live.
1536 Ratio = VWidth/InVWidth;
1537 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1538 if (DemandedElts & (1ULL << OutIdx))
1539 InputDemandedElts |= 1ULL << (OutIdx/Ratio);
1540 }
1541 } else {
1542 // Untested so far.
1543 break;
1544
1545 // If there are more elements in the source than there are in the result,
1546 // then an input element is live if the corresponding output element is
1547 // live.
1548 Ratio = InVWidth/VWidth;
1549 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1550 if (DemandedElts & (1ULL << InIdx/Ratio))
1551 InputDemandedElts |= 1ULL << InIdx;
1552 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001553
Chris Lattner69878332007-04-14 22:29:23 +00001554 // div/rem demand all inputs, because they don't want divide by zero.
1555 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1556 UndefElts2, Depth+1);
1557 if (TmpV) {
1558 I->setOperand(0, TmpV);
1559 MadeChange = true;
1560 }
1561
1562 UndefElts = UndefElts2;
1563 if (VWidth > InVWidth) {
1564 assert(0 && "Unimp");
1565 // If there are more elements in the result than there are in the source,
1566 // then an output element is undef if the corresponding input element is
1567 // undef.
1568 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1569 if (UndefElts2 & (1ULL << (OutIdx/Ratio)))
1570 UndefElts |= 1ULL << OutIdx;
1571 } else if (VWidth < InVWidth) {
1572 assert(0 && "Unimp");
1573 // If there are more elements in the source than there are in the result,
1574 // then a result element is undef if all of the corresponding input
1575 // elements are undef.
1576 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1577 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1578 if ((UndefElts2 & (1ULL << InIdx)) == 0) // Not undef?
1579 UndefElts &= ~(1ULL << (InIdx/Ratio)); // Clear undef bit.
1580 }
1581 break;
1582 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001583 case Instruction::And:
1584 case Instruction::Or:
1585 case Instruction::Xor:
1586 case Instruction::Add:
1587 case Instruction::Sub:
1588 case Instruction::Mul:
1589 // div/rem demand all inputs, because they don't want divide by zero.
1590 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1591 UndefElts, Depth+1);
1592 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1593 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1594 UndefElts2, Depth+1);
1595 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1596
1597 // Output elements are undefined if both are undefined. Consider things
1598 // like undef&0. The result is known zero, not undef.
1599 UndefElts &= UndefElts2;
1600 break;
1601
1602 case Instruction::Call: {
1603 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1604 if (!II) break;
1605 switch (II->getIntrinsicID()) {
1606 default: break;
1607
1608 // Binary vector operations that work column-wise. A dest element is a
1609 // function of the corresponding input elements from the two inputs.
1610 case Intrinsic::x86_sse_sub_ss:
1611 case Intrinsic::x86_sse_mul_ss:
1612 case Intrinsic::x86_sse_min_ss:
1613 case Intrinsic::x86_sse_max_ss:
1614 case Intrinsic::x86_sse2_sub_sd:
1615 case Intrinsic::x86_sse2_mul_sd:
1616 case Intrinsic::x86_sse2_min_sd:
1617 case Intrinsic::x86_sse2_max_sd:
1618 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1619 UndefElts, Depth+1);
1620 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1621 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1622 UndefElts2, Depth+1);
1623 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1624
1625 // If only the low elt is demanded and this is a scalarizable intrinsic,
1626 // scalarize it now.
1627 if (DemandedElts == 1) {
1628 switch (II->getIntrinsicID()) {
1629 default: break;
1630 case Intrinsic::x86_sse_sub_ss:
1631 case Intrinsic::x86_sse_mul_ss:
1632 case Intrinsic::x86_sse2_sub_sd:
1633 case Intrinsic::x86_sse2_mul_sd:
1634 // TODO: Lower MIN/MAX/ABS/etc
1635 Value *LHS = II->getOperand(1);
1636 Value *RHS = II->getOperand(2);
1637 // Extract the element as scalars.
1638 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1639 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1640
1641 switch (II->getIntrinsicID()) {
1642 default: assert(0 && "Case stmts out of sync!");
1643 case Intrinsic::x86_sse_sub_ss:
1644 case Intrinsic::x86_sse2_sub_sd:
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001645 TmpV = InsertNewInstBefore(BinaryOperator::CreateSub(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001646 II->getName()), *II);
1647 break;
1648 case Intrinsic::x86_sse_mul_ss:
1649 case Intrinsic::x86_sse2_mul_sd:
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001650 TmpV = InsertNewInstBefore(BinaryOperator::CreateMul(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001651 II->getName()), *II);
1652 break;
1653 }
1654
1655 Instruction *New =
Gabor Greif051a9502008-04-06 20:25:17 +00001656 InsertElementInst::Create(UndefValue::get(II->getType()), TmpV, 0U,
1657 II->getName());
Chris Lattner867b99f2006-10-05 06:55:50 +00001658 InsertNewInstBefore(New, *II);
1659 AddSoonDeadInstToWorklist(*II, 0);
1660 return New;
1661 }
1662 }
1663
1664 // Output elements are undefined if both are undefined. Consider things
1665 // like undef&0. The result is known zero, not undef.
1666 UndefElts &= UndefElts2;
1667 break;
1668 }
1669 break;
1670 }
1671 }
1672 return MadeChange ? I : 0;
1673}
1674
Dan Gohman45b4e482008-05-19 22:14:15 +00001675
Chris Lattner564a7272003-08-13 19:01:45 +00001676/// AssociativeOpt - Perform an optimization on an associative operator. This
1677/// function is designed to check a chain of associative operators for a
1678/// potential to apply a certain optimization. Since the optimization may be
1679/// applicable if the expression was reassociated, this checks the chain, then
1680/// reassociates the expression as necessary to expose the optimization
1681/// opportunity. This makes use of a special Functor, which must define
1682/// 'shouldApply' and 'apply' methods.
1683///
1684template<typename Functor>
Dan Gohman76d402b2008-05-20 01:14:05 +00001685static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
Chris Lattner564a7272003-08-13 19:01:45 +00001686 unsigned Opcode = Root.getOpcode();
1687 Value *LHS = Root.getOperand(0);
1688
1689 // Quick check, see if the immediate LHS matches...
1690 if (F.shouldApply(LHS))
1691 return F.apply(Root);
1692
1693 // Otherwise, if the LHS is not of the same opcode as the root, return.
1694 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +00001695 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +00001696 // Should we apply this transform to the RHS?
1697 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1698
1699 // If not to the RHS, check to see if we should apply to the LHS...
1700 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1701 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1702 ShouldApply = true;
1703 }
1704
1705 // If the functor wants to apply the optimization to the RHS of LHSI,
1706 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1707 if (ShouldApply) {
Chris Lattner564a7272003-08-13 19:01:45 +00001708 // Now all of the instructions are in the current basic block, go ahead
1709 // and perform the reassociation.
1710 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1711
1712 // First move the selected RHS to the LHS of the root...
1713 Root.setOperand(0, LHSI->getOperand(1));
1714
1715 // Make what used to be the LHS of the root be the user of the root...
1716 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +00001717 if (&Root == TmpLHSI) {
Chris Lattner15a76c02004-04-05 02:10:19 +00001718 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1719 return 0;
1720 }
Chris Lattner65725312004-04-16 18:08:07 +00001721 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +00001722 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +00001723 BasicBlock::iterator ARI = &Root; ++ARI;
Dan Gohmand02d9172008-06-19 17:47:47 +00001724 TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root
Chris Lattner65725312004-04-16 18:08:07 +00001725 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +00001726
1727 // Now propagate the ExtraOperand down the chain of instructions until we
1728 // get to LHSI.
1729 while (TmpLHSI != LHSI) {
1730 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +00001731 // Move the instruction to immediately before the chain we are
1732 // constructing to avoid breaking dominance properties.
Dan Gohmand02d9172008-06-19 17:47:47 +00001733 NextLHSI->moveBefore(ARI);
Chris Lattner65725312004-04-16 18:08:07 +00001734 ARI = NextLHSI;
1735
Chris Lattner564a7272003-08-13 19:01:45 +00001736 Value *NextOp = NextLHSI->getOperand(1);
1737 NextLHSI->setOperand(1, ExtraOperand);
1738 TmpLHSI = NextLHSI;
1739 ExtraOperand = NextOp;
1740 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001741
Chris Lattner564a7272003-08-13 19:01:45 +00001742 // Now that the instructions are reassociated, have the functor perform
1743 // the transformation...
1744 return F.apply(Root);
1745 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001746
Chris Lattner564a7272003-08-13 19:01:45 +00001747 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1748 }
1749 return 0;
1750}
1751
Dan Gohman844731a2008-05-13 00:00:25 +00001752namespace {
Chris Lattner564a7272003-08-13 19:01:45 +00001753
Nick Lewycky02d639f2008-05-23 04:34:58 +00001754// AddRHS - Implements: X + X --> X << 1
Chris Lattner564a7272003-08-13 19:01:45 +00001755struct AddRHS {
1756 Value *RHS;
1757 AddRHS(Value *rhs) : RHS(rhs) {}
1758 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1759 Instruction *apply(BinaryOperator &Add) const {
Nick Lewycky02d639f2008-05-23 04:34:58 +00001760 return BinaryOperator::CreateShl(Add.getOperand(0),
1761 ConstantInt::get(Add.getType(), 1));
Chris Lattner564a7272003-08-13 19:01:45 +00001762 }
1763};
1764
1765// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1766// iff C1&C2 == 0
1767struct AddMaskingAnd {
1768 Constant *C2;
1769 AddMaskingAnd(Constant *c) : C2(c) {}
1770 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001771 ConstantInt *C1;
Misha Brukmanfd939082005-04-21 23:48:37 +00001772 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001773 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +00001774 }
1775 Instruction *apply(BinaryOperator &Add) const {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001776 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +00001777 }
1778};
1779
Dan Gohman844731a2008-05-13 00:00:25 +00001780}
1781
Chris Lattner6e7ba452005-01-01 16:22:27 +00001782static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +00001783 InstCombiner *IC) {
Reid Spencer3da59db2006-11-27 01:05:10 +00001784 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00001785 return IC->InsertCastBefore(CI->getOpcode(), SO, I.getType(), I);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001786 }
1787
Chris Lattner2eefe512004-04-09 19:05:30 +00001788 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +00001789 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1790 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +00001791
Chris Lattner2eefe512004-04-09 19:05:30 +00001792 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1793 if (ConstIsRHS)
Chris Lattner6e7ba452005-01-01 16:22:27 +00001794 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1795 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +00001796 }
1797
1798 Value *Op0 = SO, *Op1 = ConstOperand;
1799 if (!ConstIsRHS)
1800 std::swap(Op0, Op1);
1801 Instruction *New;
Chris Lattner6e7ba452005-01-01 16:22:27 +00001802 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001803 New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Reid Spencere4d87aa2006-12-23 06:05:41 +00001804 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001805 New = CmpInst::Create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
Reid Spencere4d87aa2006-12-23 06:05:41 +00001806 SO->getName()+".cmp");
Chris Lattner326c0f32004-04-10 19:15:56 +00001807 else {
Chris Lattner2eefe512004-04-09 19:05:30 +00001808 assert(0 && "Unknown binary instruction type!");
Chris Lattner326c0f32004-04-10 19:15:56 +00001809 abort();
1810 }
Chris Lattner6e7ba452005-01-01 16:22:27 +00001811 return IC->InsertNewInstBefore(New, I);
1812}
1813
1814// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1815// constant as the other operand, try to fold the binary operator into the
1816// select arguments. This also works for Cast instructions, which obviously do
1817// not have a second operand.
1818static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1819 InstCombiner *IC) {
1820 // Don't modify shared select instructions
1821 if (!SI->hasOneUse()) return 0;
1822 Value *TV = SI->getOperand(1);
1823 Value *FV = SI->getOperand(2);
1824
1825 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +00001826 // Bool selects with constant operands can be folded to logical ops.
Reid Spencer4fe16d62007-01-11 18:21:29 +00001827 if (SI->getType() == Type::Int1Ty) return 0;
Chris Lattner956db272005-04-21 05:43:13 +00001828
Chris Lattner6e7ba452005-01-01 16:22:27 +00001829 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1830 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1831
Gabor Greif051a9502008-04-06 20:25:17 +00001832 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1833 SelectFalseVal);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001834 }
1835 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +00001836}
1837
Chris Lattner4e998b22004-09-29 05:07:12 +00001838
1839/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1840/// node as operand #0, see if we can fold the instruction into the PHI (which
1841/// is only possible if all operands to the PHI are constants).
1842Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1843 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00001844 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001845 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner4e998b22004-09-29 05:07:12 +00001846
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001847 // Check to see if all of the operands of the PHI are constants. If there is
1848 // one non-constant value, remember the BB it is. If there is more than one
Chris Lattnerb3036682007-02-24 01:03:45 +00001849 // or if *it* is a PHI, bail out.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001850 BasicBlock *NonConstBB = 0;
1851 for (unsigned i = 0; i != NumPHIValues; ++i)
1852 if (!isa<Constant>(PN->getIncomingValue(i))) {
1853 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +00001854 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001855 NonConstBB = PN->getIncomingBlock(i);
1856
1857 // If the incoming non-constant value is in I's block, we have an infinite
1858 // loop.
1859 if (NonConstBB == I.getParent())
1860 return 0;
1861 }
1862
1863 // If there is exactly one non-constant value, we can insert a copy of the
1864 // operation in that block. However, if this is a critical edge, we would be
1865 // inserting the computation one some other paths (e.g. inside a loop). Only
1866 // do this if the pred block is unconditionally branching into the phi block.
1867 if (NonConstBB) {
1868 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1869 if (!BI || !BI->isUnconditional()) return 0;
1870 }
Chris Lattner4e998b22004-09-29 05:07:12 +00001871
1872 // Okay, we can do the transformation: create the new PHI node.
Gabor Greif051a9502008-04-06 20:25:17 +00001873 PHINode *NewPN = PHINode::Create(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +00001874 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner4e998b22004-09-29 05:07:12 +00001875 InsertNewInstBefore(NewPN, *PN);
Chris Lattner6934a042007-02-11 01:23:03 +00001876 NewPN->takeName(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +00001877
1878 // Next, add all of the operands to the PHI.
1879 if (I.getNumOperands() == 2) {
1880 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +00001881 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00001882 Value *InV = 0;
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001883 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001884 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1885 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1886 else
1887 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001888 } else {
1889 assert(PN->getIncomingBlock(i) == NonConstBB);
1890 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001891 InV = BinaryOperator::Create(BO->getOpcode(),
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001892 PN->getIncomingValue(i), C, "phitmp",
1893 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +00001894 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001895 InV = CmpInst::Create(CI->getOpcode(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00001896 CI->getPredicate(),
1897 PN->getIncomingValue(i), C, "phitmp",
1898 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001899 else
1900 assert(0 && "Unknown binop!");
1901
Chris Lattnerdbab3862007-03-02 21:28:56 +00001902 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001903 }
1904 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00001905 }
Reid Spencer3da59db2006-11-27 01:05:10 +00001906 } else {
1907 CastInst *CI = cast<CastInst>(&I);
1908 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +00001909 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001910 Value *InV;
1911 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00001912 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001913 } else {
1914 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001915 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Reid Spencer3da59db2006-11-27 01:05:10 +00001916 I.getType(), "phitmp",
1917 NonConstBB->getTerminator());
Chris Lattnerdbab3862007-03-02 21:28:56 +00001918 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001919 }
1920 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00001921 }
1922 }
1923 return ReplaceInstUsesWith(I, NewPN);
1924}
1925
Chris Lattner2454a2e2008-01-29 06:52:45 +00001926
Chris Lattner3d28b1b2008-05-20 05:46:13 +00001927/// WillNotOverflowSignedAdd - Return true if we can prove that:
1928/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
1929/// This basically requires proving that the add in the original type would not
1930/// overflow to change the sign bit or have a carry out.
1931bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
1932 // There are different heuristics we can use for this. Here are some simple
1933 // ones.
1934
1935 // Add has the property that adding any two 2's complement numbers can only
1936 // have one carry bit which can change a sign. As such, if LHS and RHS each
1937 // have at least two sign bits, we know that the addition of the two values will
1938 // sign extend fine.
1939 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
1940 return true;
1941
1942
1943 // If one of the operands only has one non-zero bit, and if the other operand
1944 // has a known-zero bit in a more significant place than it (not including the
1945 // sign bit) the ripple may go up to and fill the zero, but won't change the
1946 // sign. For example, (X & ~4) + 1.
1947
1948 // TODO: Implement.
1949
1950 return false;
1951}
1952
Chris Lattner2454a2e2008-01-29 06:52:45 +00001953
Chris Lattner7e708292002-06-25 16:13:24 +00001954Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00001955 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00001956 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +00001957
Chris Lattner66331a42004-04-10 22:01:55 +00001958 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattnere87597f2004-10-16 18:11:37 +00001959 // X + undef -> undef
1960 if (isa<UndefValue>(RHS))
1961 return ReplaceInstUsesWith(I, RHS);
1962
Chris Lattner66331a42004-04-10 22:01:55 +00001963 // X + 0 --> X
Chris Lattner9919e3d2006-12-02 00:13:08 +00001964 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
Chris Lattner5e678e02005-10-17 17:56:38 +00001965 if (RHSC->isNullValue())
1966 return ReplaceInstUsesWith(I, LHS);
Chris Lattner8532cf62005-10-17 20:18:38 +00001967 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00001968 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
1969 (I.getType())->getValueAPF()))
Chris Lattner8532cf62005-10-17 20:18:38 +00001970 return ReplaceInstUsesWith(I, LHS);
Chris Lattner5e678e02005-10-17 17:56:38 +00001971 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001972
Chris Lattner66331a42004-04-10 22:01:55 +00001973 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerb4a2f052006-11-09 05:12:27 +00001974 // X + (signbit) --> X ^ signbit
Zhou Sheng3a507fd2007-04-01 17:13:37 +00001975 const APInt& Val = CI->getValue();
Zhou Sheng4351c642007-04-02 08:20:41 +00001976 uint32_t BitWidth = Val.getBitWidth();
Reid Spencer2ec619a2007-03-23 21:24:59 +00001977 if (Val == APInt::getSignBit(BitWidth))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001978 return BinaryOperator::CreateXor(LHS, RHS);
Chris Lattnerb4a2f052006-11-09 05:12:27 +00001979
1980 // See if SimplifyDemandedBits can simplify this. This handles stuff like
1981 // (X & 254)+1 -> (X&254)|1
Chris Lattner886ab6c2009-01-31 08:15:18 +00001982 if (!isa<VectorType>(I.getType()) && SimplifyDemandedInstructionBits(I))
1983 return &I;
Dan Gohman1975d032008-10-30 20:40:10 +00001984
1985 // zext(i1) - 1 -> select i1, 0, -1
1986 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
1987 if (CI->isAllOnesValue() &&
1988 ZI->getOperand(0)->getType() == Type::Int1Ty)
1989 return SelectInst::Create(ZI->getOperand(0),
1990 Constant::getNullValue(I.getType()),
1991 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattner66331a42004-04-10 22:01:55 +00001992 }
Chris Lattner4e998b22004-09-29 05:07:12 +00001993
1994 if (isa<PHINode>(LHS))
1995 if (Instruction *NV = FoldOpIntoPhi(I))
1996 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +00001997
Chris Lattner4f637d42006-01-06 17:59:59 +00001998 ConstantInt *XorRHS = 0;
1999 Value *XorLHS = 0;
Chris Lattnerc5eff442007-01-30 22:32:46 +00002000 if (isa<ConstantInt>(RHSC) &&
2001 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002002 uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002003 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner5931c542005-09-24 23:43:33 +00002004
Zhou Sheng4351c642007-04-02 08:20:41 +00002005 uint32_t Size = TySizeBits / 2;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002006 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2007 APInt CFF80Val(-C0080Val);
Chris Lattner5931c542005-09-24 23:43:33 +00002008 do {
2009 if (TySizeBits > Size) {
Chris Lattner5931c542005-09-24 23:43:33 +00002010 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2011 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002012 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2013 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner5931c542005-09-24 23:43:33 +00002014 // This is a sign extend if the top bits are known zero.
Zhou Sheng290bec52007-03-29 08:15:12 +00002015 if (!MaskedValueIsZero(XorLHS,
2016 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner5931c542005-09-24 23:43:33 +00002017 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002018 break;
Chris Lattner5931c542005-09-24 23:43:33 +00002019 }
2020 }
2021 Size >>= 1;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002022 C0080Val = APIntOps::lshr(C0080Val, Size);
2023 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2024 } while (Size >= 1);
Chris Lattner5931c542005-09-24 23:43:33 +00002025
Reid Spencer35c38852007-03-28 01:36:16 +00002026 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattner0c7a9a02008-05-19 20:25:04 +00002027 // with funny bit widths then this switch statement should be removed. It
2028 // is just here to get the size of the "middle" type back up to something
2029 // that the back ends can handle.
Reid Spencer35c38852007-03-28 01:36:16 +00002030 const Type *MiddleType = 0;
2031 switch (Size) {
2032 default: break;
2033 case 32: MiddleType = Type::Int32Ty; break;
2034 case 16: MiddleType = Type::Int16Ty; break;
2035 case 8: MiddleType = Type::Int8Ty; break;
2036 }
2037 if (MiddleType) {
Reid Spencerd977d862006-12-12 23:36:14 +00002038 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
Chris Lattner5931c542005-09-24 23:43:33 +00002039 InsertNewInstBefore(NewTrunc, I);
Reid Spencer35c38852007-03-28 01:36:16 +00002040 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner5931c542005-09-24 23:43:33 +00002041 }
2042 }
Chris Lattner66331a42004-04-10 22:01:55 +00002043 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002044
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002045 if (I.getType() == Type::Int1Ty)
2046 return BinaryOperator::CreateXor(LHS, RHS);
2047
Nick Lewycky7d26bd82008-05-23 04:39:38 +00002048 // X + X --> X << 1
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002049 if (I.getType()->isInteger()) {
Chris Lattner564a7272003-08-13 19:01:45 +00002050 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +00002051
2052 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2053 if (RHSI->getOpcode() == Instruction::Sub)
2054 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2055 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2056 }
2057 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2058 if (LHSI->getOpcode() == Instruction::Sub)
2059 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2060 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2061 }
Robert Bocchino71698282004-07-27 21:02:21 +00002062 }
Chris Lattnere92d2f42003-08-13 04:18:28 +00002063
Chris Lattner5c4afb92002-05-08 22:46:53 +00002064 // -A + B --> B - A
Chris Lattnerdd12f962008-02-17 21:03:36 +00002065 // -A + -B --> -(A + B)
2066 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattnere10c0b92008-02-18 17:50:16 +00002067 if (LHS->getType()->isIntOrIntVector()) {
2068 if (Value *RHSV = dyn_castNegVal(RHS)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002069 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
Chris Lattnere10c0b92008-02-18 17:50:16 +00002070 InsertNewInstBefore(NewAdd, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002071 return BinaryOperator::CreateNeg(NewAdd);
Chris Lattnere10c0b92008-02-18 17:50:16 +00002072 }
Chris Lattnerdd12f962008-02-17 21:03:36 +00002073 }
2074
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002075 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattnerdd12f962008-02-17 21:03:36 +00002076 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002077
2078 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +00002079 if (!isa<Constant>(RHS))
2080 if (Value *V = dyn_castNegVal(RHS))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002081 return BinaryOperator::CreateSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002082
Misha Brukmanfd939082005-04-21 23:48:37 +00002083
Chris Lattner50af16a2004-11-13 19:50:12 +00002084 ConstantInt *C2;
2085 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2086 if (X == RHS) // X*C + X --> X * (C+1)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002087 return BinaryOperator::CreateMul(RHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002088
2089 // X*C1 + X*C2 --> X * (C1+C2)
2090 ConstantInt *C1;
2091 if (X == dyn_castFoldableMul(RHS, C1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002092 return BinaryOperator::CreateMul(X, Add(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002093 }
2094
2095 // X + X*C --> X * (C+1)
Chris Lattner50af16a2004-11-13 19:50:12 +00002096 if (dyn_castFoldableMul(RHS, C2) == LHS)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002097 return BinaryOperator::CreateMul(LHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002098
Chris Lattnere617c9e2007-01-05 02:17:46 +00002099 // X + ~X --> -1 since ~X = -X-1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00002100 if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2101 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere617c9e2007-01-05 02:17:46 +00002102
Chris Lattnerad3448c2003-02-18 19:57:07 +00002103
Chris Lattner564a7272003-08-13 19:01:45 +00002104 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002105 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnere617c9e2007-01-05 02:17:46 +00002106 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2107 return R;
Chris Lattner5e0d7182008-05-19 20:01:56 +00002108
2109 // A+B --> A|B iff A and B have no bits set in common.
2110 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2111 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2112 APInt LHSKnownOne(IT->getBitWidth(), 0);
2113 APInt LHSKnownZero(IT->getBitWidth(), 0);
2114 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2115 if (LHSKnownZero != 0) {
2116 APInt RHSKnownOne(IT->getBitWidth(), 0);
2117 APInt RHSKnownZero(IT->getBitWidth(), 0);
2118 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2119
2120 // No bits in common -> bitwise or.
Chris Lattner9d60ba92008-05-19 20:03:53 +00002121 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattner5e0d7182008-05-19 20:01:56 +00002122 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattner5e0d7182008-05-19 20:01:56 +00002123 }
2124 }
Chris Lattnerc8802d22003-03-11 00:12:48 +00002125
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002126 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky0c2c3f62008-02-03 08:19:11 +00002127 if (I.getType()->isIntOrIntVector()) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002128 Value *W, *X, *Y, *Z;
2129 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2130 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2131 if (W != Y) {
2132 if (W == Z) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002133 std::swap(Y, Z);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002134 } else if (Y == X) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002135 std::swap(W, X);
2136 } else if (X == Z) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002137 std::swap(Y, Z);
2138 std::swap(W, X);
2139 }
2140 }
2141
2142 if (W == Y) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002143 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002144 LHS->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002145 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002146 }
2147 }
2148 }
2149
Chris Lattner6b032052003-10-02 15:11:26 +00002150 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002151 Value *X = 0;
Reid Spencer7177c3a2007-03-25 05:33:51 +00002152 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002153 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002154
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002155 // (X & FF00) + xx00 -> (X+xx00) & FF00
2156 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002157 Constant *Anded = And(CRHS, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002158 if (Anded == CRHS) {
2159 // See if all bits from the first bit set in the Add RHS up are included
2160 // in the mask. First, get the rightmost bit.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002161 const APInt& AddRHSV = CRHS->getValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002162
2163 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002164 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002165
2166 // See if the and mask includes all of these bits.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002167 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanfd939082005-04-21 23:48:37 +00002168
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002169 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2170 // Okay, the xform is safe. Insert the new add pronto.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002171 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002172 LHS->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002173 return BinaryOperator::CreateAnd(NewAdd, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002174 }
2175 }
2176 }
2177
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002178 // Try to fold constant add into select arguments.
2179 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002180 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002181 return R;
Chris Lattner6b032052003-10-02 15:11:26 +00002182 }
2183
Reid Spencer1628cec2006-10-26 06:15:43 +00002184 // add (cast *A to intptrtype) B ->
Chris Lattner42790482007-12-20 01:56:58 +00002185 // cast (GEP (cast *A to sbyte*) B) --> intptrtype
Andrew Lenharth16d79552006-09-19 18:24:51 +00002186 {
Reid Spencer3da59db2006-11-27 01:05:10 +00002187 CastInst *CI = dyn_cast<CastInst>(LHS);
2188 Value *Other = RHS;
Andrew Lenharth16d79552006-09-19 18:24:51 +00002189 if (!CI) {
2190 CI = dyn_cast<CastInst>(RHS);
2191 Other = LHS;
2192 }
Andrew Lenharth45633262006-09-20 15:37:57 +00002193 if (CI && CI->getType()->isSized() &&
Reid Spencerabaa8ca2007-01-08 16:32:00 +00002194 (CI->getType()->getPrimitiveSizeInBits() ==
2195 TD->getIntPtrType()->getPrimitiveSizeInBits())
Andrew Lenharth45633262006-09-20 15:37:57 +00002196 && isa<PointerType>(CI->getOperand(0)->getType())) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00002197 unsigned AS =
2198 cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +00002199 Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2200 PointerType::get(Type::Int8Ty, AS), I);
Gabor Greif051a9502008-04-06 20:25:17 +00002201 I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
Reid Spencer3da59db2006-11-27 01:05:10 +00002202 return new PtrToIntInst(I2, CI->getType());
Andrew Lenharth16d79552006-09-19 18:24:51 +00002203 }
2204 }
Christopher Lamb30f017a2007-12-18 09:34:41 +00002205
Chris Lattner42790482007-12-20 01:56:58 +00002206 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb30f017a2007-12-18 09:34:41 +00002207 {
2208 SelectInst *SI = dyn_cast<SelectInst>(LHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002209 Value *A = RHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002210 if (!SI) {
2211 SI = dyn_cast<SelectInst>(RHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002212 A = LHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002213 }
Chris Lattner42790482007-12-20 01:56:58 +00002214 if (SI && SI->hasOneUse()) {
Christopher Lamb30f017a2007-12-18 09:34:41 +00002215 Value *TV = SI->getTrueValue();
2216 Value *FV = SI->getFalseValue();
Chris Lattner6046fb72008-11-16 04:46:19 +00002217 Value *N;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002218
2219 // Can we fold the add into the argument of the select?
2220 // We check both true and false select arguments for a matching subtract.
Chris Lattner6046fb72008-11-16 04:46:19 +00002221 if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Specific(A))))
2222 // Fold the add into the true select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002223 return SelectInst::Create(SI->getCondition(), N, A);
Chris Lattner6046fb72008-11-16 04:46:19 +00002224 if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Specific(A))))
2225 // Fold the add into the false select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002226 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb30f017a2007-12-18 09:34:41 +00002227 }
2228 }
Chris Lattner2454a2e2008-01-29 06:52:45 +00002229
2230 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2231 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2232 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2233 return ReplaceInstUsesWith(I, LHS);
Andrew Lenharth16d79552006-09-19 18:24:51 +00002234
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002235 // Check for (add (sext x), y), see if we can merge this into an
2236 // integer add followed by a sext.
2237 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2238 // (add (sext x), cst) --> (sext (add x, cst'))
2239 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2240 Constant *CI =
2241 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
2242 if (LHSConv->hasOneUse() &&
2243 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
2244 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2245 // Insert the new, smaller add.
2246 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2247 CI, "addconv");
2248 InsertNewInstBefore(NewAdd, I);
2249 return new SExtInst(NewAdd, I.getType());
2250 }
2251 }
2252
2253 // (add (sext x), (sext y)) --> (sext (add int x, y))
2254 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2255 // Only do this if x/y have the same type, if at last one of them has a
2256 // single use (so we don't increase the number of sexts), and if the
2257 // integer add will not overflow.
2258 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2259 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2260 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2261 RHSConv->getOperand(0))) {
2262 // Insert the new integer add.
2263 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2264 RHSConv->getOperand(0),
2265 "addconv");
2266 InsertNewInstBefore(NewAdd, I);
2267 return new SExtInst(NewAdd, I.getType());
2268 }
2269 }
2270 }
2271
2272 // Check for (add double (sitofp x), y), see if we can merge this into an
2273 // integer add followed by a promotion.
2274 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2275 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2276 // ... if the constant fits in the integer value. This is useful for things
2277 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2278 // requires a constant pool load, and generally allows the add to be better
2279 // instcombined.
2280 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2281 Constant *CI =
2282 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
2283 if (LHSConv->hasOneUse() &&
2284 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
2285 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2286 // Insert the new integer add.
2287 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2288 CI, "addconv");
2289 InsertNewInstBefore(NewAdd, I);
2290 return new SIToFPInst(NewAdd, I.getType());
2291 }
2292 }
2293
2294 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2295 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2296 // Only do this if x/y have the same type, if at last one of them has a
2297 // single use (so we don't increase the number of int->fp conversions),
2298 // and if the integer add will not overflow.
2299 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2300 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2301 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2302 RHSConv->getOperand(0))) {
2303 // Insert the new integer add.
2304 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2305 RHSConv->getOperand(0),
2306 "addconv");
2307 InsertNewInstBefore(NewAdd, I);
2308 return new SIToFPInst(NewAdd, I.getType());
2309 }
2310 }
2311 }
2312
Chris Lattner7e708292002-06-25 16:13:24 +00002313 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002314}
2315
Chris Lattner7e708292002-06-25 16:13:24 +00002316Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00002317 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002318
Chris Lattnerd137ab42008-07-17 06:07:20 +00002319 if (Op0 == Op1 && // sub X, X -> 0
2320 !I.getType()->isFPOrFPVector())
Chris Lattner233f7dc2002-08-12 21:17:25 +00002321 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002322
Chris Lattner233f7dc2002-08-12 21:17:25 +00002323 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattner8d969642003-03-10 23:06:50 +00002324 if (Value *V = dyn_castNegVal(Op1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002325 return BinaryOperator::CreateAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002326
Chris Lattnere87597f2004-10-16 18:11:37 +00002327 if (isa<UndefValue>(Op0))
2328 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2329 if (isa<UndefValue>(Op1))
2330 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2331
Chris Lattnerd65460f2003-11-05 01:06:05 +00002332 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2333 // Replace (-1 - A) with (~A)...
Chris Lattnera2881962003-02-18 19:28:33 +00002334 if (C->isAllOnesValue())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002335 return BinaryOperator::CreateNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +00002336
Chris Lattnerd65460f2003-11-05 01:06:05 +00002337 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002338 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002339 if (match(Op1, m_Not(m_Value(X))))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002340 return BinaryOperator::CreateAdd(X, AddOne(C));
Reid Spencer7177c3a2007-03-25 05:33:51 +00002341
Chris Lattner76b7a062007-01-15 07:02:54 +00002342 // -(X >>u 31) -> (X >>s 31)
2343 // -(X >>s 31) -> (X >>u 31)
Zhou Sheng302748d2007-03-30 17:20:39 +00002344 if (C->isZero()) {
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002345 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002346 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002347 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00002348 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002349 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerb83eb642006-10-20 07:07:24 +00002350 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002351 // Ok, the transformation is safe. Insert AShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002352 return BinaryOperator::Create(Instruction::AShr,
Reid Spencer832254e2007-02-02 02:16:23 +00002353 SI->getOperand(0), CU, SI->getName());
Chris Lattner9c290672004-03-12 23:53:13 +00002354 }
2355 }
Reid Spencer3822ff52006-11-08 06:47:33 +00002356 }
2357 else if (SI->getOpcode() == Instruction::AShr) {
2358 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2359 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002360 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencer3822ff52006-11-08 06:47:33 +00002361 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00002362 // Ok, the transformation is safe. Insert LShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002363 return BinaryOperator::CreateLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00002364 SI->getOperand(0), CU, SI->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00002365 }
2366 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002367 }
2368 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00002369 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002370
2371 // Try to fold constant sub into select arguments.
2372 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002373 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002374 return R;
Chris Lattnerd65460f2003-11-05 01:06:05 +00002375 }
2376
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002377 if (I.getType() == Type::Int1Ty)
2378 return BinaryOperator::CreateXor(Op0, Op1);
2379
Chris Lattner43d84d62005-04-07 16:15:25 +00002380 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2381 if (Op1I->getOpcode() == Instruction::Add &&
Chris Lattner9919e3d2006-12-02 00:13:08 +00002382 !Op0->getType()->isFPOrFPVector()) {
Chris Lattner08954a22005-04-07 16:28:01 +00002383 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002384 return BinaryOperator::CreateNeg(Op1I->getOperand(1), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002385 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002386 return BinaryOperator::CreateNeg(Op1I->getOperand(0), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002387 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2388 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2389 // C1-(X+C2) --> (C1-C2)-X
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002390 return BinaryOperator::CreateSub(Subtract(CI1, CI2),
Chris Lattner08954a22005-04-07 16:28:01 +00002391 Op1I->getOperand(0));
2392 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002393 }
2394
Chris Lattnerfd059242003-10-15 16:48:29 +00002395 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002396 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2397 // is not used by anyone else...
2398 //
Chris Lattner0517e722004-02-02 20:09:56 +00002399 if (Op1I->getOpcode() == Instruction::Sub &&
Chris Lattner9919e3d2006-12-02 00:13:08 +00002400 !Op1I->getType()->isFPOrFPVector()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002401 // Swap the two operands of the subexpr...
2402 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2403 Op1I->setOperand(0, IIOp1);
2404 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00002405
Chris Lattnera2881962003-02-18 19:28:33 +00002406 // Create the new top level add instruction...
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002407 return BinaryOperator::CreateAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00002408 }
2409
2410 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2411 //
2412 if (Op1I->getOpcode() == Instruction::And &&
2413 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2414 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2415
Chris Lattnerf523d062004-06-09 05:08:07 +00002416 Value *NewNot =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002417 InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
2418 return BinaryOperator::CreateAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00002419 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00002420
Reid Spencerac5209e2006-10-16 23:08:08 +00002421 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer1628cec2006-10-26 06:15:43 +00002422 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencerb83eb642006-10-20 07:07:24 +00002423 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Zhou Sheng843f07672007-04-19 05:39:12 +00002424 if (CSI->isZero())
Chris Lattner91ccc152004-10-06 15:08:25 +00002425 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002426 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Chris Lattner91ccc152004-10-06 15:08:25 +00002427 ConstantExpr::getNeg(DivRHS));
2428
Chris Lattnerad3448c2003-02-18 19:57:07 +00002429 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002430 ConstantInt *C2 = 0;
Chris Lattner50af16a2004-11-13 19:50:12 +00002431 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002432 Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002433 return BinaryOperator::CreateMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00002434 }
Chris Lattner40371712002-05-09 01:29:19 +00002435 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002436 }
Chris Lattnera2881962003-02-18 19:28:33 +00002437
Chris Lattner9919e3d2006-12-02 00:13:08 +00002438 if (!Op0->getType()->isFPOrFPVector())
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002439 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner7edc8c22005-04-07 17:14:51 +00002440 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00002441 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2442 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2443 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2444 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner7edc8c22005-04-07 17:14:51 +00002445 } else if (Op0I->getOpcode() == Instruction::Sub) {
2446 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002447 return BinaryOperator::CreateNeg(Op0I->getOperand(1), I.getName());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00002448 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002449 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002450
Chris Lattner50af16a2004-11-13 19:50:12 +00002451 ConstantInt *C1;
2452 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002453 if (X == Op1) // X*C - X --> X * (C-1)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002454 return BinaryOperator::CreateMul(Op1, SubOne(C1));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002455
Chris Lattner50af16a2004-11-13 19:50:12 +00002456 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2457 if (X == dyn_castFoldableMul(Op1, C2))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002458 return BinaryOperator::CreateMul(X, Subtract(C1, C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002459 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002460 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002461}
2462
Chris Lattnera0141b92007-07-15 20:42:37 +00002463/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2464/// comparison only checks the sign bit. If it only checks the sign bit, set
2465/// TrueIfSigned if the result of the comparison is true when the input value is
2466/// signed.
2467static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2468 bool &TrueIfSigned) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002469 switch (pred) {
Chris Lattnera0141b92007-07-15 20:42:37 +00002470 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2471 TrueIfSigned = true;
2472 return RHS->isZero();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002473 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2474 TrueIfSigned = true;
2475 return RHS->isAllOnesValue();
Chris Lattnera0141b92007-07-15 20:42:37 +00002476 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2477 TrueIfSigned = false;
2478 return RHS->isAllOnesValue();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002479 case ICmpInst::ICMP_UGT:
2480 // True if LHS u> RHS and RHS == high-bit-mask - 1
2481 TrueIfSigned = true;
2482 return RHS->getValue() ==
2483 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2484 case ICmpInst::ICMP_UGE:
2485 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2486 TrueIfSigned = true;
Chris Lattner833f25d2008-06-02 01:29:46 +00002487 return RHS->getValue().isSignBit();
Chris Lattnera0141b92007-07-15 20:42:37 +00002488 default:
2489 return false;
Chris Lattner4cb170c2004-02-23 06:38:22 +00002490 }
Chris Lattner4cb170c2004-02-23 06:38:22 +00002491}
2492
Chris Lattner7e708292002-06-25 16:13:24 +00002493Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002494 bool Changed = SimplifyCommutative(I);
Chris Lattnera2881962003-02-18 19:28:33 +00002495 Value *Op0 = I.getOperand(0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002496
Chris Lattnere87597f2004-10-16 18:11:37 +00002497 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2498 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2499
Chris Lattner233f7dc2002-08-12 21:17:25 +00002500 // Simplify mul instructions with a constant RHS...
Chris Lattnera2881962003-02-18 19:28:33 +00002501 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2502 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00002503
2504 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer832254e2007-02-02 02:16:23 +00002505 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnere92d2f42003-08-13 04:18:28 +00002506 if (SI->getOpcode() == Instruction::Shl)
2507 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002508 return BinaryOperator::CreateMul(SI->getOperand(0),
Chris Lattner48595f12004-06-10 02:07:29 +00002509 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00002510
Zhou Sheng843f07672007-04-19 05:39:12 +00002511 if (CI->isZero())
Chris Lattner515c97c2003-09-11 22:24:54 +00002512 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2513 if (CI->equalsInt(1)) // X * 1 == X
2514 return ReplaceInstUsesWith(I, Op0);
2515 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002516 return BinaryOperator::CreateNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00002517
Zhou Sheng97b52c22007-03-29 01:57:21 +00002518 const APInt& Val = cast<ConstantInt>(CI)->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002519 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002520 return BinaryOperator::CreateShl(Op0,
Reid Spencerbca0e382007-03-23 20:05:17 +00002521 ConstantInt::get(Op0->getType(), Val.logBase2()));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00002522 }
Robert Bocchino71698282004-07-27 21:02:21 +00002523 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattnera2881962003-02-18 19:28:33 +00002524 if (Op1F->isNullValue())
2525 return ReplaceInstUsesWith(I, Op1);
Chris Lattner6c1ce212002-04-29 22:24:47 +00002526
Chris Lattnera2881962003-02-18 19:28:33 +00002527 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2528 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
Chris Lattnerb8cd4d32008-08-11 22:06:05 +00002529 if (Op1F->isExactlyValue(1.0))
2530 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2531 } else if (isa<VectorType>(Op1->getType())) {
2532 if (isa<ConstantAggregateZero>(Op1))
2533 return ReplaceInstUsesWith(I, Op1);
Nick Lewycky895f0852008-11-27 20:21:08 +00002534
2535 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2536 if (Op1V->isAllOnesValue()) // X * -1 == 0 - X
2537 return BinaryOperator::CreateNeg(Op0, I.getName());
2538
2539 // As above, vector X*splat(1.0) -> X in all defined cases.
2540 if (Constant *Splat = Op1V->getSplatValue()) {
2541 if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2542 if (F->isExactlyValue(1.0))
2543 return ReplaceInstUsesWith(I, Op0);
2544 if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2545 if (CI->equalsInt(1))
2546 return ReplaceInstUsesWith(I, Op0);
2547 }
2548 }
Chris Lattnera2881962003-02-18 19:28:33 +00002549 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002550
2551 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2552 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattner47c99092008-05-18 04:11:26 +00002553 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002554 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002555 Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002556 Op1, "tmp");
2557 InsertNewInstBefore(Add, I);
2558 Value *C1C2 = ConstantExpr::getMul(Op1,
2559 cast<Constant>(Op0I->getOperand(1)));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002560 return BinaryOperator::CreateAdd(Add, C1C2);
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002561
2562 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002563
2564 // Try to fold constant mul into select arguments.
2565 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002566 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002567 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002568
2569 if (isa<PHINode>(Op0))
2570 if (Instruction *NV = FoldOpIntoPhi(I))
2571 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002572 }
2573
Chris Lattnera4f445b2003-03-10 23:23:04 +00002574 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2575 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002576 return BinaryOperator::CreateMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00002577
Nick Lewycky0c730792008-11-21 07:33:58 +00002578 // (X / Y) * Y = X - (X % Y)
2579 // (X / Y) * -Y = (X % Y) - X
2580 {
2581 Value *Op1 = I.getOperand(1);
2582 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2583 if (!BO ||
2584 (BO->getOpcode() != Instruction::UDiv &&
2585 BO->getOpcode() != Instruction::SDiv)) {
2586 Op1 = Op0;
2587 BO = dyn_cast<BinaryOperator>(I.getOperand(1));
2588 }
2589 Value *Neg = dyn_castNegVal(Op1);
2590 if (BO && BO->hasOneUse() &&
2591 (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) &&
2592 (BO->getOpcode() == Instruction::UDiv ||
2593 BO->getOpcode() == Instruction::SDiv)) {
2594 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2595
2596 Instruction *Rem;
2597 if (BO->getOpcode() == Instruction::UDiv)
2598 Rem = BinaryOperator::CreateURem(Op0BO, Op1BO);
2599 else
2600 Rem = BinaryOperator::CreateSRem(Op0BO, Op1BO);
2601
2602 InsertNewInstBefore(Rem, I);
2603 Rem->takeName(BO);
2604
2605 if (Op1BO == Op1)
2606 return BinaryOperator::CreateSub(Op0BO, Rem);
2607 else
2608 return BinaryOperator::CreateSub(Rem, Op0BO);
2609 }
2610 }
2611
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002612 if (I.getType() == Type::Int1Ty)
2613 return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2614
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002615 // If one of the operands of the multiply is a cast from a boolean value, then
2616 // we know the bool is either zero or one, so this is a 'masking' multiply.
2617 // See if we can simplify things based on how the boolean was originally
2618 // formed.
2619 CastInst *BoolCast = 0;
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002620 if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002621 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002622 BoolCast = CI;
2623 if (!BoolCast)
Reid Spencerc55b2432006-12-13 18:21:21 +00002624 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002625 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002626 BoolCast = CI;
2627 if (BoolCast) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002628 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002629 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2630 const Type *SCOpTy = SCIOp0->getType();
Chris Lattnera0141b92007-07-15 20:42:37 +00002631 bool TIS = false;
2632
Reid Spencere4d87aa2006-12-23 06:05:41 +00002633 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattner4cb170c2004-02-23 06:38:22 +00002634 // multiply into a shift/and combination.
2635 if (isa<ConstantInt>(SCIOp1) &&
Chris Lattnera0141b92007-07-15 20:42:37 +00002636 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2637 TIS) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002638 // Shift the X value right to turn it into "all signbits".
Reid Spencer832254e2007-02-02 02:16:23 +00002639 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
Chris Lattner484d3cf2005-04-24 06:59:08 +00002640 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattner4cb170c2004-02-23 06:38:22 +00002641 Value *V =
Reid Spencer832254e2007-02-02 02:16:23 +00002642 InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002643 BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
Chris Lattner4cb170c2004-02-23 06:38:22 +00002644 BoolCast->getOperand(0)->getName()+
2645 ".mask"), I);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002646
2647 // If the multiply type is not the same as the source type, sign extend
2648 // or truncate to the multiply type.
Reid Spencer17212df2006-12-12 09:18:51 +00002649 if (I.getType() != V->getType()) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002650 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2651 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +00002652 Instruction::CastOps opcode =
2653 (SrcBits == DstBits ? Instruction::BitCast :
2654 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2655 V = InsertCastBefore(opcode, V, I.getType(), I);
2656 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002657
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002658 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002659 return BinaryOperator::CreateAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002660 }
2661 }
2662 }
2663
Chris Lattner7e708292002-06-25 16:13:24 +00002664 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002665}
2666
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002667/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2668/// instruction.
2669bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2670 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2671
2672 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2673 int NonNullOperand = -1;
2674 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2675 if (ST->isNullValue())
2676 NonNullOperand = 2;
2677 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2678 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2679 if (ST->isNullValue())
2680 NonNullOperand = 1;
2681
2682 if (NonNullOperand == -1)
2683 return false;
2684
2685 Value *SelectCond = SI->getOperand(0);
2686
2687 // Change the div/rem to use 'Y' instead of the select.
2688 I.setOperand(1, SI->getOperand(NonNullOperand));
2689
2690 // Okay, we know we replace the operand of the div/rem with 'Y' with no
2691 // problem. However, the select, or the condition of the select may have
2692 // multiple uses. Based on our knowledge that the operand must be non-zero,
2693 // propagate the known value for the select into other uses of it, and
2694 // propagate a known value of the condition into its other users.
2695
2696 // If the select and condition only have a single use, don't bother with this,
2697 // early exit.
2698 if (SI->use_empty() && SelectCond->hasOneUse())
2699 return true;
2700
2701 // Scan the current block backward, looking for other uses of SI.
2702 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2703
2704 while (BBI != BBFront) {
2705 --BBI;
2706 // If we found a call to a function, we can't assume it will return, so
2707 // information from below it cannot be propagated above it.
2708 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2709 break;
2710
2711 // Replace uses of the select or its condition with the known values.
2712 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2713 I != E; ++I) {
2714 if (*I == SI) {
2715 *I = SI->getOperand(NonNullOperand);
2716 AddToWorkList(BBI);
2717 } else if (*I == SelectCond) {
2718 *I = NonNullOperand == 1 ? ConstantInt::getTrue() :
2719 ConstantInt::getFalse();
2720 AddToWorkList(BBI);
2721 }
2722 }
2723
2724 // If we past the instruction, quit looking for it.
2725 if (&*BBI == SI)
2726 SI = 0;
2727 if (&*BBI == SelectCond)
2728 SelectCond = 0;
2729
2730 // If we ran out of things to eliminate, break out of the loop.
2731 if (SelectCond == 0 && SI == 0)
2732 break;
2733
2734 }
2735 return true;
2736}
2737
2738
Reid Spencer1628cec2006-10-26 06:15:43 +00002739/// This function implements the transforms on div instructions that work
2740/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2741/// used by the visitors to those instructions.
2742/// @brief Transforms common to all three div instructions
Reid Spencer3da59db2006-11-27 01:05:10 +00002743Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002744 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00002745
Chris Lattner50b2ca42008-02-19 06:12:18 +00002746 // undef / X -> 0 for integer.
2747 // undef / X -> undef for FP (the undef could be a snan).
2748 if (isa<UndefValue>(Op0)) {
2749 if (Op0->getType()->isFPOrFPVector())
2750 return ReplaceInstUsesWith(I, Op0);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002751 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00002752 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002753
2754 // X / undef -> undef
Chris Lattner857e8cd2004-12-12 21:48:58 +00002755 if (isa<UndefValue>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00002756 return ReplaceInstUsesWith(I, Op1);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002757
Reid Spencer1628cec2006-10-26 06:15:43 +00002758 return 0;
2759}
Misha Brukmanfd939082005-04-21 23:48:37 +00002760
Reid Spencer1628cec2006-10-26 06:15:43 +00002761/// This function implements the transforms common to both integer division
2762/// instructions (udiv and sdiv). It is called by the visitors to those integer
2763/// division instructions.
2764/// @brief Common integer divide transforms
Reid Spencer3da59db2006-11-27 01:05:10 +00002765Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002766 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2767
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00002768 // (sdiv X, X) --> 1 (udiv X, X) --> 1
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002769 if (Op0 == Op1) {
2770 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
2771 ConstantInt *CI = ConstantInt::get(Ty->getElementType(), 1);
2772 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
2773 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
2774 }
2775
2776 ConstantInt *CI = ConstantInt::get(I.getType(), 1);
2777 return ReplaceInstUsesWith(I, CI);
2778 }
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00002779
Reid Spencer1628cec2006-10-26 06:15:43 +00002780 if (Instruction *Common = commonDivTransforms(I))
2781 return Common;
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002782
2783 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2784 // This does not apply for fdiv.
2785 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2786 return &I;
Reid Spencer1628cec2006-10-26 06:15:43 +00002787
2788 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2789 // div X, 1 == X
2790 if (RHS->equalsInt(1))
2791 return ReplaceInstUsesWith(I, Op0);
2792
2793 // (X / C1) / C2 -> X / (C1*C2)
2794 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2795 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2796 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00002797 if (MultiplyOverflows(RHS, LHSRHS, I.getOpcode()==Instruction::SDiv))
2798 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2799 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002800 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00002801 Multiply(RHS, LHSRHS));
Chris Lattnerbf70b832005-04-08 04:03:26 +00002802 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002803
Reid Spencerbca0e382007-03-23 20:05:17 +00002804 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer1628cec2006-10-26 06:15:43 +00002805 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2806 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2807 return R;
2808 if (isa<PHINode>(Op0))
2809 if (Instruction *NV = FoldOpIntoPhi(I))
2810 return NV;
2811 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002812 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002813
Chris Lattnera2881962003-02-18 19:28:33 +00002814 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00002815 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00002816 if (LHS->equalsInt(0))
2817 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2818
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002819 // It can't be division by zero, hence it must be division by one.
2820 if (I.getType() == Type::Int1Ty)
2821 return ReplaceInstUsesWith(I, Op0);
2822
Nick Lewycky895f0852008-11-27 20:21:08 +00002823 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2824 if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
2825 // div X, 1 == X
2826 if (X->isOne())
2827 return ReplaceInstUsesWith(I, Op0);
2828 }
2829
Reid Spencer1628cec2006-10-26 06:15:43 +00002830 return 0;
2831}
2832
2833Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2834 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2835
2836 // Handle the integer div common cases
2837 if (Instruction *Common = commonIDivTransforms(I))
2838 return Common;
2839
Reid Spencer1628cec2006-10-26 06:15:43 +00002840 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky8ca52482008-11-27 22:41:10 +00002841 // X udiv C^2 -> X >> C
2842 // Check to see if this is an unsigned division with an exact power of 2,
2843 // if so, convert to a right shift.
Reid Spencer6eb0d992007-03-26 23:58:26 +00002844 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002845 return BinaryOperator::CreateLShr(Op0,
Zhou Sheng0fc50952007-03-25 05:01:29 +00002846 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Nick Lewycky8ca52482008-11-27 22:41:10 +00002847
2848 // X udiv C, where C >= signbit
2849 if (C->getValue().isNegative()) {
2850 Value *IC = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_ULT, Op0, C),
2851 I);
2852 return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
2853 ConstantInt::get(I.getType(), 1));
2854 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002855 }
2856
2857 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer832254e2007-02-02 02:16:23 +00002858 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002859 if (RHSI->getOpcode() == Instruction::Shl &&
2860 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002861 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002862 if (C1.isPowerOf2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002863 Value *N = RHSI->getOperand(1);
Reid Spencer3da59db2006-11-27 01:05:10 +00002864 const Type *NTy = N->getType();
Reid Spencer2ec619a2007-03-23 21:24:59 +00002865 if (uint32_t C2 = C1.logBase2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002866 Constant *C2V = ConstantInt::get(NTy, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002867 N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002868 }
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002869 return BinaryOperator::CreateLShr(Op0, N);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002870 }
2871 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00002872 }
2873
Reid Spencer1628cec2006-10-26 06:15:43 +00002874 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2875 // where C1&C2 are powers of two.
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002876 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00002877 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002878 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002879 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002880 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002881 // Compute the shift amounts
Reid Spencerbca0e382007-03-23 20:05:17 +00002882 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002883 // Construct the "on true" case of the select
2884 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002885 Instruction *TSI = BinaryOperator::CreateLShr(
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002886 Op0, TC, SI->getName()+".t");
2887 TSI = InsertNewInstBefore(TSI, I);
2888
2889 // Construct the "on false" case of the select
2890 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002891 Instruction *FSI = BinaryOperator::CreateLShr(
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002892 Op0, FC, SI->getName()+".f");
2893 FSI = InsertNewInstBefore(FSI, I);
Reid Spencer1628cec2006-10-26 06:15:43 +00002894
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002895 // construct the select instruction and return it.
Gabor Greif051a9502008-04-06 20:25:17 +00002896 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00002897 }
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002898 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002899 return 0;
2900}
2901
Reid Spencer1628cec2006-10-26 06:15:43 +00002902Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2903 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2904
2905 // Handle the integer div common cases
2906 if (Instruction *Common = commonIDivTransforms(I))
2907 return Common;
2908
2909 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2910 // sdiv X, -1 == -X
2911 if (RHS->isAllOnesValue())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002912 return BinaryOperator::CreateNeg(Op0);
Reid Spencer1628cec2006-10-26 06:15:43 +00002913 }
2914
2915 // If the sign bits of both operands are zero (i.e. we can prove they are
2916 // unsigned inputs), turn this into a udiv.
Chris Lattner42a75512007-01-15 02:27:26 +00002917 if (I.getType()->isInteger()) {
Reid Spencerbca0e382007-03-23 20:05:17 +00002918 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Reid Spencer1628cec2006-10-26 06:15:43 +00002919 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Dan Gohmancff55092007-11-05 23:16:33 +00002920 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002921 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00002922 }
2923 }
2924
2925 return 0;
2926}
2927
2928Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2929 return commonDivTransforms(I);
2930}
Chris Lattner3f5b8772002-05-06 16:14:14 +00002931
Reid Spencer0a783f72006-11-02 01:53:59 +00002932/// This function implements the transforms on rem instructions that work
2933/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
2934/// is used by the visitors to those instructions.
2935/// @brief Transforms common to all three rem instructions
2936Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002937 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer0a783f72006-11-02 01:53:59 +00002938
Chris Lattner50b2ca42008-02-19 06:12:18 +00002939 if (isa<UndefValue>(Op0)) { // undef % X -> 0
2940 if (I.getType()->isFPOrFPVector())
2941 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002942 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00002943 }
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002944 if (isa<UndefValue>(Op1))
2945 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer0a783f72006-11-02 01:53:59 +00002946
2947 // Handle cases involving: rem X, (select Cond, Y, Z)
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002948 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2949 return &I;
Chris Lattner5b73c082004-07-06 07:01:22 +00002950
Reid Spencer0a783f72006-11-02 01:53:59 +00002951 return 0;
2952}
2953
2954/// This function implements the transforms common to both integer remainder
2955/// instructions (urem and srem). It is called by the visitors to those integer
2956/// remainder instructions.
2957/// @brief Common integer remainder transforms
2958Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2959 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2960
2961 if (Instruction *common = commonRemTransforms(I))
2962 return common;
2963
Dale Johannesened6af242009-01-21 00:35:19 +00002964 // 0 % X == 0 for integer, we don't need to preserve faults!
2965 if (Constant *LHS = dyn_cast<Constant>(Op0))
2966 if (LHS->isNullValue())
2967 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2968
Chris Lattner857e8cd2004-12-12 21:48:58 +00002969 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002970 // X % 0 == undef, we don't need to preserve faults!
2971 if (RHS->equalsInt(0))
2972 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2973
Chris Lattnera2881962003-02-18 19:28:33 +00002974 if (RHS->equalsInt(1)) // X % 1 == 0
2975 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2976
Chris Lattner97943922006-02-28 05:49:21 +00002977 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2978 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2979 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2980 return R;
2981 } else if (isa<PHINode>(Op0I)) {
2982 if (Instruction *NV = FoldOpIntoPhi(I))
2983 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00002984 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00002985
2986 // See if we can fold away this rem instruction.
Chris Lattner886ab6c2009-01-31 08:15:18 +00002987 if (SimplifyDemandedInstructionBits(I))
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00002988 return &I;
Chris Lattner97943922006-02-28 05:49:21 +00002989 }
Chris Lattnera2881962003-02-18 19:28:33 +00002990 }
2991
Reid Spencer0a783f72006-11-02 01:53:59 +00002992 return 0;
2993}
2994
2995Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2996 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2997
2998 if (Instruction *common = commonIRemTransforms(I))
2999 return common;
3000
3001 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3002 // X urem C^2 -> X and C
3003 // Check to see if this is an unsigned remainder with an exact power of 2,
3004 // if so, convert to a bitwise and.
3005 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencerbca0e382007-03-23 20:05:17 +00003006 if (C->getValue().isPowerOf2())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003007 return BinaryOperator::CreateAnd(Op0, SubOne(C));
Reid Spencer0a783f72006-11-02 01:53:59 +00003008 }
3009
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003010 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003011 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3012 if (RHSI->getOpcode() == Instruction::Shl &&
3013 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng0fc50952007-03-25 05:01:29 +00003014 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003015 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003016 Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003017 "tmp"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003018 return BinaryOperator::CreateAnd(Op0, Add);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003019 }
3020 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003021 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003022
Reid Spencer0a783f72006-11-02 01:53:59 +00003023 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3024 // where C1&C2 are powers of two.
3025 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3026 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3027 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3028 // STO == 0 and SFO == 0 handled above.
Reid Spencerbca0e382007-03-23 20:05:17 +00003029 if ((STO->getValue().isPowerOf2()) &&
3030 (SFO->getValue().isPowerOf2())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003031 Value *TrueAnd = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003032 BinaryOperator::CreateAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
Reid Spencer0a783f72006-11-02 01:53:59 +00003033 Value *FalseAnd = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003034 BinaryOperator::CreateAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
Gabor Greif051a9502008-04-06 20:25:17 +00003035 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Reid Spencer0a783f72006-11-02 01:53:59 +00003036 }
3037 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003038 }
3039
Chris Lattner3f5b8772002-05-06 16:14:14 +00003040 return 0;
3041}
3042
Reid Spencer0a783f72006-11-02 01:53:59 +00003043Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3044 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3045
Dan Gohmancff55092007-11-05 23:16:33 +00003046 // Handle the integer rem common cases
Reid Spencer0a783f72006-11-02 01:53:59 +00003047 if (Instruction *common = commonIRemTransforms(I))
3048 return common;
3049
3050 if (Value *RHSNeg = dyn_castNegVal(Op1))
Nick Lewycky23c04302008-09-03 06:24:21 +00003051 if (!isa<Constant>(RHSNeg) ||
3052 (isa<ConstantInt>(RHSNeg) &&
3053 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003054 // X % -Y -> X % Y
3055 AddUsesToWorkList(I);
3056 I.setOperand(1, RHSNeg);
3057 return &I;
3058 }
Nick Lewyckya06cf822008-09-30 06:08:34 +00003059
Dan Gohmancff55092007-11-05 23:16:33 +00003060 // If the sign bits of both operands are zero (i.e. we can prove they are
Reid Spencer0a783f72006-11-02 01:53:59 +00003061 // unsigned inputs), turn this into a urem.
Dan Gohmancff55092007-11-05 23:16:33 +00003062 if (I.getType()->isInteger()) {
3063 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3064 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3065 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003066 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmancff55092007-11-05 23:16:33 +00003067 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003068 }
3069
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003070 // If it's a constant vector, flip any negative values positive.
Nick Lewycky9dce8732008-12-20 16:48:00 +00003071 if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3072 unsigned VWidth = RHSV->getNumOperands();
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003073
Nick Lewycky9dce8732008-12-20 16:48:00 +00003074 bool hasNegative = false;
3075 for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3076 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3077 if (RHS->getValue().isNegative())
3078 hasNegative = true;
3079
3080 if (hasNegative) {
3081 std::vector<Constant *> Elts(VWidth);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003082 for (unsigned i = 0; i != VWidth; ++i) {
3083 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3084 if (RHS->getValue().isNegative())
3085 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
3086 else
3087 Elts[i] = RHS;
3088 }
3089 }
3090
3091 Constant *NewRHSV = ConstantVector::get(Elts);
3092 if (NewRHSV != RHSV) {
Nick Lewycky19c28922008-12-18 06:42:28 +00003093 AddUsesToWorkList(I);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003094 I.setOperand(1, NewRHSV);
3095 return &I;
3096 }
3097 }
3098 }
3099
Reid Spencer0a783f72006-11-02 01:53:59 +00003100 return 0;
3101}
3102
3103Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003104 return commonRemTransforms(I);
3105}
3106
Chris Lattner457dd822004-06-09 07:59:58 +00003107// isOneBitSet - Return true if there is exactly one bit set in the specified
3108// constant.
3109static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer5f6a8952007-03-20 00:16:52 +00003110 return CI->getValue().isPowerOf2();
Chris Lattner457dd822004-06-09 07:59:58 +00003111}
3112
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003113// isHighOnes - Return true if the constant is of the form 1+0+.
3114// This is the same as lowones(~X).
3115static bool isHighOnes(const ConstantInt *CI) {
Zhou Sheng2cde46c2007-03-20 12:49:06 +00003116 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003117}
3118
Reid Spencere4d87aa2006-12-23 06:05:41 +00003119/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003120/// are carefully arranged to allow folding of expressions such as:
3121///
3122/// (A < B) | (A > B) --> (A != B)
3123///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003124/// Note that this is only valid if the first and second predicates have the
3125/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003126///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003127/// Three bits are used to represent the condition, as follows:
3128/// 0 A > B
3129/// 1 A == B
3130/// 2 A < B
3131///
3132/// <=> Value Definition
3133/// 000 0 Always false
3134/// 001 1 A > B
3135/// 010 2 A == B
3136/// 011 3 A >= B
3137/// 100 4 A < B
3138/// 101 5 A != B
3139/// 110 6 A <= B
3140/// 111 7 Always true
3141///
3142static unsigned getICmpCode(const ICmpInst *ICI) {
3143 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003144 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00003145 case ICmpInst::ICMP_UGT: return 1; // 001
3146 case ICmpInst::ICMP_SGT: return 1; // 001
3147 case ICmpInst::ICMP_EQ: return 2; // 010
3148 case ICmpInst::ICMP_UGE: return 3; // 011
3149 case ICmpInst::ICMP_SGE: return 3; // 011
3150 case ICmpInst::ICMP_ULT: return 4; // 100
3151 case ICmpInst::ICMP_SLT: return 4; // 100
3152 case ICmpInst::ICMP_NE: return 5; // 101
3153 case ICmpInst::ICMP_ULE: return 6; // 110
3154 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003155 // True -> 7
3156 default:
Reid Spencere4d87aa2006-12-23 06:05:41 +00003157 assert(0 && "Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003158 return 0;
3159 }
3160}
3161
Evan Cheng8db90722008-10-14 17:15:11 +00003162/// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3163/// predicate into a three bit mask. It also returns whether it is an ordered
3164/// predicate by reference.
3165static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3166 isOrdered = false;
3167 switch (CC) {
3168 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
3169 case FCmpInst::FCMP_UNO: return 0; // 000
Evan Cheng4990b252008-10-14 18:13:38 +00003170 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
3171 case FCmpInst::FCMP_UGT: return 1; // 001
3172 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
3173 case FCmpInst::FCMP_UEQ: return 2; // 010
Evan Cheng8db90722008-10-14 17:15:11 +00003174 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
3175 case FCmpInst::FCMP_UGE: return 3; // 011
3176 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
3177 case FCmpInst::FCMP_ULT: return 4; // 100
Evan Cheng4990b252008-10-14 18:13:38 +00003178 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
3179 case FCmpInst::FCMP_UNE: return 5; // 101
Evan Cheng8db90722008-10-14 17:15:11 +00003180 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
3181 case FCmpInst::FCMP_ULE: return 6; // 110
Evan Cheng40300622008-10-14 18:44:08 +00003182 // True -> 7
Evan Cheng8db90722008-10-14 17:15:11 +00003183 default:
3184 // Not expecting FCMP_FALSE and FCMP_TRUE;
3185 assert(0 && "Unexpected FCmp predicate!");
3186 return 0;
3187 }
3188}
3189
Reid Spencere4d87aa2006-12-23 06:05:41 +00003190/// getICmpValue - This is the complement of getICmpCode, which turns an
3191/// opcode and two operands into either a constant true or false, or a brand
Dan Gohman5d066ff2007-09-17 17:31:57 +00003192/// new ICmp instruction. The sign is passed in to determine which kind
Evan Cheng8db90722008-10-14 17:15:11 +00003193/// of predicate to use in the new icmp instruction.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003194static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3195 switch (code) {
3196 default: assert(0 && "Illegal ICmp code!");
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003197 case 0: return ConstantInt::getFalse();
Reid Spencere4d87aa2006-12-23 06:05:41 +00003198 case 1:
3199 if (sign)
3200 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3201 else
3202 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3203 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
3204 case 3:
3205 if (sign)
3206 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3207 else
3208 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3209 case 4:
3210 if (sign)
3211 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3212 else
3213 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3214 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
3215 case 6:
3216 if (sign)
3217 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3218 else
3219 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003220 case 7: return ConstantInt::getTrue();
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003221 }
3222}
3223
Evan Cheng8db90722008-10-14 17:15:11 +00003224/// getFCmpValue - This is the complement of getFCmpCode, which turns an
3225/// opcode and two operands into either a FCmp instruction. isordered is passed
3226/// in to determine which kind of predicate to use in the new fcmp instruction.
3227static Value *getFCmpValue(bool isordered, unsigned code,
3228 Value *LHS, Value *RHS) {
3229 switch (code) {
Evan Cheng4990b252008-10-14 18:13:38 +00003230 default: assert(0 && "Illegal FCmp code!");
Evan Cheng8db90722008-10-14 17:15:11 +00003231 case 0:
3232 if (isordered)
3233 return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
3234 else
3235 return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
3236 case 1:
3237 if (isordered)
Evan Cheng8db90722008-10-14 17:15:11 +00003238 return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
3239 else
3240 return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003241 case 2:
3242 if (isordered)
3243 return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
3244 else
3245 return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003246 case 3:
3247 if (isordered)
3248 return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
3249 else
3250 return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
3251 case 4:
3252 if (isordered)
3253 return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
3254 else
3255 return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
3256 case 5:
3257 if (isordered)
Evan Cheng4990b252008-10-14 18:13:38 +00003258 return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
3259 else
3260 return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
3261 case 6:
3262 if (isordered)
Evan Cheng8db90722008-10-14 17:15:11 +00003263 return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
3264 else
3265 return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
Evan Cheng40300622008-10-14 18:44:08 +00003266 case 7: return ConstantInt::getTrue();
Evan Cheng8db90722008-10-14 17:15:11 +00003267 }
3268}
3269
Chris Lattnerb9553d62008-11-16 04:55:20 +00003270/// PredicatesFoldable - Return true if both predicates match sign or if at
3271/// least one of them is an equality comparison (which is signless).
Reid Spencere4d87aa2006-12-23 06:05:41 +00003272static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3273 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
Chris Lattnerb9553d62008-11-16 04:55:20 +00003274 (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3275 (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003276}
3277
3278namespace {
3279// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3280struct FoldICmpLogical {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003281 InstCombiner &IC;
3282 Value *LHS, *RHS;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003283 ICmpInst::Predicate pred;
3284 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3285 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3286 pred(ICI->getPredicate()) {}
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003287 bool shouldApply(Value *V) const {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003288 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3289 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003290 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3291 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003292 return false;
3293 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003294 Instruction *apply(Instruction &Log) const {
3295 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3296 if (ICI->getOperand(0) != LHS) {
3297 assert(ICI->getOperand(1) == LHS);
3298 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003299 }
3300
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003301 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003302 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003303 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003304 unsigned Code;
3305 switch (Log.getOpcode()) {
3306 case Instruction::And: Code = LHSCode & RHSCode; break;
3307 case Instruction::Or: Code = LHSCode | RHSCode; break;
3308 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner021c1902003-09-22 20:33:34 +00003309 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003310 }
3311
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003312 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3313 ICmpInst::isSignedPredicate(ICI->getPredicate());
3314
3315 Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003316 if (Instruction *I = dyn_cast<Instruction>(RV))
3317 return I;
3318 // Otherwise, it's a constant boolean value...
3319 return IC.ReplaceInstUsesWith(Log, RV);
3320 }
3321};
Chris Lattnerd23b5ba2006-11-15 04:53:24 +00003322} // end anonymous namespace
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003323
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003324// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3325// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +00003326// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003327Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003328 ConstantInt *OpRHS,
3329 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003330 BinaryOperator &TheAnd) {
3331 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00003332 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +00003333 if (!Op->isShift())
Reid Spencer7177c3a2007-03-25 05:33:51 +00003334 Together = And(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00003335
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003336 switch (Op->getOpcode()) {
3337 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003338 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003339 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003340 Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003341 InsertNewInstBefore(And, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003342 And->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003343 return BinaryOperator::CreateXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003344 }
3345 break;
3346 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003347 if (Together == AndRHS) // (X | C) & C --> C
3348 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003349
Chris Lattner6e7ba452005-01-01 16:22:27 +00003350 if (Op->hasOneUse() && Together != OpRHS) {
3351 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003352 Instruction *Or = BinaryOperator::CreateOr(X, Together);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003353 InsertNewInstBefore(Or, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003354 Or->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003355 return BinaryOperator::CreateAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003356 }
3357 break;
3358 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00003359 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003360 // Adding a one to a single bit bit-field should be turned into an XOR
3361 // of the bit. First thing to check is to see if this AND is with a
3362 // single bit constant.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003363 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003364
3365 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00003366 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003367 // Ok, at this point, we know that we are masking the result of the
3368 // ADD down to exactly one bit. If the constant we are adding has
3369 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003370 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00003371
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003372 // Check to see if any bits below the one bit set in AndRHSV are set.
3373 if ((AddRHS & (AndRHSV-1)) == 0) {
3374 // If not, the only thing that can effect the output of the AND is
3375 // the bit specified by AndRHSV. If that bit is set, the effect of
3376 // the XOR is to toggle the bit. If it is clear, then the ADD has
3377 // no effect.
3378 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3379 TheAnd.setOperand(0, X);
3380 return &TheAnd;
3381 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003382 // Pull the XOR out of the AND.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003383 Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003384 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003385 NewAnd->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003386 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003387 }
3388 }
3389 }
3390 }
3391 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00003392
3393 case Instruction::Shl: {
3394 // We know that the AND will not produce any of the bits shifted in, so if
3395 // the anded constant includes them, clear them now!
3396 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003397 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003398 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003399 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3400 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00003401
Zhou Sheng290bec52007-03-29 08:15:12 +00003402 if (CI->getValue() == ShlMask) {
3403 // Masking out bits that the shift already masks
Chris Lattner0c967662004-09-24 15:21:34 +00003404 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3405 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00003406 TheAnd.setOperand(1, CI);
3407 return &TheAnd;
3408 }
3409 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00003410 }
Reid Spencer3822ff52006-11-08 06:47:33 +00003411 case Instruction::LShr:
3412 {
Chris Lattner62a355c2003-09-19 19:05:02 +00003413 // We know that the AND will not produce any of the bits shifted in, so if
3414 // the anded constant includes them, clear them now! This only applies to
3415 // unsigned shifts, because a signed shr may bring in set bits!
3416 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003417 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003418 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003419 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3420 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00003421
Zhou Sheng290bec52007-03-29 08:15:12 +00003422 if (CI->getValue() == ShrMask) {
3423 // Masking out bits that the shift already masks.
Reid Spencer3822ff52006-11-08 06:47:33 +00003424 return ReplaceInstUsesWith(TheAnd, Op);
3425 } else if (CI != AndRHS) {
3426 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3427 return &TheAnd;
3428 }
3429 break;
3430 }
3431 case Instruction::AShr:
3432 // Signed shr.
3433 // See if this is shifting in some sign extension, then masking it out
3434 // with an and.
3435 if (Op->hasOneUse()) {
Zhou Sheng290bec52007-03-29 08:15:12 +00003436 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003437 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003438 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3439 Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
Reid Spencer7eb76382006-12-13 17:19:09 +00003440 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +00003441 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +00003442 // Make the argument unsigned.
3443 Value *ShVal = Op->getOperand(0);
Reid Spencer832254e2007-02-02 02:16:23 +00003444 ShVal = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003445 BinaryOperator::CreateLShr(ShVal, OpRHS,
Reid Spencer832254e2007-02-02 02:16:23 +00003446 Op->getName()), TheAnd);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003447 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00003448 }
Chris Lattner62a355c2003-09-19 19:05:02 +00003449 }
3450 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003451 }
3452 return 0;
3453}
3454
Chris Lattner8b170942002-08-09 23:47:40 +00003455
Chris Lattnera96879a2004-09-29 17:40:11 +00003456/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3457/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +00003458/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3459/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +00003460/// insert new instructions.
3461Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003462 bool isSigned, bool Inside,
3463 Instruction &IB) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003464 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +00003465 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +00003466 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003467
Chris Lattnera96879a2004-09-29 17:40:11 +00003468 if (Inside) {
3469 if (Lo == Hi) // Trivially false.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003470 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +00003471
Reid Spencere4d87aa2006-12-23 06:05:41 +00003472 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003473 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4e40032007-03-21 23:19:50 +00003474 ICmpInst::Predicate pred = (isSigned ?
Reid Spencere4d87aa2006-12-23 06:05:41 +00003475 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3476 return new ICmpInst(pred, V, Hi);
3477 }
3478
3479 // Emit V-Lo <u Hi-Lo
3480 Constant *NegLo = ConstantExpr::getNeg(Lo);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003481 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003482 InsertNewInstBefore(Add, IB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003483 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3484 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003485 }
3486
3487 if (Lo == Hi) // Trivially true.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003488 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +00003489
Reid Spencere4e40032007-03-21 23:19:50 +00003490 // V < Min || V >= Hi -> V > Hi-1
Chris Lattnera96879a2004-09-29 17:40:11 +00003491 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003492 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003493 ICmpInst::Predicate pred = (isSigned ?
3494 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3495 return new ICmpInst(pred, V, Hi);
3496 }
Reid Spencerb83eb642006-10-20 07:07:24 +00003497
Reid Spencere4e40032007-03-21 23:19:50 +00003498 // Emit V-Lo >u Hi-1-Lo
3499 // Note that Hi has already had one subtracted from it, above.
3500 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003501 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003502 InsertNewInstBefore(Add, IB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003503 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3504 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003505}
3506
Chris Lattner7203e152005-09-18 07:22:02 +00003507// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3508// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3509// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3510// not, since all 1s are not contiguous.
Zhou Sheng4351c642007-04-02 08:20:41 +00003511static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003512 const APInt& V = Val->getValue();
Reid Spencerf2442522007-03-24 00:42:08 +00003513 uint32_t BitWidth = Val->getType()->getBitWidth();
3514 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattner7203e152005-09-18 07:22:02 +00003515
3516 // look for the first zero bit after the run of ones
Reid Spencerf2442522007-03-24 00:42:08 +00003517 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattner7203e152005-09-18 07:22:02 +00003518 // look for the first non-zero bit
Reid Spencerf2442522007-03-24 00:42:08 +00003519 ME = V.getActiveBits();
Chris Lattner7203e152005-09-18 07:22:02 +00003520 return true;
3521}
3522
Chris Lattner7203e152005-09-18 07:22:02 +00003523/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3524/// where isSub determines whether the operator is a sub. If we can fold one of
3525/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00003526///
3527/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3528/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3529/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3530///
3531/// return (A +/- B).
3532///
3533Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003534 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +00003535 Instruction &I) {
3536 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3537 if (!LHSI || LHSI->getNumOperands() != 2 ||
3538 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3539
3540 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3541
3542 switch (LHSI->getOpcode()) {
3543 default: return 0;
3544 case Instruction::And:
Reid Spencer7177c3a2007-03-25 05:33:51 +00003545 if (And(N, Mask) == Mask) {
Chris Lattner7203e152005-09-18 07:22:02 +00003546 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Sheng00f436c2007-03-24 15:34:37 +00003547 if ((Mask->getValue().countLeadingZeros() +
3548 Mask->getValue().countPopulation()) ==
3549 Mask->getValue().getBitWidth())
Chris Lattner7203e152005-09-18 07:22:02 +00003550 break;
3551
3552 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3553 // part, we don't need any explicit masks to take them out of A. If that
3554 // is all N is, ignore it.
Zhou Sheng4351c642007-04-02 08:20:41 +00003555 uint32_t MB = 0, ME = 0;
Chris Lattner7203e152005-09-18 07:22:02 +00003556 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerb35ae032007-03-23 18:46:34 +00003557 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Sheng290bec52007-03-29 08:15:12 +00003558 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattner3bedbd92006-02-07 07:27:52 +00003559 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00003560 break;
3561 }
3562 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00003563 return 0;
3564 case Instruction::Or:
3565 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00003566 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Sheng00f436c2007-03-24 15:34:37 +00003567 if ((Mask->getValue().countLeadingZeros() +
3568 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Reid Spencer6eb0d992007-03-26 23:58:26 +00003569 && And(N, Mask)->isZero())
Chris Lattnerc8e77562005-09-18 04:24:45 +00003570 break;
3571 return 0;
3572 }
3573
3574 Instruction *New;
3575 if (isSub)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003576 New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00003577 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003578 New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00003579 return InsertNewInstBefore(New, I);
3580}
3581
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003582/// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3583Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3584 ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattnerea065fb2008-11-16 05:10:52 +00003585 Value *Val, *Val2;
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003586 ConstantInt *LHSCst, *RHSCst;
3587 ICmpInst::Predicate LHSCC, RHSCC;
3588
Chris Lattnerea065fb2008-11-16 05:10:52 +00003589 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003590 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) ||
Chris Lattnerea065fb2008-11-16 05:10:52 +00003591 !match(RHS, m_ICmp(RHSCC, m_Value(Val2), m_ConstantInt(RHSCst))))
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003592 return 0;
Chris Lattnerea065fb2008-11-16 05:10:52 +00003593
3594 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3595 // where C is a power of 2
3596 if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3597 LHSCst->getValue().isPowerOf2()) {
3598 Instruction *NewOr = BinaryOperator::CreateOr(Val, Val2);
3599 InsertNewInstBefore(NewOr, I);
3600 return new ICmpInst(LHSCC, NewOr, LHSCst);
3601 }
3602
3603 // From here on, we only handle:
3604 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3605 if (Val != Val2) return 0;
3606
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003607 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3608 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3609 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3610 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3611 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3612 return 0;
3613
3614 // We can't fold (ugt x, C) & (sgt x, C2).
3615 if (!PredicatesFoldable(LHSCC, RHSCC))
3616 return 0;
3617
3618 // Ensure that the larger constant is on the RHS.
Chris Lattneraa3e1572008-11-16 05:14:43 +00003619 bool ShouldSwap;
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003620 if (ICmpInst::isSignedPredicate(LHSCC) ||
3621 (ICmpInst::isEquality(LHSCC) &&
3622 ICmpInst::isSignedPredicate(RHSCC)))
Chris Lattneraa3e1572008-11-16 05:14:43 +00003623 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003624 else
Chris Lattneraa3e1572008-11-16 05:14:43 +00003625 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3626
3627 if (ShouldSwap) {
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003628 std::swap(LHS, RHS);
3629 std::swap(LHSCst, RHSCst);
3630 std::swap(LHSCC, RHSCC);
3631 }
3632
3633 // At this point, we know we have have two icmp instructions
3634 // comparing a value against two constants and and'ing the result
3635 // together. Because of the above check, we know that we only have
3636 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3637 // (from the FoldICmpLogical check above), that the two constants
3638 // are not equal and that the larger constant is on the RHS
3639 assert(LHSCst != RHSCst && "Compares not folded above?");
3640
3641 switch (LHSCC) {
3642 default: assert(0 && "Unknown integer condition code!");
3643 case ICmpInst::ICMP_EQ:
3644 switch (RHSCC) {
3645 default: assert(0 && "Unknown integer condition code!");
3646 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3647 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3648 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
3649 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3650 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3651 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3652 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
3653 return ReplaceInstUsesWith(I, LHS);
3654 }
3655 case ICmpInst::ICMP_NE:
3656 switch (RHSCC) {
3657 default: assert(0 && "Unknown integer condition code!");
3658 case ICmpInst::ICMP_ULT:
3659 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3660 return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
3661 break; // (X != 13 & X u< 15) -> no change
3662 case ICmpInst::ICMP_SLT:
3663 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3664 return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
3665 break; // (X != 13 & X s< 15) -> no change
3666 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3667 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3668 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
3669 return ReplaceInstUsesWith(I, RHS);
3670 case ICmpInst::ICMP_NE:
3671 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3672 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3673 Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
3674 Val->getName()+".off");
3675 InsertNewInstBefore(Add, I);
3676 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3677 ConstantInt::get(Add->getType(), 1));
3678 }
3679 break; // (X != 13 & X != 15) -> no change
3680 }
3681 break;
3682 case ICmpInst::ICMP_ULT:
3683 switch (RHSCC) {
3684 default: assert(0 && "Unknown integer condition code!");
3685 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3686 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
3687 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3688 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3689 break;
3690 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3691 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
3692 return ReplaceInstUsesWith(I, LHS);
3693 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3694 break;
3695 }
3696 break;
3697 case ICmpInst::ICMP_SLT:
3698 switch (RHSCC) {
3699 default: assert(0 && "Unknown integer condition code!");
3700 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3701 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
3702 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3703 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3704 break;
3705 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3706 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
3707 return ReplaceInstUsesWith(I, LHS);
3708 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3709 break;
3710 }
3711 break;
3712 case ICmpInst::ICMP_UGT:
3713 switch (RHSCC) {
3714 default: assert(0 && "Unknown integer condition code!");
3715 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
3716 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3717 return ReplaceInstUsesWith(I, RHS);
3718 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3719 break;
3720 case ICmpInst::ICMP_NE:
3721 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3722 return new ICmpInst(LHSCC, Val, RHSCst);
3723 break; // (X u> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00003724 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003725 return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, false, true, I);
3726 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3727 break;
3728 }
3729 break;
3730 case ICmpInst::ICMP_SGT:
3731 switch (RHSCC) {
3732 default: assert(0 && "Unknown integer condition code!");
3733 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
3734 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3735 return ReplaceInstUsesWith(I, RHS);
3736 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3737 break;
3738 case ICmpInst::ICMP_NE:
3739 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3740 return new ICmpInst(LHSCC, Val, RHSCst);
3741 break; // (X s> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00003742 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003743 return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, true, true, I);
3744 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3745 break;
3746 }
3747 break;
3748 }
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003749
3750 return 0;
3751}
3752
3753
Chris Lattner7e708292002-06-25 16:13:24 +00003754Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003755 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00003756 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003757
Chris Lattnere87597f2004-10-16 18:11:37 +00003758 if (isa<UndefValue>(Op1)) // X & undef -> 0
3759 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3760
Chris Lattner6e7ba452005-01-01 16:22:27 +00003761 // and X, X = X
3762 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00003763 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003764
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003765 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00003766 // purpose is to compute bits we don't care about.
Reid Spencer9d6565a2007-02-15 02:26:10 +00003767 if (!isa<VectorType>(I.getType())) {
Chris Lattner886ab6c2009-01-31 08:15:18 +00003768 if (SimplifyDemandedInstructionBits(I))
Reid Spencer6eb0d992007-03-26 23:58:26 +00003769 return &I;
Chris Lattner696ee0a2007-01-18 22:16:33 +00003770 } else {
Reid Spencer9d6565a2007-02-15 02:26:10 +00003771 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
Chris Lattner041a6c92007-06-15 05:26:55 +00003772 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
Chris Lattner696ee0a2007-01-18 22:16:33 +00003773 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner041a6c92007-06-15 05:26:55 +00003774 } else if (isa<ConstantAggregateZero>(Op1)) {
3775 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
Chris Lattner696ee0a2007-01-18 22:16:33 +00003776 }
3777 }
Chris Lattner9ca96412006-02-08 03:25:32 +00003778
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003779 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003780 const APInt& AndRHSMask = AndRHS->getValue();
3781 APInt NotAndRHS(~AndRHSMask);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003782
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003783 // Optimize a variety of ((val OP C1) & C2) combinations...
Reid Spencer832254e2007-02-02 02:16:23 +00003784 if (isa<BinaryOperator>(Op0)) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003785 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003786 Value *Op0LHS = Op0I->getOperand(0);
3787 Value *Op0RHS = Op0I->getOperand(1);
3788 switch (Op0I->getOpcode()) {
3789 case Instruction::Xor:
3790 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00003791 // If the mask is only needed on one incoming arm, push it up.
3792 if (Op0I->hasOneUse()) {
3793 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3794 // Not masking anything out for the LHS, move to RHS.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003795 Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
Chris Lattnerad1e3022005-01-23 20:26:55 +00003796 Op0RHS->getName()+".masked");
3797 InsertNewInstBefore(NewRHS, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003798 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00003799 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003800 }
Chris Lattner3bedbd92006-02-07 07:27:52 +00003801 if (!isa<Constant>(Op0RHS) &&
Chris Lattnerad1e3022005-01-23 20:26:55 +00003802 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3803 // Not masking anything out for the RHS, move to LHS.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003804 Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
Chris Lattnerad1e3022005-01-23 20:26:55 +00003805 Op0LHS->getName()+".masked");
3806 InsertNewInstBefore(NewLHS, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003807 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00003808 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3809 }
3810 }
3811
Chris Lattner6e7ba452005-01-01 16:22:27 +00003812 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00003813 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00003814 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3815 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3816 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3817 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003818 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattner7203e152005-09-18 07:22:02 +00003819 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003820 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00003821 break;
3822
3823 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00003824 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3825 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3826 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3827 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003828 return BinaryOperator::CreateAnd(V, AndRHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00003829
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00003830 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
3831 // has 1's for all bits that the subtraction with A might affect.
3832 if (Op0I->hasOneUse()) {
3833 uint32_t BitWidth = AndRHSMask.getBitWidth();
3834 uint32_t Zeros = AndRHSMask.countLeadingZeros();
3835 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
3836
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00003837 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00003838 if (!(A && A->isZero()) && // avoid infinite recursion.
3839 MaskedValueIsZero(Op0LHS, Mask)) {
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00003840 Instruction *NewNeg = BinaryOperator::CreateNeg(Op0RHS);
3841 InsertNewInstBefore(NewNeg, I);
3842 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
3843 }
3844 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00003845 break;
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00003846
3847 case Instruction::Shl:
3848 case Instruction::LShr:
3849 // (1 << x) & 1 --> zext(x == 0)
3850 // (1 >> x) & 1 --> zext(x == 0)
Nick Lewyckyd8ad4922008-07-09 07:35:26 +00003851 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00003852 Instruction *NewICmp = new ICmpInst(ICmpInst::ICMP_EQ, Op0RHS,
3853 Constant::getNullValue(I.getType()));
3854 InsertNewInstBefore(NewICmp, I);
3855 return new ZExtInst(NewICmp, I.getType());
3856 }
3857 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00003858 }
3859
Chris Lattner58403262003-07-23 19:25:52 +00003860 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003861 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003862 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00003863 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00003864 // If this is an integer truncation or change from signed-to-unsigned, and
3865 // if the source is an and/or with immediate, transform it. This
3866 // frequently occurs for bitfield accesses.
3867 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00003868 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00003869 CastOp->getNumOperands() == 2)
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003870 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
Chris Lattner2b83af22005-08-07 07:03:10 +00003871 if (CastOp->getOpcode() == Instruction::And) {
3872 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00003873 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
3874 // This will fold the two constants together, which may allow
3875 // other simplifications.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003876 Instruction *NewCast = CastInst::CreateTruncOrBitCast(
Reid Spencerd977d862006-12-12 23:36:14 +00003877 CastOp->getOperand(0), I.getType(),
3878 CastOp->getName()+".shrunk");
Chris Lattner2b83af22005-08-07 07:03:10 +00003879 NewCast = InsertNewInstBefore(NewCast, I);
Reid Spencer3da59db2006-11-27 01:05:10 +00003880 // trunc_or_bitcast(C1)&C2
Reid Spencerd977d862006-12-12 23:36:14 +00003881 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00003882 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003883 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner2b83af22005-08-07 07:03:10 +00003884 } else if (CastOp->getOpcode() == Instruction::Or) {
3885 // Change: and (cast (or X, C1) to T), C2
3886 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattnerbb4e7b22006-12-12 19:11:20 +00003887 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Chris Lattner2b83af22005-08-07 07:03:10 +00003888 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3889 return ReplaceInstUsesWith(I, AndRHS);
3890 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003891 }
Chris Lattner2b83af22005-08-07 07:03:10 +00003892 }
Chris Lattner06782f82003-07-23 19:36:21 +00003893 }
Chris Lattner2eefe512004-04-09 19:05:30 +00003894
3895 // Try to fold constant and into select arguments.
3896 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003897 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00003898 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00003899 if (isa<PHINode>(Op0))
3900 if (Instruction *NV = FoldOpIntoPhi(I))
3901 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00003902 }
3903
Chris Lattner8d969642003-03-10 23:06:50 +00003904 Value *Op0NotVal = dyn_castNotVal(Op0);
3905 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00003906
Chris Lattner5b62aa72004-06-18 06:07:51 +00003907 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3908 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3909
Misha Brukmancb6267b2004-07-30 12:50:08 +00003910 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00003911 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003912 Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
Chris Lattner48595f12004-06-10 02:07:29 +00003913 I.getName()+".demorgan");
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00003914 InsertNewInstBefore(Or, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003915 return BinaryOperator::CreateNot(Or);
Chris Lattnera2881962003-02-18 19:28:33 +00003916 }
Chris Lattner2082ad92006-02-13 23:07:23 +00003917
3918 {
Chris Lattner003b6202007-06-15 05:58:24 +00003919 Value *A = 0, *B = 0, *C = 0, *D = 0;
3920 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00003921 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3922 return ReplaceInstUsesWith(I, Op1);
Chris Lattner003b6202007-06-15 05:58:24 +00003923
3924 // (A|B) & ~(A&B) -> A^B
3925 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
3926 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003927 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00003928 }
3929 }
3930
3931 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00003932 if (A == Op0 || B == Op0) // A & (A | ?) --> A
3933 return ReplaceInstUsesWith(I, Op0);
Chris Lattner003b6202007-06-15 05:58:24 +00003934
3935 // ~(A&B) & (A|B) -> A^B
3936 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
3937 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003938 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00003939 }
3940 }
Chris Lattner64daab52006-04-01 08:03:55 +00003941
3942 if (Op0->hasOneUse() &&
3943 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3944 if (A == Op1) { // (A^B)&A -> A&(A^B)
3945 I.swapOperands(); // Simplify below
3946 std::swap(Op0, Op1);
3947 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
3948 cast<BinaryOperator>(Op0)->swapOperands();
3949 I.swapOperands(); // Simplify below
3950 std::swap(Op0, Op1);
3951 }
3952 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00003953
Chris Lattner64daab52006-04-01 08:03:55 +00003954 if (Op1->hasOneUse() &&
3955 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3956 if (B == Op0) { // B&(A^B) -> B&(B^A)
3957 cast<BinaryOperator>(Op1)->swapOperands();
3958 std::swap(A, B);
3959 }
3960 if (A == Op0) { // A&(A^B) -> A & ~B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003961 Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
Chris Lattner64daab52006-04-01 08:03:55 +00003962 InsertNewInstBefore(NotB, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003963 return BinaryOperator::CreateAnd(A, NotB);
Chris Lattner64daab52006-04-01 08:03:55 +00003964 }
3965 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00003966
3967 // (A&((~A)|B)) -> A&B
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00003968 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
3969 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
3970 return BinaryOperator::CreateAnd(A, Op1);
3971 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
3972 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
3973 return BinaryOperator::CreateAnd(A, Op0);
Chris Lattner2082ad92006-02-13 23:07:23 +00003974 }
3975
Reid Spencere4d87aa2006-12-23 06:05:41 +00003976 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3977 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3978 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003979 return R;
3980
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003981 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
3982 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
3983 return Res;
Chris Lattner955f3312004-09-28 21:48:02 +00003984 }
3985
Chris Lattner6fc205f2006-05-05 06:39:07 +00003986 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003987 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3988 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3989 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3990 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00003991 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003992 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003993 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
3994 I.getType(), TD) &&
3995 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
3996 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003997 Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003998 Op1C->getOperand(0),
3999 I.getName());
4000 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004001 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004002 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004003 }
Chris Lattnere511b742006-11-14 07:46:50 +00004004
4005 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004006 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4007 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4008 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004009 SI0->getOperand(1) == SI1->getOperand(1) &&
4010 (SI0->hasOneUse() || SI1->hasOneUse())) {
4011 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004012 InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
Chris Lattnere511b742006-11-14 07:46:50 +00004013 SI1->getOperand(0),
4014 SI0->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004015 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004016 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004017 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004018 }
4019
Evan Cheng8db90722008-10-14 17:15:11 +00004020 // If and'ing two fcmp, try combine them into one.
Chris Lattner99c65742007-10-24 05:38:08 +00004021 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4022 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4023 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
Evan Cheng8db90722008-10-14 17:15:11 +00004024 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
4025 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
Chris Lattner99c65742007-10-24 05:38:08 +00004026 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4027 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4028 // If either of the constants are nans, then the whole thing returns
4029 // false.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00004030 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner99c65742007-10-24 05:38:08 +00004031 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4032 return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
4033 RHS->getOperand(0));
4034 }
Evan Cheng8db90722008-10-14 17:15:11 +00004035 } else {
4036 Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4037 FCmpInst::Predicate Op0CC, Op1CC;
4038 if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS), m_Value(Op0RHS))) &&
4039 match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS), m_Value(Op1RHS)))) {
Evan Cheng4990b252008-10-14 18:13:38 +00004040 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4041 // Swap RHS operands to match LHS.
4042 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4043 std::swap(Op1LHS, Op1RHS);
4044 }
Evan Cheng8db90722008-10-14 17:15:11 +00004045 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4046 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4047 if (Op0CC == Op1CC)
4048 return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
4049 else if (Op0CC == FCmpInst::FCMP_FALSE ||
4050 Op1CC == FCmpInst::FCMP_FALSE)
4051 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4052 else if (Op0CC == FCmpInst::FCMP_TRUE)
4053 return ReplaceInstUsesWith(I, Op1);
4054 else if (Op1CC == FCmpInst::FCMP_TRUE)
4055 return ReplaceInstUsesWith(I, Op0);
4056 bool Op0Ordered;
4057 bool Op1Ordered;
4058 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4059 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4060 if (Op1Pred == 0) {
4061 std::swap(Op0, Op1);
4062 std::swap(Op0Pred, Op1Pred);
4063 std::swap(Op0Ordered, Op1Ordered);
4064 }
4065 if (Op0Pred == 0) {
4066 // uno && ueq -> uno && (uno || eq) -> ueq
4067 // ord && olt -> ord && (ord && lt) -> olt
4068 if (Op0Ordered == Op1Ordered)
4069 return ReplaceInstUsesWith(I, Op1);
4070 // uno && oeq -> uno && (ord && eq) -> false
4071 // uno && ord -> false
4072 if (!Op0Ordered)
4073 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4074 // ord && ueq -> ord && (uno || eq) -> oeq
4075 return cast<Instruction>(getFCmpValue(true, Op1Pred,
4076 Op0LHS, Op0RHS));
4077 }
4078 }
4079 }
4080 }
Chris Lattner99c65742007-10-24 05:38:08 +00004081 }
4082 }
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004083
Chris Lattner7e708292002-06-25 16:13:24 +00004084 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004085}
4086
Chris Lattner8c34cd22008-10-05 02:13:19 +00004087/// CollectBSwapParts - Analyze the specified subexpression and see if it is
4088/// capable of providing pieces of a bswap. The subexpression provides pieces
4089/// of a bswap if it is proven that each of the non-zero bytes in the output of
4090/// the expression came from the corresponding "byte swapped" byte in some other
4091/// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
4092/// we know that the expression deposits the low byte of %X into the high byte
4093/// of the bswap result and that all other bytes are zero. This expression is
4094/// accepted, the high byte of ByteValues is set to X to indicate a correct
4095/// match.
4096///
4097/// This function returns true if the match was unsuccessful and false if so.
4098/// On entry to the function the "OverallLeftShift" is a signed integer value
4099/// indicating the number of bytes that the subexpression is later shifted. For
4100/// example, if the expression is later right shifted by 16 bits, the
4101/// OverallLeftShift value would be -2 on entry. This is used to specify which
4102/// byte of ByteValues is actually being set.
4103///
4104/// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4105/// byte is masked to zero by a user. For example, in (X & 255), X will be
4106/// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
4107/// this function to working on up to 32-byte (256 bit) values. ByteMask is
4108/// always in the local (OverallLeftShift) coordinate space.
4109///
4110static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4111 SmallVector<Value*, 8> &ByteValues) {
4112 if (Instruction *I = dyn_cast<Instruction>(V)) {
4113 // If this is an or instruction, it may be an inner node of the bswap.
4114 if (I->getOpcode() == Instruction::Or) {
4115 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4116 ByteValues) ||
4117 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4118 ByteValues);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004119 }
Chris Lattner8c34cd22008-10-05 02:13:19 +00004120
4121 // If this is a logical shift by a constant multiple of 8, recurse with
4122 // OverallLeftShift and ByteMask adjusted.
4123 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4124 unsigned ShAmt =
4125 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4126 // Ensure the shift amount is defined and of a byte value.
4127 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4128 return true;
4129
4130 unsigned ByteShift = ShAmt >> 3;
4131 if (I->getOpcode() == Instruction::Shl) {
4132 // X << 2 -> collect(X, +2)
4133 OverallLeftShift += ByteShift;
4134 ByteMask >>= ByteShift;
4135 } else {
4136 // X >>u 2 -> collect(X, -2)
4137 OverallLeftShift -= ByteShift;
4138 ByteMask <<= ByteShift;
Chris Lattnerde17ddc2008-10-08 06:42:28 +00004139 ByteMask &= (~0U >> (32-ByteValues.size()));
Chris Lattner8c34cd22008-10-05 02:13:19 +00004140 }
4141
4142 if (OverallLeftShift >= (int)ByteValues.size()) return true;
4143 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4144
4145 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4146 ByteValues);
4147 }
4148
4149 // If this is a logical 'and' with a mask that clears bytes, clear the
4150 // corresponding bytes in ByteMask.
4151 if (I->getOpcode() == Instruction::And &&
4152 isa<ConstantInt>(I->getOperand(1))) {
4153 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4154 unsigned NumBytes = ByteValues.size();
4155 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4156 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4157
4158 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4159 // If this byte is masked out by a later operation, we don't care what
4160 // the and mask is.
4161 if ((ByteMask & (1 << i)) == 0)
4162 continue;
4163
4164 // If the AndMask is all zeros for this byte, clear the bit.
4165 APInt MaskB = AndMask & Byte;
4166 if (MaskB == 0) {
4167 ByteMask &= ~(1U << i);
4168 continue;
4169 }
4170
4171 // If the AndMask is not all ones for this byte, it's not a bytezap.
4172 if (MaskB != Byte)
4173 return true;
4174
4175 // Otherwise, this byte is kept.
4176 }
4177
4178 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4179 ByteValues);
4180 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004181 }
4182
Chris Lattner8c34cd22008-10-05 02:13:19 +00004183 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
4184 // the input value to the bswap. Some observations: 1) if more than one byte
4185 // is demanded from this input, then it could not be successfully assembled
4186 // into a byteswap. At least one of the two bytes would not be aligned with
4187 // their ultimate destination.
4188 if (!isPowerOf2_32(ByteMask)) return true;
4189 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004190
Chris Lattner8c34cd22008-10-05 02:13:19 +00004191 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4192 // is demanded, it needs to go into byte 0 of the result. This means that the
4193 // byte needs to be shifted until it lands in the right byte bucket. The
4194 // shift amount depends on the position: if the byte is coming from the high
4195 // part of the value (e.g. byte 3) then it must be shifted right. If from the
4196 // low part, it must be shifted left.
4197 unsigned DestByteNo = InputByteNo + OverallLeftShift;
4198 if (InputByteNo < ByteValues.size()/2) {
4199 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4200 return true;
4201 } else {
4202 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4203 return true;
4204 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004205
4206 // If the destination byte value is already defined, the values are or'd
4207 // together, which isn't a bswap (unless it's an or of the same bits).
Chris Lattner8c34cd22008-10-05 02:13:19 +00004208 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
Chris Lattnerafe91a52006-06-15 19:07:26 +00004209 return true;
Chris Lattner8c34cd22008-10-05 02:13:19 +00004210 ByteValues[DestByteNo] = V;
Chris Lattnerafe91a52006-06-15 19:07:26 +00004211 return false;
4212}
4213
4214/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4215/// If so, insert the new bswap intrinsic and return it.
4216Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattner55fc8c42007-04-01 20:57:36 +00004217 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
Chris Lattner8c34cd22008-10-05 02:13:19 +00004218 if (!ITy || ITy->getBitWidth() % 16 ||
4219 // ByteMask only allows up to 32-byte values.
4220 ITy->getBitWidth() > 32*8)
Chris Lattner55fc8c42007-04-01 20:57:36 +00004221 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004222
4223 /// ByteValues - For each byte of the result, we keep track of which value
4224 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00004225 SmallVector<Value*, 8> ByteValues;
Chris Lattner55fc8c42007-04-01 20:57:36 +00004226 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004227
4228 // Try to find all the pieces corresponding to the bswap.
Chris Lattner8c34cd22008-10-05 02:13:19 +00004229 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4230 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
Chris Lattnerafe91a52006-06-15 19:07:26 +00004231 return 0;
4232
4233 // Check to see if all of the bytes come from the same value.
4234 Value *V = ByteValues[0];
4235 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4236
4237 // Check to make sure that all of the bytes come from the same value.
4238 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4239 if (ByteValues[i] != V)
4240 return 0;
Chandler Carruth69940402007-08-04 01:51:18 +00004241 const Type *Tys[] = { ITy };
Chris Lattnerafe91a52006-06-15 19:07:26 +00004242 Module *M = I.getParent()->getParent()->getParent();
Chandler Carruth69940402007-08-04 01:51:18 +00004243 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greif051a9502008-04-06 20:25:17 +00004244 return CallInst::Create(F, V);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004245}
4246
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004247/// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
4248/// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4249/// we can simplify this expression to "cond ? C : D or B".
4250static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
4251 Value *C, Value *D) {
Chris Lattnera6a474d2008-11-16 04:26:55 +00004252 // If A is not a select of -1/0, this cannot match.
Chris Lattner6046fb72008-11-16 04:46:19 +00004253 Value *Cond = 0;
Chris Lattner159c35b2009-01-05 23:53:12 +00004254 if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004255 return 0;
4256
Chris Lattnera6a474d2008-11-16 04:26:55 +00004257 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
Chris Lattner159c35b2009-01-05 23:53:12 +00004258 if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004259 return SelectInst::Create(Cond, C, B);
Chris Lattner159c35b2009-01-05 23:53:12 +00004260 if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004261 return SelectInst::Create(Cond, C, B);
4262 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
Chris Lattner159c35b2009-01-05 23:53:12 +00004263 if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004264 return SelectInst::Create(Cond, C, D);
Chris Lattner159c35b2009-01-05 23:53:12 +00004265 if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004266 return SelectInst::Create(Cond, C, D);
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004267 return 0;
4268}
Chris Lattnerafe91a52006-06-15 19:07:26 +00004269
Chris Lattner69d4ced2008-11-16 05:20:07 +00004270/// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4271Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4272 ICmpInst *LHS, ICmpInst *RHS) {
4273 Value *Val, *Val2;
4274 ConstantInt *LHSCst, *RHSCst;
4275 ICmpInst::Predicate LHSCC, RHSCC;
4276
4277 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
4278 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) ||
4279 !match(RHS, m_ICmp(RHSCC, m_Value(Val2), m_ConstantInt(RHSCst))))
4280 return 0;
4281
4282 // From here on, we only handle:
4283 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4284 if (Val != Val2) return 0;
4285
4286 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4287 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4288 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4289 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4290 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4291 return 0;
4292
4293 // We can't fold (ugt x, C) | (sgt x, C2).
4294 if (!PredicatesFoldable(LHSCC, RHSCC))
4295 return 0;
4296
4297 // Ensure that the larger constant is on the RHS.
4298 bool ShouldSwap;
4299 if (ICmpInst::isSignedPredicate(LHSCC) ||
4300 (ICmpInst::isEquality(LHSCC) &&
4301 ICmpInst::isSignedPredicate(RHSCC)))
4302 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4303 else
4304 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4305
4306 if (ShouldSwap) {
4307 std::swap(LHS, RHS);
4308 std::swap(LHSCst, RHSCst);
4309 std::swap(LHSCC, RHSCC);
4310 }
4311
4312 // At this point, we know we have have two icmp instructions
4313 // comparing a value against two constants and or'ing the result
4314 // together. Because of the above check, we know that we only have
4315 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4316 // FoldICmpLogical check above), that the two constants are not
4317 // equal.
4318 assert(LHSCst != RHSCst && "Compares not folded above?");
4319
4320 switch (LHSCC) {
4321 default: assert(0 && "Unknown integer condition code!");
4322 case ICmpInst::ICMP_EQ:
4323 switch (RHSCC) {
4324 default: assert(0 && "Unknown integer condition code!");
4325 case ICmpInst::ICMP_EQ:
4326 if (LHSCst == SubOne(RHSCst)) { // (X == 13 | X == 14) -> X-13 <u 2
4327 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4328 Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
4329 Val->getName()+".off");
4330 InsertNewInstBefore(Add, I);
4331 AddCST = Subtract(AddOne(RHSCst), LHSCst);
4332 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4333 }
4334 break; // (X == 13 | X == 15) -> no change
4335 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4336 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4337 break;
4338 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4339 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4340 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4341 return ReplaceInstUsesWith(I, RHS);
4342 }
4343 break;
4344 case ICmpInst::ICMP_NE:
4345 switch (RHSCC) {
4346 default: assert(0 && "Unknown integer condition code!");
4347 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4348 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4349 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4350 return ReplaceInstUsesWith(I, LHS);
4351 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4352 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4353 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
4354 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4355 }
4356 break;
4357 case ICmpInst::ICMP_ULT:
4358 switch (RHSCC) {
4359 default: assert(0 && "Unknown integer condition code!");
4360 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4361 break;
4362 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
4363 // If RHSCst is [us]MAXINT, it is always false. Not handling
4364 // this can cause overflow.
4365 if (RHSCst->isMaxValue(false))
4366 return ReplaceInstUsesWith(I, LHS);
4367 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), false, false, I);
4368 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4369 break;
4370 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4371 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4372 return ReplaceInstUsesWith(I, RHS);
4373 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4374 break;
4375 }
4376 break;
4377 case ICmpInst::ICMP_SLT:
4378 switch (RHSCC) {
4379 default: assert(0 && "Unknown integer condition code!");
4380 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4381 break;
4382 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
4383 // If RHSCst is [us]MAXINT, it is always false. Not handling
4384 // this can cause overflow.
4385 if (RHSCst->isMaxValue(true))
4386 return ReplaceInstUsesWith(I, LHS);
4387 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), true, false, I);
4388 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4389 break;
4390 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4391 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4392 return ReplaceInstUsesWith(I, RHS);
4393 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4394 break;
4395 }
4396 break;
4397 case ICmpInst::ICMP_UGT:
4398 switch (RHSCC) {
4399 default: assert(0 && "Unknown integer condition code!");
4400 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4401 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4402 return ReplaceInstUsesWith(I, LHS);
4403 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4404 break;
4405 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4406 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
4407 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4408 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4409 break;
4410 }
4411 break;
4412 case ICmpInst::ICMP_SGT:
4413 switch (RHSCC) {
4414 default: assert(0 && "Unknown integer condition code!");
4415 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4416 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4417 return ReplaceInstUsesWith(I, LHS);
4418 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4419 break;
4420 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4421 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
4422 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4423 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4424 break;
4425 }
4426 break;
4427 }
4428 return 0;
4429}
4430
Bill Wendlinga698a472008-12-01 08:23:25 +00004431/// FoldOrWithConstants - This helper function folds:
4432///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004433/// ((A | B) & C1) | (B & C2)
Bill Wendlinga698a472008-12-01 08:23:25 +00004434///
4435/// into:
4436///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004437/// (A & C1) | B
Bill Wendlingd54d8602008-12-01 08:32:40 +00004438///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004439/// when the XOR of the two constants is "all ones" (-1).
Bill Wendlingd54d8602008-12-01 08:32:40 +00004440Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +00004441 Value *A, Value *B, Value *C) {
Bill Wendlingdda74e02008-12-02 05:06:43 +00004442 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4443 if (!CI1) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00004444
Bill Wendling286a0542008-12-02 06:24:20 +00004445 Value *V1 = 0;
4446 ConstantInt *CI2 = 0;
4447 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00004448
Bill Wendling29976b92008-12-02 06:18:11 +00004449 APInt Xor = CI1->getValue() ^ CI2->getValue();
4450 if (!Xor.isAllOnesValue()) return 0;
4451
Bill Wendling286a0542008-12-02 06:24:20 +00004452 if (V1 == A || V1 == B) {
Bill Wendling29976b92008-12-02 06:18:11 +00004453 Instruction *NewOp =
Bill Wendlingd16c6e92008-12-02 06:22:04 +00004454 InsertNewInstBefore(BinaryOperator::CreateAnd((V1 == A) ? B : A, CI1), I);
4455 return BinaryOperator::CreateOr(NewOp, V1);
Bill Wendlinga698a472008-12-01 08:23:25 +00004456 }
4457
4458 return 0;
4459}
4460
Chris Lattner7e708292002-06-25 16:13:24 +00004461Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004462 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004463 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004464
Chris Lattner42593e62007-03-24 23:56:43 +00004465 if (isa<UndefValue>(Op1)) // X | undef -> -1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004466 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004467
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004468 // or X, X = X
4469 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00004470 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004471
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004472 // See if we can simplify any instructions used by the instruction whose sole
4473 // purpose is to compute bits we don't care about.
Chris Lattner42593e62007-03-24 23:56:43 +00004474 if (!isa<VectorType>(I.getType())) {
Chris Lattner886ab6c2009-01-31 08:15:18 +00004475 if (SimplifyDemandedInstructionBits(I))
Chris Lattner42593e62007-03-24 23:56:43 +00004476 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00004477 } else if (isa<ConstantAggregateZero>(Op1)) {
4478 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4479 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4480 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4481 return ReplaceInstUsesWith(I, I.getOperand(1));
Chris Lattner42593e62007-03-24 23:56:43 +00004482 }
Chris Lattner041a6c92007-06-15 05:26:55 +00004483
4484
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004485
Chris Lattner3f5b8772002-05-06 16:14:14 +00004486 // or X, -1 == -1
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004487 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00004488 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004489 // (X & C1) | C2 --> (X | C2) & (C1|C2)
4490 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004491 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004492 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00004493 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004494 return BinaryOperator::CreateAnd(Or,
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004495 ConstantInt::get(RHS->getValue() | C1->getValue()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004496 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004497
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004498 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4499 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004500 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004501 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00004502 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004503 return BinaryOperator::CreateXor(Or,
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004504 ConstantInt::get(C1->getValue() & ~RHS->getValue()));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004505 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004506
4507 // Try to fold constant and into select arguments.
4508 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004509 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004510 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004511 if (isa<PHINode>(Op0))
4512 if (Instruction *NV = FoldOpIntoPhi(I))
4513 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004514 }
4515
Chris Lattner4f637d42006-01-06 17:59:59 +00004516 Value *A = 0, *B = 0;
4517 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004518
4519 if (match(Op0, m_And(m_Value(A), m_Value(B))))
4520 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4521 return ReplaceInstUsesWith(I, Op1);
4522 if (match(Op1, m_And(m_Value(A), m_Value(B))))
4523 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4524 return ReplaceInstUsesWith(I, Op0);
4525
Chris Lattner6423d4c2006-07-10 20:25:24 +00004526 // (A | B) | C and A | (B | C) -> bswap if possible.
4527 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004528 if (match(Op0, m_Or(m_Value(), m_Value())) ||
Chris Lattner6423d4c2006-07-10 20:25:24 +00004529 match(Op1, m_Or(m_Value(), m_Value())) ||
4530 (match(Op0, m_Shift(m_Value(), m_Value())) &&
4531 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00004532 if (Instruction *BSwap = MatchBSwap(I))
4533 return BSwap;
4534 }
4535
Chris Lattner6e4c6492005-05-09 04:58:36 +00004536 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4537 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004538 MaskedValueIsZero(Op1, C1->getValue())) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004539 Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00004540 InsertNewInstBefore(NOr, I);
4541 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004542 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004543 }
4544
4545 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4546 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004547 MaskedValueIsZero(Op0, C1->getValue())) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004548 Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
Chris Lattner6934a042007-02-11 01:23:03 +00004549 InsertNewInstBefore(NOr, I);
4550 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004551 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004552 }
4553
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004554 // (A & C)|(B & D)
Chris Lattner2384d7b2007-06-19 05:43:49 +00004555 Value *C = 0, *D = 0;
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004556 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4557 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004558 Value *V1 = 0, *V2 = 0, *V3 = 0;
4559 C1 = dyn_cast<ConstantInt>(C);
4560 C2 = dyn_cast<ConstantInt>(D);
4561 if (C1 && C2) { // (A & C1)|(B & C2)
4562 // If we have: ((V + N) & C1) | (V & C2)
4563 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4564 // replace with V+N.
4565 if (C1->getValue() == ~C2->getValue()) {
4566 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4567 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4568 // Add commutes, try both ways.
4569 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4570 return ReplaceInstUsesWith(I, A);
4571 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4572 return ReplaceInstUsesWith(I, A);
4573 }
4574 // Or commutes, try both ways.
4575 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4576 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4577 // Add commutes, try both ways.
4578 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4579 return ReplaceInstUsesWith(I, B);
4580 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4581 return ReplaceInstUsesWith(I, B);
4582 }
4583 }
Chris Lattner044e5332007-04-08 08:01:49 +00004584 V1 = 0; V2 = 0; V3 = 0;
Chris Lattner6cae0e02007-04-08 07:55:22 +00004585 }
4586
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004587 // Check to see if we have any common things being and'ed. If so, find the
4588 // terms for V1 & (V2|V3).
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004589 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4590 if (A == B) // (A & C)|(A & D) == A & (C|D)
4591 V1 = A, V2 = C, V3 = D;
4592 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4593 V1 = A, V2 = B, V3 = C;
4594 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4595 V1 = C, V2 = A, V3 = D;
4596 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4597 V1 = C, V2 = A, V3 = B;
4598
4599 if (V1) {
4600 Value *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004601 InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4602 return BinaryOperator::CreateAnd(V1, Or);
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00004603 }
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004604 }
Dan Gohmanb493b272008-10-28 22:38:57 +00004605
Dan Gohman1975d032008-10-30 20:40:10 +00004606 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004607 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D))
4608 return Match;
4609 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C))
4610 return Match;
4611 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D))
4612 return Match;
4613 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C))
4614 return Match;
Bill Wendlingb01865c2008-11-30 13:52:49 +00004615
Bill Wendlingb01865c2008-11-30 13:52:49 +00004616 // ((A&~B)|(~A&B)) -> A^B
Bill Wendling03aae5f2008-12-01 08:09:47 +00004617 if ((match(C, m_Not(m_Specific(D))) &&
4618 match(B, m_Not(m_Specific(A)))))
4619 return BinaryOperator::CreateXor(A, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004620 // ((~B&A)|(~A&B)) -> A^B
Bill Wendling03aae5f2008-12-01 08:09:47 +00004621 if ((match(A, m_Not(m_Specific(D))) &&
4622 match(B, m_Not(m_Specific(C)))))
4623 return BinaryOperator::CreateXor(C, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004624 // ((A&~B)|(B&~A)) -> A^B
Bill Wendling03aae5f2008-12-01 08:09:47 +00004625 if ((match(C, m_Not(m_Specific(B))) &&
4626 match(D, m_Not(m_Specific(A)))))
4627 return BinaryOperator::CreateXor(A, B);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004628 // ((~B&A)|(B&~A)) -> A^B
Bill Wendling03aae5f2008-12-01 08:09:47 +00004629 if ((match(A, m_Not(m_Specific(B))) &&
4630 match(D, m_Not(m_Specific(C)))))
4631 return BinaryOperator::CreateXor(C, B);
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004632 }
Chris Lattnere511b742006-11-14 07:46:50 +00004633
4634 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004635 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4636 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4637 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004638 SI0->getOperand(1) == SI1->getOperand(1) &&
4639 (SI0->hasOneUse() || SI1->hasOneUse())) {
4640 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004641 InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
Chris Lattnere511b742006-11-14 07:46:50 +00004642 SI1->getOperand(0),
4643 SI0->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004644 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004645 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004646 }
4647 }
Chris Lattner67ca7682003-08-12 19:11:07 +00004648
Bill Wendlingb3833d12008-12-01 01:07:11 +00004649 // ((A|B)&1)|(B&-2) -> (A&1) | B
4650 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4651 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00004652 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00004653 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00004654 }
4655 // (B&-2)|((A|B)&1) -> (A&1) | B
4656 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4657 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00004658 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00004659 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00004660 }
4661
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004662 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
4663 if (A == Op1) // ~A | A == -1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004664 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004665 } else {
4666 A = 0;
4667 }
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004668 // Note, A is still live here!
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004669 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
4670 if (Op0 == B)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004671 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera27231a2003-03-10 23:13:59 +00004672
Misha Brukmancb6267b2004-07-30 12:50:08 +00004673 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004674 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004675 Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004676 I.getName()+".demorgan"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004677 return BinaryOperator::CreateNot(And);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004678 }
Chris Lattnera27231a2003-03-10 23:13:59 +00004679 }
Chris Lattnera2881962003-02-18 19:28:33 +00004680
Reid Spencere4d87aa2006-12-23 06:05:41 +00004681 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4682 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4683 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004684 return R;
4685
Chris Lattner69d4ced2008-11-16 05:20:07 +00004686 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4687 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4688 return Res;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004689 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004690
4691 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00004692 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00004693 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004694 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chengb98a10e2008-03-24 00:21:34 +00004695 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4696 !isa<ICmpInst>(Op1C->getOperand(0))) {
4697 const Type *SrcTy = Op0C->getOperand(0)->getType();
4698 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4699 // Only do this if the casts both really cause code to be
4700 // generated.
4701 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4702 I.getType(), TD) &&
4703 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4704 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004705 Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
Evan Chengb98a10e2008-03-24 00:21:34 +00004706 Op1C->getOperand(0),
4707 I.getName());
4708 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004709 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00004710 }
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004711 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004712 }
Chris Lattner99c65742007-10-24 05:38:08 +00004713 }
4714
4715
4716 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4717 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4718 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4719 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
Chris Lattner5ebd9362008-02-29 06:09:11 +00004720 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
Evan Cheng40300622008-10-14 18:44:08 +00004721 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
Chris Lattner99c65742007-10-24 05:38:08 +00004722 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4723 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4724 // If either of the constants are nans, then the whole thing returns
4725 // true.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00004726 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner99c65742007-10-24 05:38:08 +00004727 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4728
4729 // Otherwise, no need to compare the two constants, compare the
4730 // rest.
4731 return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4732 RHS->getOperand(0));
4733 }
Evan Cheng40300622008-10-14 18:44:08 +00004734 } else {
4735 Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4736 FCmpInst::Predicate Op0CC, Op1CC;
4737 if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS), m_Value(Op0RHS))) &&
4738 match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS), m_Value(Op1RHS)))) {
4739 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4740 // Swap RHS operands to match LHS.
4741 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4742 std::swap(Op1LHS, Op1RHS);
4743 }
4744 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4745 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4746 if (Op0CC == Op1CC)
4747 return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
4748 else if (Op0CC == FCmpInst::FCMP_TRUE ||
4749 Op1CC == FCmpInst::FCMP_TRUE)
4750 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4751 else if (Op0CC == FCmpInst::FCMP_FALSE)
4752 return ReplaceInstUsesWith(I, Op1);
4753 else if (Op1CC == FCmpInst::FCMP_FALSE)
4754 return ReplaceInstUsesWith(I, Op0);
4755 bool Op0Ordered;
4756 bool Op1Ordered;
4757 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4758 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4759 if (Op0Ordered == Op1Ordered) {
4760 // If both are ordered or unordered, return a new fcmp with
4761 // or'ed predicates.
4762 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4763 Op0LHS, Op0RHS);
4764 if (Instruction *I = dyn_cast<Instruction>(RV))
4765 return I;
4766 // Otherwise, it's a constant boolean value...
4767 return ReplaceInstUsesWith(I, RV);
4768 }
4769 }
4770 }
4771 }
Chris Lattner99c65742007-10-24 05:38:08 +00004772 }
4773 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004774
Chris Lattner7e708292002-06-25 16:13:24 +00004775 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004776}
4777
Dan Gohman844731a2008-05-13 00:00:25 +00004778namespace {
4779
Chris Lattnerc317d392004-02-16 01:20:27 +00004780// XorSelf - Implements: X ^ X --> 0
4781struct XorSelf {
4782 Value *RHS;
4783 XorSelf(Value *rhs) : RHS(rhs) {}
4784 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4785 Instruction *apply(BinaryOperator &Xor) const {
4786 return &Xor;
4787 }
4788};
Chris Lattner3f5b8772002-05-06 16:14:14 +00004789
Dan Gohman844731a2008-05-13 00:00:25 +00004790}
Chris Lattner3f5b8772002-05-06 16:14:14 +00004791
Chris Lattner7e708292002-06-25 16:13:24 +00004792Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004793 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004794 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004795
Evan Chengd34af782008-03-25 20:07:13 +00004796 if (isa<UndefValue>(Op1)) {
4797 if (isa<UndefValue>(Op0))
4798 // Handle undef ^ undef -> 0 special case. This is a common
4799 // idiom (misuse).
4800 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004801 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chengd34af782008-03-25 20:07:13 +00004802 }
Chris Lattnere87597f2004-10-16 18:11:37 +00004803
Chris Lattnerc317d392004-02-16 01:20:27 +00004804 // xor X, X = 0, even if X is nested in a sequence of Xor's.
4805 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00004806 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Chris Lattner233f7dc2002-08-12 21:17:25 +00004807 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00004808 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004809
4810 // See if we can simplify any instructions used by the instruction whose sole
4811 // purpose is to compute bits we don't care about.
Reid Spencera03d45f2007-03-22 22:19:58 +00004812 if (!isa<VectorType>(I.getType())) {
Chris Lattner886ab6c2009-01-31 08:15:18 +00004813 if (SimplifyDemandedInstructionBits(I))
Reid Spencera03d45f2007-03-22 22:19:58 +00004814 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00004815 } else if (isa<ConstantAggregateZero>(Op1)) {
4816 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Reid Spencera03d45f2007-03-22 22:19:58 +00004817 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00004818
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004819 // Is this a ~ operation?
4820 if (Value *NotOp = dyn_castNotVal(&I)) {
4821 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4822 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4823 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4824 if (Op0I->getOpcode() == Instruction::And ||
4825 Op0I->getOpcode() == Instruction::Or) {
4826 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4827 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4828 Instruction *NotY =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004829 BinaryOperator::CreateNot(Op0I->getOperand(1),
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004830 Op0I->getOperand(1)->getName()+".not");
4831 InsertNewInstBefore(NotY, I);
4832 if (Op0I->getOpcode() == Instruction::And)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004833 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004834 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004835 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004836 }
4837 }
4838 }
4839 }
4840
4841
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004842 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00004843 if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
Bill Wendling3479be92009-01-01 01:18:23 +00004844 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00004845 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00004846 return new ICmpInst(ICI->getInversePredicate(),
4847 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00004848
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00004849 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
4850 return new FCmpInst(FCI->getInversePredicate(),
4851 FCI->getOperand(0), FCI->getOperand(1));
4852 }
4853
Nick Lewycky517e1f52008-05-31 19:01:33 +00004854 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
4855 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4856 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
4857 if (CI->hasOneUse() && Op0C->hasOneUse()) {
4858 Instruction::CastOps Opcode = Op0C->getOpcode();
4859 if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
4860 if (RHS == ConstantExpr::getCast(Opcode, ConstantInt::getTrue(),
4861 Op0C->getDestTy())) {
4862 Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
4863 CI->getOpcode(), CI->getInversePredicate(),
4864 CI->getOperand(0), CI->getOperand(1)), I);
4865 NewCI->takeName(CI);
4866 return CastInst::Create(Opcode, NewCI, Op0C->getType());
4867 }
4868 }
4869 }
4870 }
4871 }
4872
Reid Spencere4d87aa2006-12-23 06:05:41 +00004873 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00004874 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00004875 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4876 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattner48595f12004-06-10 02:07:29 +00004877 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4878 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattner7c4049c2004-01-12 19:35:11 +00004879 ConstantInt::get(I.getType(), 1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004880 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00004881 }
Chris Lattner5c6e2db2007-04-02 05:36:22 +00004882
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004883 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004884 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00004885 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00004886 if (RHS->isAllOnesValue()) {
Chris Lattner48595f12004-06-10 02:07:29 +00004887 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004888 return BinaryOperator::CreateSub(
Chris Lattner48595f12004-06-10 02:07:29 +00004889 ConstantExpr::getSub(NegOp0CI,
Chris Lattner7c4049c2004-01-12 19:35:11 +00004890 ConstantInt::get(I.getType(), 1)),
Chris Lattner689d24b2003-11-04 23:37:10 +00004891 Op0I->getOperand(0));
Chris Lattneracf4e072007-04-02 05:42:22 +00004892 } else if (RHS->getValue().isSignBit()) {
Chris Lattner5c6e2db2007-04-02 05:36:22 +00004893 // (X + C) ^ signbit -> (X + C + signbit)
4894 Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004895 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Chris Lattnercd1d6d52007-04-02 05:48:58 +00004896
Chris Lattner7c4049c2004-01-12 19:35:11 +00004897 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00004898 } else if (Op0I->getOpcode() == Instruction::Or) {
4899 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencera03d45f2007-03-22 22:19:58 +00004900 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Chris Lattner02bd1b32006-02-26 19:57:54 +00004901 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4902 // Anything in both C1 and C2 is known to be zero, remove it from
4903 // NewRHS.
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004904 Constant *CommonBits = And(Op0CI, RHS);
Chris Lattner02bd1b32006-02-26 19:57:54 +00004905 NewRHS = ConstantExpr::getAnd(NewRHS,
4906 ConstantExpr::getNot(CommonBits));
Chris Lattnerdbab3862007-03-02 21:28:56 +00004907 AddToWorkList(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00004908 I.setOperand(0, Op0I->getOperand(0));
4909 I.setOperand(1, NewRHS);
4910 return &I;
4911 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00004912 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004913 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00004914 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004915
4916 // Try to fold constant and into select arguments.
4917 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004918 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004919 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004920 if (isa<PHINode>(Op0))
4921 if (Instruction *NV = FoldOpIntoPhi(I))
4922 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004923 }
4924
Chris Lattner8d969642003-03-10 23:06:50 +00004925 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00004926 if (X == Op1)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004927 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00004928
Chris Lattner8d969642003-03-10 23:06:50 +00004929 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00004930 if (X == Op0)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004931 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00004932
Chris Lattner318bf792007-03-18 22:51:34 +00004933
4934 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
4935 if (Op1I) {
4936 Value *A, *B;
4937 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
4938 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00004939 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00004940 I.swapOperands();
4941 std::swap(Op0, Op1);
Chris Lattner318bf792007-03-18 22:51:34 +00004942 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00004943 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00004944 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00004945 }
Chris Lattnercb504b92008-11-16 05:38:51 +00004946 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
4947 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
4948 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
4949 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
Chris Lattner318bf792007-03-18 22:51:34 +00004950 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
Chris Lattner6abbdf92007-04-01 05:36:37 +00004951 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattner64daab52006-04-01 08:03:55 +00004952 Op1I->swapOperands();
Chris Lattner6abbdf92007-04-01 05:36:37 +00004953 std::swap(A, B);
4954 }
Chris Lattner318bf792007-03-18 22:51:34 +00004955 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattner64daab52006-04-01 08:03:55 +00004956 I.swapOperands(); // Simplified below.
4957 std::swap(Op0, Op1);
4958 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00004959 }
Chris Lattner318bf792007-03-18 22:51:34 +00004960 }
4961
4962 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
4963 if (Op0I) {
4964 Value *A, *B;
4965 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
4966 if (A == Op1) // (B|A)^B == (A|B)^B
4967 std::swap(A, B);
4968 if (B == Op1) { // (A|B)^B == A & ~B
4969 Instruction *NotB =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004970 InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I);
4971 return BinaryOperator::CreateAnd(A, NotB);
Chris Lattnercb40a372003-03-10 18:24:17 +00004972 }
Chris Lattnercb504b92008-11-16 05:38:51 +00004973 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
4974 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
4975 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
4976 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
Chris Lattner318bf792007-03-18 22:51:34 +00004977 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
4978 if (A == Op1) // (A&B)^A -> (B&A)^A
4979 std::swap(A, B);
4980 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattnerae1ab392006-04-01 22:05:01 +00004981 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner318bf792007-03-18 22:51:34 +00004982 Instruction *N =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004983 InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I);
4984 return BinaryOperator::CreateAnd(N, Op1);
Chris Lattner64daab52006-04-01 08:03:55 +00004985 }
Chris Lattnercb40a372003-03-10 18:24:17 +00004986 }
Chris Lattner318bf792007-03-18 22:51:34 +00004987 }
4988
4989 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
4990 if (Op0I && Op1I && Op0I->isShift() &&
4991 Op0I->getOpcode() == Op1I->getOpcode() &&
4992 Op0I->getOperand(1) == Op1I->getOperand(1) &&
4993 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
4994 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004995 InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
Chris Lattner318bf792007-03-18 22:51:34 +00004996 Op1I->getOperand(0),
4997 Op0I->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004998 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Chris Lattner318bf792007-03-18 22:51:34 +00004999 Op1I->getOperand(1));
5000 }
5001
5002 if (Op0I && Op1I) {
5003 Value *A, *B, *C, *D;
5004 // (A & B)^(A | B) -> A ^ B
5005 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5006 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
5007 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005008 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005009 }
5010 // (A | B)^(A & B) -> A ^ B
5011 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5012 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5013 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005014 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005015 }
5016
5017 // (A & B)^(C & D)
5018 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
5019 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5020 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5021 // (X & Y)^(X & Y) -> (Y^Z) & X
5022 Value *X = 0, *Y = 0, *Z = 0;
5023 if (A == C)
5024 X = A, Y = B, Z = D;
5025 else if (A == D)
5026 X = A, Y = B, Z = C;
5027 else if (B == C)
5028 X = B, Y = A, Z = D;
5029 else if (B == D)
5030 X = B, Y = A, Z = C;
5031
5032 if (X) {
5033 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005034 InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
5035 return BinaryOperator::CreateAnd(NewOp, X);
Chris Lattner318bf792007-03-18 22:51:34 +00005036 }
5037 }
5038 }
5039
Reid Spencere4d87aa2006-12-23 06:05:41 +00005040 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5041 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
5042 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00005043 return R;
5044
Chris Lattner6fc205f2006-05-05 06:39:07 +00005045 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00005046 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00005047 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005048 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5049 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00005050 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005051 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005052 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5053 I.getType(), TD) &&
5054 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5055 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005056 Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005057 Op1C->getOperand(0),
5058 I.getName());
5059 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005060 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005061 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00005062 }
Chris Lattner99c65742007-10-24 05:38:08 +00005063 }
Nick Lewycky517e1f52008-05-31 19:01:33 +00005064
Chris Lattner7e708292002-06-25 16:13:24 +00005065 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005066}
5067
Chris Lattnera96879a2004-09-29 17:40:11 +00005068/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
5069/// overflowed for this type.
5070static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
Reid Spencere4e40032007-03-21 23:19:50 +00005071 ConstantInt *In2, bool IsSigned = false) {
Zhou Sheng4a1822a2007-04-02 13:45:30 +00005072 Result = cast<ConstantInt>(Add(In1, In2));
Chris Lattnera96879a2004-09-29 17:40:11 +00005073
Reid Spencere4e40032007-03-21 23:19:50 +00005074 if (IsSigned)
5075 if (In2->getValue().isNegative())
5076 return Result->getValue().sgt(In1->getValue());
5077 else
5078 return Result->getValue().slt(In1->getValue());
5079 else
5080 return Result->getValue().ult(In1->getValue());
Chris Lattnera96879a2004-09-29 17:40:11 +00005081}
5082
Dan Gohman1df3fd62008-09-10 23:30:57 +00005083/// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5084/// overflowed for this type.
5085static bool SubWithOverflow(ConstantInt *&Result, ConstantInt *In1,
5086 ConstantInt *In2, bool IsSigned = false) {
Dan Gohmanbcb37fd2008-09-11 18:53:02 +00005087 Result = cast<ConstantInt>(Subtract(In1, In2));
Dan Gohman1df3fd62008-09-10 23:30:57 +00005088
5089 if (IsSigned)
5090 if (In2->getValue().isNegative())
5091 return Result->getValue().slt(In1->getValue());
5092 else
5093 return Result->getValue().sgt(In1->getValue());
5094 else
5095 return Result->getValue().ugt(In1->getValue());
5096}
5097
Chris Lattner574da9b2005-01-13 20:14:25 +00005098/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5099/// code necessary to compute the offset from the base pointer (without adding
5100/// in the base pointer). Return the result as a signed integer of intptr size.
5101static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
5102 TargetData &TD = IC.getTargetData();
5103 gep_type_iterator GTI = gep_type_begin(GEP);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005104 const Type *IntPtrTy = TD.getIntPtrType();
5105 Value *Result = Constant::getNullValue(IntPtrTy);
Chris Lattner574da9b2005-01-13 20:14:25 +00005106
5107 // Build a mask for high order bits.
Chris Lattner10c0d912008-04-22 02:53:33 +00005108 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Chris Lattnere62f0212007-04-28 04:52:43 +00005109 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Chris Lattner574da9b2005-01-13 20:14:25 +00005110
Gabor Greif177dd3f2008-06-12 21:37:33 +00005111 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5112 ++i, ++GTI) {
5113 Value *Op = *i;
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00005114 uint64_t Size = TD.getTypePaddedSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattnere62f0212007-04-28 04:52:43 +00005115 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5116 if (OpC->isZero()) continue;
5117
5118 // Handle a struct index, which adds its field offset to the pointer.
5119 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5120 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5121
5122 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
5123 Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
Chris Lattner9bc14642007-04-28 00:57:34 +00005124 else
Chris Lattnere62f0212007-04-28 04:52:43 +00005125 Result = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005126 BinaryOperator::CreateAdd(Result,
Chris Lattnere62f0212007-04-28 04:52:43 +00005127 ConstantInt::get(IntPtrTy, Size),
5128 GEP->getName()+".offs"), I);
5129 continue;
Chris Lattner9bc14642007-04-28 00:57:34 +00005130 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005131
5132 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5133 Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5134 Scale = ConstantExpr::getMul(OC, Scale);
5135 if (Constant *RC = dyn_cast<Constant>(Result))
5136 Result = ConstantExpr::getAdd(RC, Scale);
5137 else {
5138 // Emit an add instruction.
5139 Result = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005140 BinaryOperator::CreateAdd(Result, Scale,
Chris Lattnere62f0212007-04-28 04:52:43 +00005141 GEP->getName()+".offs"), I);
Chris Lattner9bc14642007-04-28 00:57:34 +00005142 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005143 continue;
Chris Lattner574da9b2005-01-13 20:14:25 +00005144 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005145 // Convert to correct type.
5146 if (Op->getType() != IntPtrTy) {
5147 if (Constant *OpC = dyn_cast<Constant>(Op))
5148 Op = ConstantExpr::getSExt(OpC, IntPtrTy);
5149 else
5150 Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
5151 Op->getName()+".c"), I);
5152 }
5153 if (Size != 1) {
5154 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5155 if (Constant *OpC = dyn_cast<Constant>(Op))
5156 Op = ConstantExpr::getMul(OpC, Scale);
5157 else // We'll let instcombine(mul) convert this to a shl if possible.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005158 Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
Chris Lattnere62f0212007-04-28 04:52:43 +00005159 GEP->getName()+".idx"), I);
5160 }
5161
5162 // Emit an add instruction.
5163 if (isa<Constant>(Op) && isa<Constant>(Result))
5164 Result = ConstantExpr::getAdd(cast<Constant>(Op),
5165 cast<Constant>(Result));
5166 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005167 Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
Chris Lattnere62f0212007-04-28 04:52:43 +00005168 GEP->getName()+".offs"), I);
Chris Lattner574da9b2005-01-13 20:14:25 +00005169 }
5170 return Result;
5171}
5172
Chris Lattner10c0d912008-04-22 02:53:33 +00005173
5174/// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
5175/// the *offset* implied by GEP to zero. For example, if we have &A[i], we want
5176/// to return 'i' for "icmp ne i, 0". Note that, in general, indices can be
5177/// complex, and scales are involved. The above expression would also be legal
5178/// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32). This
5179/// later form is less amenable to optimization though, and we are allowed to
5180/// generate the first by knowing that pointer arithmetic doesn't overflow.
5181///
5182/// If we can't emit an optimized form for this expression, this returns null.
5183///
5184static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5185 InstCombiner &IC) {
Chris Lattner10c0d912008-04-22 02:53:33 +00005186 TargetData &TD = IC.getTargetData();
5187 gep_type_iterator GTI = gep_type_begin(GEP);
5188
5189 // Check to see if this gep only has a single variable index. If so, and if
5190 // any constant indices are a multiple of its scale, then we can compute this
5191 // in terms of the scale of the variable index. For example, if the GEP
5192 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5193 // because the expression will cross zero at the same point.
5194 unsigned i, e = GEP->getNumOperands();
5195 int64_t Offset = 0;
5196 for (i = 1; i != e; ++i, ++GTI) {
5197 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5198 // Compute the aggregate offset of constant indices.
5199 if (CI->isZero()) continue;
5200
5201 // Handle a struct index, which adds its field offset to the pointer.
5202 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5203 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5204 } else {
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00005205 uint64_t Size = TD.getTypePaddedSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005206 Offset += Size*CI->getSExtValue();
5207 }
5208 } else {
5209 // Found our variable index.
5210 break;
5211 }
5212 }
5213
5214 // If there are no variable indices, we must have a constant offset, just
5215 // evaluate it the general way.
5216 if (i == e) return 0;
5217
5218 Value *VariableIdx = GEP->getOperand(i);
5219 // Determine the scale factor of the variable element. For example, this is
5220 // 4 if the variable index is into an array of i32.
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00005221 uint64_t VariableScale = TD.getTypePaddedSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005222
5223 // Verify that there are no other variable indices. If so, emit the hard way.
5224 for (++i, ++GTI; i != e; ++i, ++GTI) {
5225 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5226 if (!CI) return 0;
5227
5228 // Compute the aggregate offset of constant indices.
5229 if (CI->isZero()) continue;
5230
5231 // Handle a struct index, which adds its field offset to the pointer.
5232 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5233 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5234 } else {
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00005235 uint64_t Size = TD.getTypePaddedSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005236 Offset += Size*CI->getSExtValue();
5237 }
5238 }
5239
5240 // Okay, we know we have a single variable index, which must be a
5241 // pointer/array/vector index. If there is no offset, life is simple, return
5242 // the index.
5243 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5244 if (Offset == 0) {
5245 // Cast to intptrty in case a truncation occurs. If an extension is needed,
5246 // we don't need to bother extending: the extension won't affect where the
5247 // computation crosses zero.
5248 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5249 VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
5250 VariableIdx->getNameStart(), &I);
5251 return VariableIdx;
5252 }
5253
5254 // Otherwise, there is an index. The computation we will do will be modulo
5255 // the pointer size, so get it.
5256 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5257
5258 Offset &= PtrSizeMask;
5259 VariableScale &= PtrSizeMask;
5260
5261 // To do this transformation, any constant index must be a multiple of the
5262 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
5263 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
5264 // multiple of the variable scale.
5265 int64_t NewOffs = Offset / (int64_t)VariableScale;
5266 if (Offset != NewOffs*(int64_t)VariableScale)
5267 return 0;
5268
5269 // Okay, we can do this evaluation. Start by converting the index to intptr.
5270 const Type *IntPtrTy = TD.getIntPtrType();
5271 if (VariableIdx->getType() != IntPtrTy)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005272 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
Chris Lattner10c0d912008-04-22 02:53:33 +00005273 true /*SExt*/,
5274 VariableIdx->getNameStart(), &I);
5275 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005276 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
Chris Lattner10c0d912008-04-22 02:53:33 +00005277}
5278
5279
Reid Spencere4d87aa2006-12-23 06:05:41 +00005280/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner574da9b2005-01-13 20:14:25 +00005281/// else. At this point we know that the GEP is on the LHS of the comparison.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005282Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
5283 ICmpInst::Predicate Cond,
5284 Instruction &I) {
Chris Lattner574da9b2005-01-13 20:14:25 +00005285 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattnere9d782b2005-01-13 22:25:21 +00005286
Chris Lattner10c0d912008-04-22 02:53:33 +00005287 // Look through bitcasts.
5288 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5289 RHS = BCI->getOperand(0);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005290
Chris Lattner574da9b2005-01-13 20:14:25 +00005291 Value *PtrBase = GEPLHS->getOperand(0);
5292 if (PtrBase == RHS) {
Chris Lattner7c95deb2008-02-05 04:45:32 +00005293 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattner10c0d912008-04-22 02:53:33 +00005294 // This transformation (ignoring the base and scales) is valid because we
5295 // know pointers can't overflow. See if we can output an optimized form.
5296 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5297
5298 // If not, synthesize the offset the hard way.
5299 if (Offset == 0)
5300 Offset = EmitGEPOffset(GEPLHS, I, *this);
Chris Lattner7c95deb2008-02-05 04:45:32 +00005301 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
5302 Constant::getNullValue(Offset->getType()));
Chris Lattner574da9b2005-01-13 20:14:25 +00005303 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00005304 // If the base pointers are different, but the indices are the same, just
5305 // compare the base pointer.
5306 if (PtrBase != GEPRHS->getOperand(0)) {
5307 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00005308 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00005309 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00005310 if (IndicesTheSame)
5311 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5312 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5313 IndicesTheSame = false;
5314 break;
5315 }
5316
5317 // If all indices are the same, just compare the base pointers.
5318 if (IndicesTheSame)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005319 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
5320 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera70b66d2005-04-25 20:17:30 +00005321
5322 // Otherwise, the base pointers are different and the indices are
5323 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00005324 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00005325 }
Chris Lattner574da9b2005-01-13 20:14:25 +00005326
Chris Lattnere9d782b2005-01-13 22:25:21 +00005327 // If one of the GEPs has all zero indices, recurse.
5328 bool AllZeros = true;
5329 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5330 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5331 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5332 AllZeros = false;
5333 break;
5334 }
5335 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005336 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5337 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005338
5339 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00005340 AllZeros = true;
5341 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5342 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5343 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5344 AllZeros = false;
5345 break;
5346 }
5347 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005348 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005349
Chris Lattner4401c9c2005-01-14 00:20:05 +00005350 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5351 // If the GEPs only differ by one index, compare it.
5352 unsigned NumDifferences = 0; // Keep track of # differences.
5353 unsigned DiffOperand = 0; // The operand that differs.
5354 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5355 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00005356 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5357 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005358 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00005359 NumDifferences = 2;
5360 break;
5361 } else {
5362 if (NumDifferences++) break;
5363 DiffOperand = i;
5364 }
5365 }
5366
5367 if (NumDifferences == 0) // SAME GEP?
5368 return ReplaceInstUsesWith(I, // No comparison is needed here.
Nick Lewycky455e1762007-09-06 02:40:25 +00005369 ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005370 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky455e1762007-09-06 02:40:25 +00005371
Chris Lattner4401c9c2005-01-14 00:20:05 +00005372 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005373 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5374 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005375 // Make sure we do a signed comparison here.
5376 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005377 }
5378 }
5379
Reid Spencere4d87aa2006-12-23 06:05:41 +00005380 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00005381 // the result to fold to a constant!
5382 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5383 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5384 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
5385 Value *L = EmitGEPOffset(GEPLHS, I, *this);
5386 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005387 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner574da9b2005-01-13 20:14:25 +00005388 }
5389 }
5390 return 0;
5391}
5392
Chris Lattnera5406232008-05-19 20:18:56 +00005393/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5394///
5395Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5396 Instruction *LHSI,
5397 Constant *RHSC) {
5398 if (!isa<ConstantFP>(RHSC)) return 0;
5399 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5400
5401 // Get the width of the mantissa. We don't want to hack on conversions that
5402 // might lose information from the integer, e.g. "i64 -> float"
Chris Lattner7be1c452008-05-19 21:17:23 +00005403 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Chris Lattnera5406232008-05-19 20:18:56 +00005404 if (MantissaWidth == -1) return 0; // Unknown.
5405
5406 // Check to see that the input is converted from an integer type that is small
5407 // enough that preserves all bits. TODO: check here for "known" sign bits.
5408 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5409 unsigned InputSize = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
5410
5411 // If this is a uitofp instruction, we need an extra bit to hold the sign.
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005412 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5413 if (LHSUnsigned)
Chris Lattnera5406232008-05-19 20:18:56 +00005414 ++InputSize;
5415
5416 // If the conversion would lose info, don't hack on this.
5417 if ((int)InputSize > MantissaWidth)
5418 return 0;
5419
5420 // Otherwise, we can potentially simplify the comparison. We know that it
5421 // will always come through as an integer value and we know the constant is
5422 // not a NAN (it would have been previously simplified).
5423 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5424
5425 ICmpInst::Predicate Pred;
5426 switch (I.getPredicate()) {
5427 default: assert(0 && "Unexpected predicate!");
5428 case FCmpInst::FCMP_UEQ:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005429 case FCmpInst::FCMP_OEQ:
5430 Pred = ICmpInst::ICMP_EQ;
5431 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005432 case FCmpInst::FCMP_UGT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005433 case FCmpInst::FCMP_OGT:
5434 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5435 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005436 case FCmpInst::FCMP_UGE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005437 case FCmpInst::FCMP_OGE:
5438 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5439 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005440 case FCmpInst::FCMP_ULT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005441 case FCmpInst::FCMP_OLT:
5442 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5443 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005444 case FCmpInst::FCMP_ULE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005445 case FCmpInst::FCMP_OLE:
5446 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5447 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005448 case FCmpInst::FCMP_UNE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005449 case FCmpInst::FCMP_ONE:
5450 Pred = ICmpInst::ICMP_NE;
5451 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005452 case FCmpInst::FCMP_ORD:
Eli Friedman8b019c82008-11-30 22:48:49 +00005453 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnera5406232008-05-19 20:18:56 +00005454 case FCmpInst::FCMP_UNO:
Eli Friedman8b019c82008-11-30 22:48:49 +00005455 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattnera5406232008-05-19 20:18:56 +00005456 }
5457
5458 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5459
5460 // Now we know that the APFloat is a normal number, zero or inf.
5461
Chris Lattner85162782008-05-20 03:50:52 +00005462 // See if the FP constant is too large for the integer. For example,
Chris Lattnera5406232008-05-19 20:18:56 +00005463 // comparing an i8 to 300.0.
5464 unsigned IntWidth = IntTy->getPrimitiveSizeInBits();
5465
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005466 if (!LHSUnsigned) {
5467 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5468 // and large values.
5469 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5470 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5471 APFloat::rmNearestTiesToEven);
5472 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5473 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
5474 Pred == ICmpInst::ICMP_SLE)
Eli Friedman8b019c82008-11-30 22:48:49 +00005475 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5476 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005477 }
5478 } else {
5479 // If the RHS value is > UnsignedMax, fold the comparison. This handles
5480 // +INF and large values.
5481 APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5482 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5483 APFloat::rmNearestTiesToEven);
5484 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
5485 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
5486 Pred == ICmpInst::ICMP_ULE)
Eli Friedman8b019c82008-11-30 22:48:49 +00005487 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5488 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005489 }
Chris Lattnera5406232008-05-19 20:18:56 +00005490 }
5491
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005492 if (!LHSUnsigned) {
5493 // See if the RHS value is < SignedMin.
5494 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5495 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5496 APFloat::rmNearestTiesToEven);
5497 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5498 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5499 Pred == ICmpInst::ICMP_SGE)
Eli Friedman8b019c82008-11-30 22:48:49 +00005500 return ReplaceInstUsesWith(I,ConstantInt::getTrue());
5501 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005502 }
Chris Lattnera5406232008-05-19 20:18:56 +00005503 }
5504
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005505 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5506 // [0, UMAX], but it may still be fractional. See if it is fractional by
5507 // casting the FP value to the integer value and back, checking for equality.
5508 // Don't do this for zero, because -0.0 is not fractional.
Chris Lattnera5406232008-05-19 20:18:56 +00005509 Constant *RHSInt = ConstantExpr::getFPToSI(RHSC, IntTy);
5510 if (!RHS.isZero() &&
5511 ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) != RHSC) {
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005512 // If we had a comparison against a fractional value, we have to adjust the
5513 // compare predicate and sometimes the value. RHSC is rounded towards zero
5514 // at this point.
Chris Lattnera5406232008-05-19 20:18:56 +00005515 switch (Pred) {
5516 default: assert(0 && "Unexpected integer comparison!");
5517 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
Eli Friedman8b019c82008-11-30 22:48:49 +00005518 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnera5406232008-05-19 20:18:56 +00005519 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
Eli Friedman8b019c82008-11-30 22:48:49 +00005520 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005521 case ICmpInst::ICMP_ULE:
5522 // (float)int <= 4.4 --> int <= 4
5523 // (float)int <= -4.4 --> false
5524 if (RHS.isNegative())
Eli Friedman8b019c82008-11-30 22:48:49 +00005525 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005526 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005527 case ICmpInst::ICMP_SLE:
5528 // (float)int <= 4.4 --> int <= 4
5529 // (float)int <= -4.4 --> int < -4
5530 if (RHS.isNegative())
5531 Pred = ICmpInst::ICMP_SLT;
5532 break;
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005533 case ICmpInst::ICMP_ULT:
5534 // (float)int < -4.4 --> false
5535 // (float)int < 4.4 --> int <= 4
5536 if (RHS.isNegative())
Eli Friedman8b019c82008-11-30 22:48:49 +00005537 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005538 Pred = ICmpInst::ICMP_ULE;
5539 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005540 case ICmpInst::ICMP_SLT:
5541 // (float)int < -4.4 --> int < -4
5542 // (float)int < 4.4 --> int <= 4
5543 if (!RHS.isNegative())
5544 Pred = ICmpInst::ICMP_SLE;
5545 break;
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005546 case ICmpInst::ICMP_UGT:
5547 // (float)int > 4.4 --> int > 4
5548 // (float)int > -4.4 --> true
5549 if (RHS.isNegative())
Eli Friedman8b019c82008-11-30 22:48:49 +00005550 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005551 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005552 case ICmpInst::ICMP_SGT:
5553 // (float)int > 4.4 --> int > 4
5554 // (float)int > -4.4 --> int >= -4
5555 if (RHS.isNegative())
5556 Pred = ICmpInst::ICMP_SGE;
5557 break;
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005558 case ICmpInst::ICMP_UGE:
5559 // (float)int >= -4.4 --> true
5560 // (float)int >= 4.4 --> int > 4
5561 if (!RHS.isNegative())
Eli Friedman8b019c82008-11-30 22:48:49 +00005562 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005563 Pred = ICmpInst::ICMP_UGT;
5564 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005565 case ICmpInst::ICMP_SGE:
5566 // (float)int >= -4.4 --> int >= -4
5567 // (float)int >= 4.4 --> int > 4
5568 if (!RHS.isNegative())
5569 Pred = ICmpInst::ICMP_SGT;
5570 break;
5571 }
5572 }
5573
5574 // Lower this FP comparison into an appropriate integer version of the
5575 // comparison.
5576 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
5577}
5578
Reid Spencere4d87aa2006-12-23 06:05:41 +00005579Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5580 bool Changed = SimplifyCompare(I);
Chris Lattner8b170942002-08-09 23:47:40 +00005581 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005582
Chris Lattner58e97462007-01-14 19:42:17 +00005583 // Fold trivial predicates.
5584 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
Eli Friedman8b019c82008-11-30 22:48:49 +00005585 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattner58e97462007-01-14 19:42:17 +00005586 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
Eli Friedman8b019c82008-11-30 22:48:49 +00005587 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner58e97462007-01-14 19:42:17 +00005588
5589 // Simplify 'fcmp pred X, X'
5590 if (Op0 == Op1) {
5591 switch (I.getPredicate()) {
5592 default: assert(0 && "Unknown predicate!");
5593 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5594 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5595 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
Eli Friedman8b019c82008-11-30 22:48:49 +00005596 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner58e97462007-01-14 19:42:17 +00005597 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5598 case FCmpInst::FCMP_OLT: // True if ordered and less than
5599 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
Eli Friedman8b019c82008-11-30 22:48:49 +00005600 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattner58e97462007-01-14 19:42:17 +00005601
5602 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5603 case FCmpInst::FCMP_ULT: // True if unordered or less than
5604 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5605 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5606 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5607 I.setPredicate(FCmpInst::FCMP_UNO);
5608 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5609 return &I;
5610
5611 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5612 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5613 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5614 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5615 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5616 I.setPredicate(FCmpInst::FCMP_ORD);
5617 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5618 return &I;
5619 }
5620 }
5621
Reid Spencere4d87aa2006-12-23 06:05:41 +00005622 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Reid Spencer4fe16d62007-01-11 18:21:29 +00005623 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Chris Lattnere87597f2004-10-16 18:11:37 +00005624
Reid Spencere4d87aa2006-12-23 06:05:41 +00005625 // Handle fcmp with constant RHS
5626 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
Chris Lattnera5406232008-05-19 20:18:56 +00005627 // If the constant is a nan, see if we can fold the comparison based on it.
5628 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5629 if (CFP->getValueAPF().isNaN()) {
5630 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
Eli Friedman8b019c82008-11-30 22:48:49 +00005631 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattner85162782008-05-20 03:50:52 +00005632 assert(FCmpInst::isUnordered(I.getPredicate()) &&
5633 "Comparison must be either ordered or unordered!");
5634 // True if unordered.
Eli Friedman8b019c82008-11-30 22:48:49 +00005635 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnera5406232008-05-19 20:18:56 +00005636 }
5637 }
5638
Reid Spencere4d87aa2006-12-23 06:05:41 +00005639 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5640 switch (LHSI->getOpcode()) {
5641 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00005642 // Only fold fcmp into the PHI if the phi and fcmp are in the same
5643 // block. If in the same block, we're encouraging jump threading. If
5644 // not, we are just pessimizing the code by making an i1 phi.
5645 if (LHSI->getParent() == I.getParent())
5646 if (Instruction *NV = FoldOpIntoPhi(I))
5647 return NV;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005648 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005649 case Instruction::SIToFP:
5650 case Instruction::UIToFP:
5651 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5652 return NV;
5653 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005654 case Instruction::Select:
5655 // If either operand of the select is a constant, we can fold the
5656 // comparison into the select arms, which will cause one to be
5657 // constant folded and the select turned into a bitwise or.
5658 Value *Op1 = 0, *Op2 = 0;
5659 if (LHSI->hasOneUse()) {
5660 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5661 // Fold the known value into the constant operand.
5662 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5663 // Insert a new FCmp of the other select operand.
5664 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5665 LHSI->getOperand(2), RHSC,
5666 I.getName()), I);
5667 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5668 // Fold the known value into the constant operand.
5669 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5670 // Insert a new FCmp of the other select operand.
5671 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5672 LHSI->getOperand(1), RHSC,
5673 I.getName()), I);
5674 }
5675 }
5676
5677 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00005678 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005679 break;
5680 }
5681 }
5682
5683 return Changed ? &I : 0;
5684}
5685
5686Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5687 bool Changed = SimplifyCompare(I);
5688 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5689 const Type *Ty = Op0->getType();
5690
5691 // icmp X, X
5692 if (Op0 == Op1)
Reid Spencer579dca12007-01-12 04:24:46 +00005693 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005694 I.isTrueWhenEqual()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00005695
5696 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Reid Spencer4fe16d62007-01-11 18:21:29 +00005697 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Christopher Lamb7a0678c2007-12-18 21:32:20 +00005698
Reid Spencere4d87aa2006-12-23 06:05:41 +00005699 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner711b3402004-11-14 07:33:16 +00005700 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanfd939082005-04-21 23:48:37 +00005701 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5702 isa<ConstantPointerNull>(Op0)) &&
5703 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner711b3402004-11-14 07:33:16 +00005704 isa<ConstantPointerNull>(Op1)))
Reid Spencer579dca12007-01-12 04:24:46 +00005705 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005706 !I.isTrueWhenEqual()));
Chris Lattner8b170942002-08-09 23:47:40 +00005707
Reid Spencere4d87aa2006-12-23 06:05:41 +00005708 // icmp's with boolean values can always be turned into bitwise operations
Reid Spencer4fe16d62007-01-11 18:21:29 +00005709 if (Ty == Type::Int1Ty) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005710 switch (I.getPredicate()) {
5711 default: assert(0 && "Invalid icmp instruction!");
Chris Lattner85b5eb02008-07-11 04:20:58 +00005712 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005713 Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner8b170942002-08-09 23:47:40 +00005714 InsertNewInstBefore(Xor, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005715 return BinaryOperator::CreateNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00005716 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00005717 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005718 return BinaryOperator::CreateXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00005719
Reid Spencere4d87aa2006-12-23 06:05:41 +00005720 case ICmpInst::ICMP_UGT:
Chris Lattner85b5eb02008-07-11 04:20:58 +00005721 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
Chris Lattner5dbef222004-08-11 00:50:51 +00005722 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00005723 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005724 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Chris Lattner5dbef222004-08-11 00:50:51 +00005725 InsertNewInstBefore(Not, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005726 return BinaryOperator::CreateAnd(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00005727 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00005728 case ICmpInst::ICMP_SGT:
5729 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
Chris Lattner5dbef222004-08-11 00:50:51 +00005730 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00005731 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
5732 Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
5733 InsertNewInstBefore(Not, I);
5734 return BinaryOperator::CreateAnd(Not, Op0);
5735 }
5736 case ICmpInst::ICMP_UGE:
5737 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
5738 // FALL THROUGH
5739 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005740 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Chris Lattner5dbef222004-08-11 00:50:51 +00005741 InsertNewInstBefore(Not, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005742 return BinaryOperator::CreateOr(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00005743 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00005744 case ICmpInst::ICMP_SGE:
5745 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
5746 // FALL THROUGH
5747 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
5748 Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
5749 InsertNewInstBefore(Not, I);
5750 return BinaryOperator::CreateOr(Not, Op0);
5751 }
Chris Lattner5dbef222004-08-11 00:50:51 +00005752 }
Chris Lattner8b170942002-08-09 23:47:40 +00005753 }
5754
Dan Gohman81b28ce2008-09-16 18:46:06 +00005755 // See if we are doing a comparison with a constant.
Chris Lattner8b170942002-08-09 23:47:40 +00005756 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerf2991842008-07-11 04:09:09 +00005757 Value *A, *B;
Christopher Lamb103e1a32007-12-20 07:21:11 +00005758
Chris Lattnerb6566012008-01-05 01:18:20 +00005759 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5760 if (I.isEquality() && CI->isNullValue() &&
5761 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
5762 // (icmp cond A B) if cond is equality
5763 return new ICmpInst(I.getPredicate(), A, B);
Owen Andersonf5783f82007-12-28 07:42:12 +00005764 }
Christopher Lamb103e1a32007-12-20 07:21:11 +00005765
Dan Gohman81b28ce2008-09-16 18:46:06 +00005766 // If we have an icmp le or icmp ge instruction, turn it into the
5767 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
5768 // them being folded in the code below.
Chris Lattner84dff672008-07-11 05:08:55 +00005769 switch (I.getPredicate()) {
5770 default: break;
5771 case ICmpInst::ICMP_ULE:
5772 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
5773 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5774 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5775 case ICmpInst::ICMP_SLE:
5776 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
5777 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5778 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5779 case ICmpInst::ICMP_UGE:
5780 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
5781 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5782 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5783 case ICmpInst::ICMP_SGE:
5784 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
5785 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5786 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
5787 }
5788
Chris Lattner183661e2008-07-11 05:40:05 +00005789 // See if we can fold the comparison based on range information we can get
5790 // by checking whether bits are known to be zero or one in the input.
5791 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
5792 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
5793
5794 // If this comparison is a normal comparison, it demands all
Chris Lattner4241e4d2007-07-15 20:54:51 +00005795 // bits, if it is a sign bit comparison, it only demands the sign bit.
Chris Lattner4241e4d2007-07-15 20:54:51 +00005796 bool UnusedBit;
5797 bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5798
Chris Lattner886ab6c2009-01-31 08:15:18 +00005799 if (SimplifyDemandedBits(I.getOperandUse(0),
Chris Lattner4241e4d2007-07-15 20:54:51 +00005800 isSignBit ? APInt::getSignBit(BitWidth)
5801 : APInt::getAllOnesValue(BitWidth),
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005802 KnownZero, KnownOne, 0))
5803 return &I;
5804
5805 // Given the known and unknown bits, compute a range that the LHS could be
Chris Lattner84dff672008-07-11 05:08:55 +00005806 // in. Compute the Min, Max and RHS values based on the known bits. For the
5807 // EQ and NE we use unsigned values.
5808 APInt Min(BitWidth, 0), Max(BitWidth, 0);
Chris Lattner84dff672008-07-11 05:08:55 +00005809 if (ICmpInst::isSignedPredicate(I.getPredicate()))
5810 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min, Max);
5811 else
5812 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,Min,Max);
5813
Chris Lattner183661e2008-07-11 05:40:05 +00005814 // If Min and Max are known to be the same, then SimplifyDemandedBits
5815 // figured out that the LHS is a constant. Just constant fold this now so
5816 // that code below can assume that Min != Max.
5817 if (Min == Max)
5818 return ReplaceInstUsesWith(I, ConstantExpr::getICmp(I.getPredicate(),
5819 ConstantInt::get(Min),
5820 CI));
5821
5822 // Based on the range information we know about the LHS, see if we can
5823 // simplify this comparison. For example, (x&4) < 8 is always true.
5824 const APInt &RHSVal = CI->getValue();
Chris Lattner84dff672008-07-11 05:08:55 +00005825 switch (I.getPredicate()) { // LE/GE have been folded already.
5826 default: assert(0 && "Unknown icmp opcode!");
5827 case ICmpInst::ICMP_EQ:
5828 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5829 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5830 break;
5831 case ICmpInst::ICMP_NE:
5832 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5833 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5834 break;
5835 case ICmpInst::ICMP_ULT:
Chris Lattner183661e2008-07-11 05:40:05 +00005836 if (Max.ult(RHSVal)) // A <u C -> true iff max(A) < C
Chris Lattner84dff672008-07-11 05:08:55 +00005837 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner183661e2008-07-11 05:40:05 +00005838 if (Min.uge(RHSVal)) // A <u C -> false iff min(A) >= C
Chris Lattner84dff672008-07-11 05:08:55 +00005839 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattner183661e2008-07-11 05:40:05 +00005840 if (RHSVal == Max) // A <u MAX -> A != MAX
5841 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5842 if (RHSVal == Min+1) // A <u MIN+1 -> A == MIN
5843 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5844
5845 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
5846 if (CI->isMinValue(true))
5847 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
5848 ConstantInt::getAllOnesValue(Op0->getType()));
Chris Lattner84dff672008-07-11 05:08:55 +00005849 break;
5850 case ICmpInst::ICMP_UGT:
Chris Lattner183661e2008-07-11 05:40:05 +00005851 if (Min.ugt(RHSVal)) // A >u C -> true iff min(A) > C
Chris Lattner84dff672008-07-11 05:08:55 +00005852 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner183661e2008-07-11 05:40:05 +00005853 if (Max.ule(RHSVal)) // A >u C -> false iff max(A) <= C
Chris Lattner84dff672008-07-11 05:08:55 +00005854 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattner183661e2008-07-11 05:40:05 +00005855
5856 if (RHSVal == Min) // A >u MIN -> A != MIN
5857 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5858 if (RHSVal == Max-1) // A >u MAX-1 -> A == MAX
5859 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5860
5861 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
5862 if (CI->isMaxValue(true))
5863 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
5864 ConstantInt::getNullValue(Op0->getType()));
Chris Lattner84dff672008-07-11 05:08:55 +00005865 break;
5866 case ICmpInst::ICMP_SLT:
Chris Lattner183661e2008-07-11 05:40:05 +00005867 if (Max.slt(RHSVal)) // A <s C -> true iff max(A) < C
Chris Lattner84dff672008-07-11 05:08:55 +00005868 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnerd01bee72008-07-11 06:40:29 +00005869 if (Min.sge(RHSVal)) // A <s C -> false iff min(A) >= C
Chris Lattner84dff672008-07-11 05:08:55 +00005870 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattner183661e2008-07-11 05:40:05 +00005871 if (RHSVal == Max) // A <s MAX -> A != MAX
5872 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Chris Lattnera8ff4a82008-07-11 06:36:01 +00005873 if (RHSVal == Min+1) // A <s MIN+1 -> A == MIN
Chris Lattnerf9685ac2008-07-11 06:38:16 +00005874 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00005875 break;
5876 case ICmpInst::ICMP_SGT:
Chris Lattner183661e2008-07-11 05:40:05 +00005877 if (Min.sgt(RHSVal)) // A >s C -> true iff min(A) > C
Chris Lattner84dff672008-07-11 05:08:55 +00005878 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner183661e2008-07-11 05:40:05 +00005879 if (Max.sle(RHSVal)) // A >s C -> false iff max(A) <= C
Chris Lattner84dff672008-07-11 05:08:55 +00005880 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattner183661e2008-07-11 05:40:05 +00005881
5882 if (RHSVal == Min) // A >s MIN -> A != MIN
5883 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5884 if (RHSVal == Max-1) // A >s MAX-1 -> A == MAX
5885 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00005886 break;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005887 }
Dan Gohman81b28ce2008-09-16 18:46:06 +00005888 }
5889
5890 // Test if the ICmpInst instruction is used exclusively by a select as
5891 // part of a minimum or maximum operation. If so, refrain from doing
5892 // any other folding. This helps out other analyses which understand
5893 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
5894 // and CodeGen. And in this case, at least one of the comparison
5895 // operands has at least one user besides the compare (the select),
5896 // which would often largely negate the benefit of folding anyway.
5897 if (I.hasOneUse())
5898 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
5899 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
5900 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
5901 return 0;
5902
5903 // See if we are doing a comparison between a constant and an instruction that
5904 // can be folded into the comparison.
5905 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005906 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer1628cec2006-10-26 06:15:43 +00005907 // instruction, see if that instruction also has constants so that the
Reid Spencere4d87aa2006-12-23 06:05:41 +00005908 // instruction can be folded into the icmp
Chris Lattner3c6a0d42004-05-25 06:32:08 +00005909 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner01deb9d2007-04-03 17:43:25 +00005910 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
5911 return Res;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005912 }
5913
Chris Lattner01deb9d2007-04-03 17:43:25 +00005914 // Handle icmp with constant (but not simple integer constant) RHS
Chris Lattner6970b662005-04-23 15:31:55 +00005915 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5916 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5917 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00005918 case Instruction::GetElementPtr:
5919 if (RHSC->isNullValue()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005920 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattner9fb25db2005-05-01 04:42:15 +00005921 bool isAllZeros = true;
5922 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5923 if (!isa<Constant>(LHSI->getOperand(i)) ||
5924 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5925 isAllZeros = false;
5926 break;
5927 }
5928 if (isAllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005929 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Chris Lattner9fb25db2005-05-01 04:42:15 +00005930 Constant::getNullValue(LHSI->getOperand(0)->getType()));
5931 }
5932 break;
5933
Chris Lattner6970b662005-04-23 15:31:55 +00005934 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00005935 // Only fold icmp into the PHI if the phi and fcmp are in the same
5936 // block. If in the same block, we're encouraging jump threading. If
5937 // not, we are just pessimizing the code by making an i1 phi.
5938 if (LHSI->getParent() == I.getParent())
5939 if (Instruction *NV = FoldOpIntoPhi(I))
5940 return NV;
Chris Lattner6970b662005-04-23 15:31:55 +00005941 break;
Chris Lattner4802d902007-04-06 18:57:34 +00005942 case Instruction::Select: {
Chris Lattner6970b662005-04-23 15:31:55 +00005943 // If either operand of the select is a constant, we can fold the
5944 // comparison into the select arms, which will cause one to be
5945 // constant folded and the select turned into a bitwise or.
5946 Value *Op1 = 0, *Op2 = 0;
5947 if (LHSI->hasOneUse()) {
5948 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5949 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005950 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5951 // Insert a new ICmp of the other select operand.
5952 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5953 LHSI->getOperand(2), RHSC,
5954 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00005955 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5956 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005957 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5958 // Insert a new ICmp of the other select operand.
5959 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5960 LHSI->getOperand(1), RHSC,
5961 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00005962 }
5963 }
Jeff Cohen9d809302005-04-23 21:38:35 +00005964
Chris Lattner6970b662005-04-23 15:31:55 +00005965 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00005966 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Chris Lattner6970b662005-04-23 15:31:55 +00005967 break;
5968 }
Chris Lattner4802d902007-04-06 18:57:34 +00005969 case Instruction::Malloc:
5970 // If we have (malloc != null), and if the malloc has a single use, we
5971 // can assume it is successful and remove the malloc.
5972 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
5973 AddToWorkList(LHSI);
5974 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005975 !I.isTrueWhenEqual()));
Chris Lattner4802d902007-04-06 18:57:34 +00005976 }
5977 break;
5978 }
Chris Lattner6970b662005-04-23 15:31:55 +00005979 }
5980
Reid Spencere4d87aa2006-12-23 06:05:41 +00005981 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Chris Lattner574da9b2005-01-13 20:14:25 +00005982 if (User *GEP = dyn_castGetElementPtr(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005983 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00005984 return NI;
5985 if (User *GEP = dyn_castGetElementPtr(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005986 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5987 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00005988 return NI;
5989
Reid Spencere4d87aa2006-12-23 06:05:41 +00005990 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner57d86372007-01-06 01:45:59 +00005991 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
5992 // now.
5993 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5994 if (isa<PointerType>(Op0->getType()) &&
5995 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattnerde90b762003-11-03 04:25:02 +00005996 // We keep moving the cast from the left operand over to the right
5997 // operand, where it can often be eliminated completely.
Chris Lattner57d86372007-01-06 01:45:59 +00005998 Op0 = CI->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00005999
Chris Lattner57d86372007-01-06 01:45:59 +00006000 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6001 // so eliminate it as well.
6002 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6003 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006004
Chris Lattnerde90b762003-11-03 04:25:02 +00006005 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006006 if (Op0->getType() != Op1->getType()) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006007 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Reid Spencerd977d862006-12-12 23:36:14 +00006008 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00006009 } else {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006010 // Otherwise, cast the RHS right before the icmp
Chris Lattner6d0339d2008-01-13 22:23:22 +00006011 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
Chris Lattnerde90b762003-11-03 04:25:02 +00006012 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006013 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00006014 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattnerde90b762003-11-03 04:25:02 +00006015 }
Chris Lattner57d86372007-01-06 01:45:59 +00006016 }
6017
6018 if (isa<CastInst>(Op0)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006019 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner68708052003-11-03 05:17:03 +00006020 // This comes up when you have code like
6021 // int X = A < B;
6022 // if (X) ...
6023 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00006024 // with a constant or another cast from the same type.
6025 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006026 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattner484d3cf2005-04-24 06:59:08 +00006027 return R;
Chris Lattner68708052003-11-03 05:17:03 +00006028 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006029
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006030 // See if it's the same type of instruction on the left and right.
6031 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6032 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Nick Lewycky5d52c452008-08-21 05:56:10 +00006033 if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
6034 Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1) &&
6035 I.isEquality()) {
Nick Lewycky23c04302008-09-03 06:24:21 +00006036 switch (Op0I->getOpcode()) {
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006037 default: break;
6038 case Instruction::Add:
6039 case Instruction::Sub:
6040 case Instruction::Xor:
Nick Lewycky5d52c452008-08-21 05:56:10 +00006041 // a+x icmp eq/ne b+x --> a icmp b
6042 return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
6043 Op1I->getOperand(0));
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006044 break;
6045 case Instruction::Mul:
Nick Lewycky5d52c452008-08-21 05:56:10 +00006046 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6047 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6048 // Mask = -1 >> count-trailing-zeros(Cst).
6049 if (!CI->isZero() && !CI->isOne()) {
6050 const APInt &AP = CI->getValue();
6051 ConstantInt *Mask = ConstantInt::get(
6052 APInt::getLowBitsSet(AP.getBitWidth(),
6053 AP.getBitWidth() -
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006054 AP.countTrailingZeros()));
Nick Lewycky5d52c452008-08-21 05:56:10 +00006055 Instruction *And1 = BinaryOperator::CreateAnd(Op0I->getOperand(0),
6056 Mask);
6057 Instruction *And2 = BinaryOperator::CreateAnd(Op1I->getOperand(0),
6058 Mask);
6059 InsertNewInstBefore(And1, I);
6060 InsertNewInstBefore(And2, I);
6061 return new ICmpInst(I.getPredicate(), And1, And2);
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006062 }
6063 }
6064 break;
6065 }
6066 }
6067 }
6068 }
6069
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006070 // ~x < ~y --> y < x
6071 { Value *A, *B;
6072 if (match(Op0, m_Not(m_Value(A))) &&
6073 match(Op1, m_Not(m_Value(B))))
6074 return new ICmpInst(I.getPredicate(), B, A);
6075 }
6076
Chris Lattner65b72ba2006-09-18 04:22:48 +00006077 if (I.isEquality()) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006078 Value *A, *B, *C, *D;
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006079
6080 // -x == -y --> x == y
6081 if (match(Op0, m_Neg(m_Value(A))) &&
6082 match(Op1, m_Neg(m_Value(B))))
6083 return new ICmpInst(I.getPredicate(), A, B);
6084
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006085 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
6086 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6087 Value *OtherVal = A == Op1 ? B : A;
6088 return new ICmpInst(I.getPredicate(), OtherVal,
6089 Constant::getNullValue(A->getType()));
6090 }
6091
6092 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
6093 // A^c1 == C^c2 --> A == C^(c1^c2)
Chris Lattnercb504b92008-11-16 05:38:51 +00006094 ConstantInt *C1, *C2;
6095 if (match(B, m_ConstantInt(C1)) &&
6096 match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
6097 Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
6098 Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
6099 return new ICmpInst(I.getPredicate(), A,
6100 InsertNewInstBefore(Xor, I));
6101 }
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006102
6103 // A^B == A^D -> B == D
6104 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6105 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6106 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6107 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
6108 }
6109 }
6110
6111 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
6112 (A == Op0 || B == Op0)) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00006113 // A == (A^B) -> B == 0
6114 Value *OtherVal = A == Op0 ? B : A;
Reid Spencere4d87aa2006-12-23 06:05:41 +00006115 return new ICmpInst(I.getPredicate(), OtherVal,
6116 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006117 }
Chris Lattnercb504b92008-11-16 05:38:51 +00006118
6119 // (A-B) == A -> B == 0
6120 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
6121 return new ICmpInst(I.getPredicate(), B,
6122 Constant::getNullValue(B->getType()));
6123
6124 // A == (A-B) -> B == 0
6125 if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006126 return new ICmpInst(I.getPredicate(), B,
6127 Constant::getNullValue(B->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006128
Chris Lattner9c2328e2006-11-14 06:06:06 +00006129 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6130 if (Op0->hasOneUse() && Op1->hasOneUse() &&
6131 match(Op0, m_And(m_Value(A), m_Value(B))) &&
6132 match(Op1, m_And(m_Value(C), m_Value(D)))) {
6133 Value *X = 0, *Y = 0, *Z = 0;
6134
6135 if (A == C) {
6136 X = B; Y = D; Z = A;
6137 } else if (A == D) {
6138 X = B; Y = C; Z = A;
6139 } else if (B == C) {
6140 X = A; Y = D; Z = B;
6141 } else if (B == D) {
6142 X = A; Y = C; Z = B;
6143 }
6144
6145 if (X) { // Build (X^Y) & Z
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006146 Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
6147 Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
Chris Lattner9c2328e2006-11-14 06:06:06 +00006148 I.setOperand(0, Op1);
6149 I.setOperand(1, Constant::getNullValue(Op1->getType()));
6150 return &I;
6151 }
6152 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006153 }
Chris Lattner7e708292002-06-25 16:13:24 +00006154 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006155}
6156
Chris Lattner562ef782007-06-20 23:46:26 +00006157
6158/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6159/// and CmpRHS are both known to be integer constants.
6160Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6161 ConstantInt *DivRHS) {
6162 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6163 const APInt &CmpRHSV = CmpRHS->getValue();
6164
6165 // FIXME: If the operand types don't match the type of the divide
6166 // then don't attempt this transform. The code below doesn't have the
6167 // logic to deal with a signed divide and an unsigned compare (and
6168 // vice versa). This is because (x /s C1) <s C2 produces different
6169 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6170 // (x /u C1) <u C2. Simply casting the operands and result won't
6171 // work. :( The if statement below tests that condition and bails
6172 // if it finds it.
6173 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6174 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6175 return 0;
6176 if (DivRHS->isZero())
Chris Lattner1dbfd482007-06-21 18:11:19 +00006177 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattnera6321b42008-10-11 22:55:00 +00006178 if (DivIsSigned && DivRHS->isAllOnesValue())
6179 return 0; // The overflow computation also screws up here
6180 if (DivRHS->isOne())
6181 return 0; // Not worth bothering, and eliminates some funny cases
6182 // with INT_MIN.
Chris Lattner562ef782007-06-20 23:46:26 +00006183
6184 // Compute Prod = CI * DivRHS. We are essentially solving an equation
6185 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
6186 // C2 (CI). By solving for X we can turn this into a range check
6187 // instead of computing a divide.
6188 ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
6189
6190 // Determine if the product overflows by seeing if the product is
6191 // not equal to the divide. Make sure we do the same kind of divide
6192 // as in the LHS instruction that we're folding.
6193 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6194 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
6195
6196 // Get the ICmp opcode
Chris Lattner1dbfd482007-06-21 18:11:19 +00006197 ICmpInst::Predicate Pred = ICI.getPredicate();
Chris Lattner562ef782007-06-20 23:46:26 +00006198
Chris Lattner1dbfd482007-06-21 18:11:19 +00006199 // Figure out the interval that is being checked. For example, a comparison
6200 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
6201 // Compute this interval based on the constants involved and the signedness of
6202 // the compare/divide. This computes a half-open interval, keeping track of
6203 // whether either value in the interval overflows. After analysis each
6204 // overflow variable is set to 0 if it's corresponding bound variable is valid
6205 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6206 int LoOverflow = 0, HiOverflow = 0;
6207 ConstantInt *LoBound = 0, *HiBound = 0;
6208
Chris Lattner562ef782007-06-20 23:46:26 +00006209 if (!DivIsSigned) { // udiv
Chris Lattner1dbfd482007-06-21 18:11:19 +00006210 // e.g. X/5 op 3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00006211 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006212 HiOverflow = LoOverflow = ProdOV;
6213 if (!HiOverflow)
6214 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
Dan Gohman76491272008-02-13 22:09:18 +00006215 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006216 if (CmpRHSV == 0) { // (X / pos) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006217 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Chris Lattner562ef782007-06-20 23:46:26 +00006218 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
6219 HiBound = DivRHS;
Dan Gohman76491272008-02-13 22:09:18 +00006220 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006221 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
6222 HiOverflow = LoOverflow = ProdOV;
6223 if (!HiOverflow)
6224 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006225 } else { // (X / pos) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00006226 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Chris Lattner562ef782007-06-20 23:46:26 +00006227 HiBound = AddOne(Prod);
Chris Lattnera6321b42008-10-11 22:55:00 +00006228 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6229 if (!LoOverflow) {
6230 ConstantInt* DivNeg = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6231 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg,
6232 true) ? -1 : 0;
6233 }
Chris Lattner562ef782007-06-20 23:46:26 +00006234 }
Dan Gohman76491272008-02-13 22:09:18 +00006235 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006236 if (CmpRHSV == 0) { // (X / neg) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006237 // e.g. X/-5 op 0 --> [-4, 5)
Chris Lattner562ef782007-06-20 23:46:26 +00006238 LoBound = AddOne(DivRHS);
6239 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006240 if (HiBound == DivRHS) { // -INTMIN = INTMIN
6241 HiOverflow = 1; // [INTMIN+1, overflow)
6242 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
6243 }
Dan Gohman76491272008-02-13 22:09:18 +00006244 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006245 // e.g. X/-5 op 3 --> [-19, -14)
Chris Lattnera6321b42008-10-11 22:55:00 +00006246 HiBound = AddOne(Prod);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006247 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006248 if (!LoOverflow)
Chris Lattnera6321b42008-10-11 22:55:00 +00006249 LoOverflow = AddWithOverflow(LoBound, HiBound, DivRHS, true) ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006250 } else { // (X / neg) op neg
Chris Lattnera6321b42008-10-11 22:55:00 +00006251 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
6252 LoOverflow = HiOverflow = ProdOV;
Dan Gohman7f85fbd2008-09-11 00:25:00 +00006253 if (!HiOverflow)
6254 HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006255 }
6256
Chris Lattner1dbfd482007-06-21 18:11:19 +00006257 // Dividing by a negative swaps the condition. LT <-> GT
6258 Pred = ICmpInst::getSwappedPredicate(Pred);
Chris Lattner562ef782007-06-20 23:46:26 +00006259 }
6260
6261 Value *X = DivI->getOperand(0);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006262 switch (Pred) {
Chris Lattner562ef782007-06-20 23:46:26 +00006263 default: assert(0 && "Unhandled icmp opcode!");
6264 case ICmpInst::ICMP_EQ:
6265 if (LoOverflow && HiOverflow)
6266 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6267 else if (HiOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00006268 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006269 ICmpInst::ICMP_UGE, X, LoBound);
6270 else if (LoOverflow)
6271 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
6272 ICmpInst::ICMP_ULT, X, HiBound);
6273 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006274 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006275 case ICmpInst::ICMP_NE:
6276 if (LoOverflow && HiOverflow)
6277 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6278 else if (HiOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00006279 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006280 ICmpInst::ICMP_ULT, X, LoBound);
6281 else if (LoOverflow)
6282 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
6283 ICmpInst::ICMP_UGE, X, HiBound);
6284 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006285 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006286 case ICmpInst::ICMP_ULT:
6287 case ICmpInst::ICMP_SLT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006288 if (LoOverflow == +1) // Low bound is greater than input range.
6289 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6290 if (LoOverflow == -1) // Low bound is less than input range.
Chris Lattner562ef782007-06-20 23:46:26 +00006291 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00006292 return new ICmpInst(Pred, X, LoBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006293 case ICmpInst::ICMP_UGT:
6294 case ICmpInst::ICMP_SGT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006295 if (HiOverflow == +1) // High bound greater than input range.
Chris Lattner562ef782007-06-20 23:46:26 +00006296 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00006297 else if (HiOverflow == -1) // High bound less than input range.
6298 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6299 if (Pred == ICmpInst::ICMP_UGT)
Chris Lattner562ef782007-06-20 23:46:26 +00006300 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
6301 else
6302 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
6303 }
6304}
6305
6306
Chris Lattner01deb9d2007-04-03 17:43:25 +00006307/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6308///
6309Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6310 Instruction *LHSI,
6311 ConstantInt *RHS) {
6312 const APInt &RHSV = RHS->getValue();
6313
6314 switch (LHSI->getOpcode()) {
Chris Lattnera80d6682009-01-09 07:47:06 +00006315 case Instruction::Trunc:
6316 if (ICI.isEquality() && LHSI->hasOneUse()) {
6317 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6318 // of the high bits truncated out of x are known.
6319 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6320 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6321 APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6322 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6323 ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6324
6325 // If all the high bits are known, we can do this xform.
6326 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6327 // Pull in the high bits from known-ones set.
6328 APInt NewRHS(RHS->getValue());
6329 NewRHS.zext(SrcBits);
6330 NewRHS |= KnownOne;
6331 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6332 ConstantInt::get(NewRHS));
6333 }
6334 }
6335 break;
6336
Duncan Sands0091bf22007-04-04 06:42:45 +00006337 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
Chris Lattner01deb9d2007-04-03 17:43:25 +00006338 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6339 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6340 // fold the xor.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006341 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6342 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006343 Value *CompareVal = LHSI->getOperand(0);
6344
6345 // If the sign bit of the XorCST is not set, there is no change to
6346 // the operation, just stop using the Xor.
6347 if (!XorCST->getValue().isNegative()) {
6348 ICI.setOperand(0, CompareVal);
6349 AddToWorkList(LHSI);
6350 return &ICI;
6351 }
6352
6353 // Was the old condition true if the operand is positive?
6354 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6355
6356 // If so, the new one isn't.
6357 isTrueIfPositive ^= true;
6358
6359 if (isTrueIfPositive)
6360 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
6361 else
6362 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
6363 }
6364 }
6365 break;
6366 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
6367 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6368 LHSI->getOperand(0)->hasOneUse()) {
6369 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6370
6371 // If the LHS is an AND of a truncating cast, we can widen the
6372 // and/compare to be the input width without changing the value
6373 // produced, eliminating a cast.
6374 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6375 // We can do this transformation if either the AND constant does not
6376 // have its sign bit set or if it is an equality comparison.
6377 // Extending a relational comparison when we're checking the sign
6378 // bit would not work.
6379 if (Cast->hasOneUse() &&
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00006380 (ICI.isEquality() ||
6381 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006382 uint32_t BitWidth =
6383 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6384 APInt NewCST = AndCST->getValue();
6385 NewCST.zext(BitWidth);
6386 APInt NewCI = RHSV;
6387 NewCI.zext(BitWidth);
6388 Instruction *NewAnd =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006389 BinaryOperator::CreateAnd(Cast->getOperand(0),
Chris Lattner01deb9d2007-04-03 17:43:25 +00006390 ConstantInt::get(NewCST),LHSI->getName());
6391 InsertNewInstBefore(NewAnd, ICI);
6392 return new ICmpInst(ICI.getPredicate(), NewAnd,
6393 ConstantInt::get(NewCI));
6394 }
6395 }
6396
6397 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6398 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
6399 // happens a LOT in code produced by the C front-end, for bitfield
6400 // access.
6401 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6402 if (Shift && !Shift->isShift())
6403 Shift = 0;
6404
6405 ConstantInt *ShAmt;
6406 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6407 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
6408 const Type *AndTy = AndCST->getType(); // Type of the and.
6409
6410 // We can fold this as long as we can't shift unknown bits
6411 // into the mask. This can only happen with signed shift
6412 // rights, as they sign-extend.
6413 if (ShAmt) {
6414 bool CanFold = Shift->isLogicalShift();
6415 if (!CanFold) {
6416 // To test for the bad case of the signed shr, see if any
6417 // of the bits shifted in could be tested after the mask.
6418 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6419 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6420
6421 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6422 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
6423 AndCST->getValue()) == 0)
6424 CanFold = true;
6425 }
6426
6427 if (CanFold) {
6428 Constant *NewCst;
6429 if (Shift->getOpcode() == Instruction::Shl)
6430 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
6431 else
6432 NewCst = ConstantExpr::getShl(RHS, ShAmt);
6433
6434 // Check to see if we are shifting out any of the bits being
6435 // compared.
6436 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
6437 // If we shifted bits out, the fold is not going to work out.
6438 // As a special case, check to see if this means that the
6439 // result is always true or false now.
6440 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6441 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6442 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6443 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6444 } else {
6445 ICI.setOperand(1, NewCst);
6446 Constant *NewAndCST;
6447 if (Shift->getOpcode() == Instruction::Shl)
6448 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
6449 else
6450 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
6451 LHSI->setOperand(1, NewAndCST);
6452 LHSI->setOperand(0, Shift->getOperand(0));
6453 AddToWorkList(Shift); // Shift is dead.
6454 AddUsesToWorkList(ICI);
6455 return &ICI;
6456 }
6457 }
6458 }
6459
6460 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
6461 // preferable because it allows the C<<Y expression to be hoisted out
6462 // of a loop if Y is invariant and X is not.
6463 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
6464 ICI.isEquality() && !Shift->isArithmeticShift() &&
6465 isa<Instruction>(Shift->getOperand(0))) {
6466 // Compute C << Y.
6467 Value *NS;
6468 if (Shift->getOpcode() == Instruction::LShr) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006469 NS = BinaryOperator::CreateShl(AndCST,
Chris Lattner01deb9d2007-04-03 17:43:25 +00006470 Shift->getOperand(1), "tmp");
6471 } else {
6472 // Insert a logical shift.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006473 NS = BinaryOperator::CreateLShr(AndCST,
Chris Lattner01deb9d2007-04-03 17:43:25 +00006474 Shift->getOperand(1), "tmp");
6475 }
6476 InsertNewInstBefore(cast<Instruction>(NS), ICI);
6477
6478 // Compute X & (C << Y).
6479 Instruction *NewAnd =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006480 BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006481 InsertNewInstBefore(NewAnd, ICI);
6482
6483 ICI.setOperand(0, NewAnd);
6484 return &ICI;
6485 }
6486 }
6487 break;
6488
Chris Lattnera0141b92007-07-15 20:42:37 +00006489 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6490 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6491 if (!ShAmt) break;
6492
6493 uint32_t TypeBits = RHSV.getBitWidth();
6494
6495 // Check that the shift amount is in range. If not, don't perform
6496 // undefined shifts. When the shift is visited it will be
6497 // simplified.
6498 if (ShAmt->uge(TypeBits))
6499 break;
6500
6501 if (ICI.isEquality()) {
6502 // If we are comparing against bits always shifted out, the
6503 // comparison cannot succeed.
6504 Constant *Comp =
6505 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
6506 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6507 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6508 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6509 return ReplaceInstUsesWith(ICI, Cst);
6510 }
6511
6512 if (LHSI->hasOneUse()) {
6513 // Otherwise strength reduce the shift into an and.
6514 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6515 Constant *Mask =
6516 ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006517
Chris Lattnera0141b92007-07-15 20:42:37 +00006518 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006519 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattnera0141b92007-07-15 20:42:37 +00006520 Mask, LHSI->getName()+".mask");
6521 Value *And = InsertNewInstBefore(AndI, ICI);
6522 return new ICmpInst(ICI.getPredicate(), And,
6523 ConstantInt::get(RHSV.lshr(ShAmtVal)));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006524 }
6525 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006526
6527 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6528 bool TrueIfSigned = false;
6529 if (LHSI->hasOneUse() &&
6530 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6531 // (X << 31) <s 0 --> (X&1) != 0
6532 Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
6533 (TypeBits-ShAmt->getZExtValue()-1));
6534 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006535 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattnera0141b92007-07-15 20:42:37 +00006536 Mask, LHSI->getName()+".mask");
6537 Value *And = InsertNewInstBefore(AndI, ICI);
6538
6539 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6540 And, Constant::getNullValue(And->getType()));
6541 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006542 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006543 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006544
6545 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Chris Lattnera0141b92007-07-15 20:42:37 +00006546 case Instruction::AShr: {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006547 // Only handle equality comparisons of shift-by-constant.
Chris Lattnera0141b92007-07-15 20:42:37 +00006548 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006549 if (!ShAmt || !ICI.isEquality()) break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006550
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006551 // Check that the shift amount is in range. If not, don't perform
6552 // undefined shifts. When the shift is visited it will be
6553 // simplified.
6554 uint32_t TypeBits = RHSV.getBitWidth();
6555 if (ShAmt->uge(TypeBits))
6556 break;
6557
6558 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattnera0141b92007-07-15 20:42:37 +00006559
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006560 // If we are comparing against bits always shifted out, the
6561 // comparison cannot succeed.
6562 APInt Comp = RHSV << ShAmtVal;
6563 if (LHSI->getOpcode() == Instruction::LShr)
6564 Comp = Comp.lshr(ShAmtVal);
6565 else
6566 Comp = Comp.ashr(ShAmtVal);
6567
6568 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6569 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6570 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6571 return ReplaceInstUsesWith(ICI, Cst);
6572 }
6573
6574 // Otherwise, check to see if the bits shifted out are known to be zero.
6575 // If so, we can compare against the unshifted value:
6576 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengf30752c2008-04-23 00:38:06 +00006577 if (LHSI->hasOneUse() &&
6578 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006579 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
6580 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6581 ConstantExpr::getShl(RHS, ShAmt));
6582 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006583
Evan Chengf30752c2008-04-23 00:38:06 +00006584 if (LHSI->hasOneUse()) {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006585 // Otherwise strength reduce the shift into an and.
6586 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
6587 Constant *Mask = ConstantInt::get(Val);
Chris Lattnera0141b92007-07-15 20:42:37 +00006588
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006589 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006590 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006591 Mask, LHSI->getName()+".mask");
6592 Value *And = InsertNewInstBefore(AndI, ICI);
6593 return new ICmpInst(ICI.getPredicate(), And,
6594 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006595 }
6596 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006597 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006598
6599 case Instruction::SDiv:
6600 case Instruction::UDiv:
6601 // Fold: icmp pred ([us]div X, C1), C2 -> range test
6602 // Fold this div into the comparison, producing a range check.
6603 // Determine, based on the divide type, what the range is being
6604 // checked. If there is an overflow on the low or high side, remember
6605 // it, otherwise compute the range [low, hi) bounding the new value.
6606 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner562ef782007-06-20 23:46:26 +00006607 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6608 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6609 DivRHS))
6610 return R;
Chris Lattner01deb9d2007-04-03 17:43:25 +00006611 break;
Nick Lewycky5be29202008-02-03 16:33:09 +00006612
6613 case Instruction::Add:
6614 // Fold: icmp pred (add, X, C1), C2
6615
6616 if (!ICI.isEquality()) {
6617 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6618 if (!LHSC) break;
6619 const APInt &LHSV = LHSC->getValue();
6620
6621 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6622 .subtract(LHSV);
6623
6624 if (ICI.isSignedPredicate()) {
6625 if (CR.getLower().isSignBit()) {
6626 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
6627 ConstantInt::get(CR.getUpper()));
6628 } else if (CR.getUpper().isSignBit()) {
6629 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
6630 ConstantInt::get(CR.getLower()));
6631 }
6632 } else {
6633 if (CR.getLower().isMinValue()) {
6634 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
6635 ConstantInt::get(CR.getUpper()));
6636 } else if (CR.getUpper().isMinValue()) {
6637 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
6638 ConstantInt::get(CR.getLower()));
6639 }
6640 }
6641 }
6642 break;
Chris Lattner01deb9d2007-04-03 17:43:25 +00006643 }
6644
6645 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6646 if (ICI.isEquality()) {
6647 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6648
6649 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
6650 // the second operand is a constant, simplify a bit.
6651 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6652 switch (BO->getOpcode()) {
6653 case Instruction::SRem:
6654 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6655 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6656 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6657 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
6658 Instruction *NewRem =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006659 BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
Chris Lattner01deb9d2007-04-03 17:43:25 +00006660 BO->getName());
6661 InsertNewInstBefore(NewRem, ICI);
6662 return new ICmpInst(ICI.getPredicate(), NewRem,
6663 Constant::getNullValue(BO->getType()));
6664 }
6665 }
6666 break;
6667 case Instruction::Add:
6668 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
6669 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6670 if (BO->hasOneUse())
6671 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6672 Subtract(RHS, BOp1C));
6673 } else if (RHSV == 0) {
6674 // Replace ((add A, B) != 0) with (A != -B) if A or B is
6675 // efficiently invertible, or if the add has just this one use.
6676 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
6677
6678 if (Value *NegVal = dyn_castNegVal(BOp1))
6679 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
6680 else if (Value *NegVal = dyn_castNegVal(BOp0))
6681 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
6682 else if (BO->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006683 Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006684 InsertNewInstBefore(Neg, ICI);
6685 Neg->takeName(BO);
6686 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
6687 }
6688 }
6689 break;
6690 case Instruction::Xor:
6691 // For the xor case, we can xor two constants together, eliminating
6692 // the explicit xor.
6693 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
6694 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6695 ConstantExpr::getXor(RHS, BOC));
6696
6697 // FALLTHROUGH
6698 case Instruction::Sub:
6699 // Replace (([sub|xor] A, B) != 0) with (A != B)
6700 if (RHSV == 0)
6701 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6702 BO->getOperand(1));
6703 break;
6704
6705 case Instruction::Or:
6706 // If bits are being or'd in that are not present in the constant we
6707 // are comparing against, then the comparison could never succeed!
6708 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
6709 Constant *NotCI = ConstantExpr::getNot(RHS);
6710 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
6711 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6712 isICMP_NE));
6713 }
6714 break;
6715
6716 case Instruction::And:
6717 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6718 // If bits are being compared against that are and'd out, then the
6719 // comparison can never succeed!
6720 if ((RHSV & ~BOC->getValue()) != 0)
6721 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6722 isICMP_NE));
6723
6724 // If we have ((X & C) == C), turn it into ((X & C) != 0).
6725 if (RHS == BOC && RHSV.isPowerOf2())
6726 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
6727 ICmpInst::ICMP_NE, LHSI,
6728 Constant::getNullValue(RHS->getType()));
6729
6730 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattner833f25d2008-06-02 01:29:46 +00006731 if (BOC->getValue().isSignBit()) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006732 Value *X = BO->getOperand(0);
6733 Constant *Zero = Constant::getNullValue(X->getType());
6734 ICmpInst::Predicate pred = isICMP_NE ?
6735 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
6736 return new ICmpInst(pred, X, Zero);
6737 }
6738
6739 // ((X & ~7) == 0) --> X < 8
6740 if (RHSV == 0 && isHighOnes(BOC)) {
6741 Value *X = BO->getOperand(0);
6742 Constant *NegX = ConstantExpr::getNeg(BOC);
6743 ICmpInst::Predicate pred = isICMP_NE ?
6744 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
6745 return new ICmpInst(pred, X, NegX);
6746 }
6747 }
6748 default: break;
6749 }
6750 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
6751 // Handle icmp {eq|ne} <intrinsic>, intcst.
6752 if (II->getIntrinsicID() == Intrinsic::bswap) {
6753 AddToWorkList(II);
6754 ICI.setOperand(0, II->getOperand(1));
6755 ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
6756 return &ICI;
6757 }
6758 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006759 }
6760 return 0;
6761}
6762
6763/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
6764/// We only handle extending casts so far.
6765///
Reid Spencere4d87aa2006-12-23 06:05:41 +00006766Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
6767 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +00006768 Value *LHSCIOp = LHSCI->getOperand(0);
6769 const Type *SrcTy = LHSCIOp->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00006770 const Type *DestTy = LHSCI->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00006771 Value *RHSCIOp;
6772
Chris Lattner8c756c12007-05-05 22:41:33 +00006773 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
6774 // integer type is the same size as the pointer type.
6775 if (LHSCI->getOpcode() == Instruction::PtrToInt &&
6776 getTargetData().getPointerSizeInBits() ==
6777 cast<IntegerType>(DestTy)->getBitWidth()) {
6778 Value *RHSOp = 0;
6779 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Chris Lattner6f6f5122007-05-06 07:24:03 +00006780 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Chris Lattner8c756c12007-05-05 22:41:33 +00006781 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
6782 RHSOp = RHSC->getOperand(0);
6783 // If the pointer types don't match, insert a bitcast.
6784 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner6d0339d2008-01-13 22:23:22 +00006785 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
Chris Lattner8c756c12007-05-05 22:41:33 +00006786 }
6787
6788 if (RHSOp)
6789 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
6790 }
6791
6792 // The code below only handles extension cast instructions, so far.
6793 // Enforce this.
Reid Spencere4d87aa2006-12-23 06:05:41 +00006794 if (LHSCI->getOpcode() != Instruction::ZExt &&
6795 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattnerb352fa52005-01-17 03:20:02 +00006796 return 0;
6797
Reid Spencere4d87aa2006-12-23 06:05:41 +00006798 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
6799 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattner484d3cf2005-04-24 06:59:08 +00006800
Reid Spencere4d87aa2006-12-23 06:05:41 +00006801 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00006802 // Not an extension from the same type?
6803 RHSCIOp = CI->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006804 if (RHSCIOp->getType() != LHSCIOp->getType())
6805 return 0;
Chris Lattnera5c5e772007-01-13 23:11:38 +00006806
Nick Lewycky4189a532008-01-28 03:48:02 +00006807 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Chris Lattnera5c5e772007-01-13 23:11:38 +00006808 // and the other is a zext), then we can't handle this.
6809 if (CI->getOpcode() != LHSCI->getOpcode())
6810 return 0;
6811
Nick Lewycky4189a532008-01-28 03:48:02 +00006812 // Deal with equality cases early.
6813 if (ICI.isEquality())
6814 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6815
6816 // A signed comparison of sign extended values simplifies into a
6817 // signed comparison.
6818 if (isSignedCmp && isSignedExt)
6819 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6820
6821 // The other three cases all fold into an unsigned comparison.
6822 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer6731d5c2004-11-28 21:31:15 +00006823 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00006824
Reid Spencere4d87aa2006-12-23 06:05:41 +00006825 // If we aren't dealing with a constant on the RHS, exit early
6826 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
6827 if (!CI)
6828 return 0;
6829
6830 // Compute the constant that would happen if we truncated to SrcTy then
6831 // reextended to DestTy.
6832 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
6833 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
6834
6835 // If the re-extended constant didn't change...
6836 if (Res2 == CI) {
6837 // Make sure that sign of the Cmp and the sign of the Cast are the same.
6838 // For example, we might have:
6839 // %A = sext short %X to uint
6840 // %B = icmp ugt uint %A, 1330
6841 // It is incorrect to transform this into
6842 // %B = icmp ugt short %X, 1330
6843 // because %A may have negative value.
6844 //
Chris Lattnerf2991842008-07-11 04:09:09 +00006845 // However, we allow this when the compare is EQ/NE, because they are
6846 // signless.
6847 if (isSignedExt == isSignedCmp || ICI.isEquality())
Reid Spencere4d87aa2006-12-23 06:05:41 +00006848 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
Chris Lattnerf2991842008-07-11 04:09:09 +00006849 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +00006850 }
6851
6852 // The re-extended constant changed so the constant cannot be represented
6853 // in the shorter type. Consequently, we cannot emit a simple comparison.
6854
6855 // First, handle some easy cases. We know the result cannot be equal at this
6856 // point so handle the ICI.isEquality() cases
6857 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006858 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006859 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006860 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006861
6862 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
6863 // should have been folded away previously and not enter in here.
6864 Value *Result;
6865 if (isSignedCmp) {
6866 // We're performing a signed comparison.
Reid Spencer0460fb32007-03-22 20:36:03 +00006867 if (cast<ConstantInt>(CI)->getValue().isNegative())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006868 Result = ConstantInt::getFalse(); // X < (small) --> false
Reid Spencere4d87aa2006-12-23 06:05:41 +00006869 else
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006870 Result = ConstantInt::getTrue(); // X < (large) --> true
Reid Spencere4d87aa2006-12-23 06:05:41 +00006871 } else {
6872 // We're performing an unsigned comparison.
6873 if (isSignedExt) {
6874 // We're performing an unsigned comp with a sign extended value.
6875 // This is true if the input is >= 0. [aka >s -1]
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006876 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006877 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
6878 NegOne, ICI.getName()), ICI);
6879 } else {
6880 // Unsigned extend & unsigned compare -> always true.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006881 Result = ConstantInt::getTrue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00006882 }
6883 }
6884
6885 // Finally, return the value computed.
6886 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
Chris Lattnerf2991842008-07-11 04:09:09 +00006887 ICI.getPredicate() == ICmpInst::ICMP_SLT)
Reid Spencere4d87aa2006-12-23 06:05:41 +00006888 return ReplaceInstUsesWith(ICI, Result);
Chris Lattnerf2991842008-07-11 04:09:09 +00006889
6890 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
6891 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
6892 "ICmp should be folded!");
6893 if (Constant *CI = dyn_cast<Constant>(Result))
6894 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
6895 return BinaryOperator::CreateNot(Result);
Chris Lattner484d3cf2005-04-24 06:59:08 +00006896}
Chris Lattner3f5b8772002-05-06 16:14:14 +00006897
Reid Spencer832254e2007-02-02 02:16:23 +00006898Instruction *InstCombiner::visitShl(BinaryOperator &I) {
6899 return commonShiftTransforms(I);
6900}
6901
6902Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
6903 return commonShiftTransforms(I);
6904}
6905
6906Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner348f6652007-12-06 01:59:46 +00006907 if (Instruction *R = commonShiftTransforms(I))
6908 return R;
6909
6910 Value *Op0 = I.getOperand(0);
6911
6912 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
6913 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
6914 if (CSI->isAllOnesValue())
6915 return ReplaceInstUsesWith(I, CSI);
6916
6917 // See if we can turn a signed shr into an unsigned shr.
Nate Begeman5bc1ea02008-07-29 15:49:41 +00006918 if (!isa<VectorType>(I.getType()) &&
6919 MaskedValueIsZero(Op0,
Chris Lattner348f6652007-12-06 01:59:46 +00006920 APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006921 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
Chris Lattner348f6652007-12-06 01:59:46 +00006922
6923 return 0;
Reid Spencer832254e2007-02-02 02:16:23 +00006924}
6925
6926Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
6927 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00006928 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00006929
6930 // shl X, 0 == X and shr X, 0 == X
6931 // shl 0, X == 0 and shr 0, X == 0
Reid Spencer832254e2007-02-02 02:16:23 +00006932 if (Op1 == Constant::getNullValue(Op1->getType()) ||
Chris Lattner233f7dc2002-08-12 21:17:25 +00006933 Op0 == Constant::getNullValue(Op0->getType()))
6934 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006935
Reid Spencere4d87aa2006-12-23 06:05:41 +00006936 if (isa<UndefValue>(Op0)) {
6937 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00006938 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006939 else // undef << X -> 0, undef >>u X -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00006940 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6941 }
6942 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006943 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
6944 return ReplaceInstUsesWith(I, Op0);
6945 else // X << undef, X >>u undef -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00006946 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00006947 }
6948
Chris Lattner2eefe512004-04-09 19:05:30 +00006949 // Try to fold constant and into select arguments.
6950 if (isa<Constant>(Op0))
6951 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00006952 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00006953 return R;
6954
Reid Spencerb83eb642006-10-20 07:07:24 +00006955 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00006956 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
6957 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006958 return 0;
6959}
6960
Reid Spencerb83eb642006-10-20 07:07:24 +00006961Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00006962 BinaryOperator &I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006963 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006964
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006965 // See if we can simplify any instructions used by the instruction whose sole
6966 // purpose is to compute bits we don't care about.
Reid Spencerb35ae032007-03-23 18:46:34 +00006967 uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
Chris Lattner886ab6c2009-01-31 08:15:18 +00006968 if (SimplifyDemandedInstructionBits(I))
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006969 return &I;
6970
Chris Lattner4d5542c2006-01-06 07:12:35 +00006971 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
6972 // of a signed value.
6973 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00006974 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00006975 if (I.getOpcode() != Instruction::AShr)
Chris Lattner4d5542c2006-01-06 07:12:35 +00006976 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
6977 else {
Chris Lattner0737c242007-02-02 05:29:55 +00006978 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00006979 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00006980 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006981 }
6982
6983 // ((X*C1) << C2) == (X * (C1 << C2))
6984 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
6985 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
6986 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006987 return BinaryOperator::CreateMul(BO->getOperand(0),
Chris Lattner4d5542c2006-01-06 07:12:35 +00006988 ConstantExpr::getShl(BOOp, Op1));
6989
6990 // Try to fold constant and into select arguments.
6991 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
6992 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6993 return R;
6994 if (isa<PHINode>(Op0))
6995 if (Instruction *NV = FoldOpIntoPhi(I))
6996 return NV;
6997
Chris Lattner8999dd32007-12-22 09:07:47 +00006998 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
6999 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7000 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7001 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7002 // place. Don't try to do this transformation in this case. Also, we
7003 // require that the input operand is a shift-by-constant so that we have
7004 // confidence that the shifts will get folded together. We could do this
7005 // xform in more cases, but it is unlikely to be profitable.
7006 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
7007 isa<ConstantInt>(TrOp->getOperand(1))) {
7008 // Okay, we'll do this xform. Make the shift of shift.
7009 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007010 Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
Chris Lattner8999dd32007-12-22 09:07:47 +00007011 I.getName());
7012 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
7013
7014 // For logical shifts, the truncation has the effect of making the high
7015 // part of the register be zeros. Emulate this by inserting an AND to
7016 // clear the top bits as needed. This 'and' will usually be zapped by
7017 // other xforms later if dead.
7018 unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
7019 unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
7020 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7021
7022 // The mask we constructed says what the trunc would do if occurring
7023 // between the shifts. We want to know the effect *after* the second
7024 // shift. We know that it is a logical shift by a constant, so adjust the
7025 // mask as appropriate.
7026 if (I.getOpcode() == Instruction::Shl)
7027 MaskV <<= Op1->getZExtValue();
7028 else {
7029 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7030 MaskV = MaskV.lshr(Op1->getZExtValue());
7031 }
7032
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007033 Instruction *And = BinaryOperator::CreateAnd(NSh, ConstantInt::get(MaskV),
Chris Lattner8999dd32007-12-22 09:07:47 +00007034 TI->getName());
7035 InsertNewInstBefore(And, I); // shift1 & 0x00FF
7036
7037 // Return the value truncated to the interesting size.
7038 return new TruncInst(And, I.getType());
7039 }
7040 }
7041
Chris Lattner4d5542c2006-01-06 07:12:35 +00007042 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00007043 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7044 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7045 Value *V1, *V2;
7046 ConstantInt *CC;
7047 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00007048 default: break;
7049 case Instruction::Add:
7050 case Instruction::And:
7051 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00007052 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007053 // These operators commute.
7054 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007055 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
Chris Lattnercb504b92008-11-16 05:38:51 +00007056 match(Op0BO->getOperand(1), m_Shr(m_Value(V1), m_Specific(Op1)))){
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007057 Instruction *YS = BinaryOperator::CreateShl(
Chris Lattner4d5542c2006-01-06 07:12:35 +00007058 Op0BO->getOperand(0), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00007059 Op0BO->getName());
7060 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007061 Instruction *X =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007062 BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007063 Op0BO->getOperand(1)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007064 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00007065 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007066 return BinaryOperator::CreateAnd(X, ConstantInt::get(
Zhou Sheng90b96812007-03-30 05:45:18 +00007067 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007068 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007069
Chris Lattner150f12a2005-09-18 06:30:59 +00007070 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00007071 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00007072 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00007073 match(Op0BOOp1,
Chris Lattnercb504b92008-11-16 05:38:51 +00007074 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
7075 m_ConstantInt(CC))) &&
7076 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007077 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007078 Op0BO->getOperand(0), Op1,
7079 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007080 InsertNewInstBefore(YS, I); // (Y << C)
7081 Instruction *XM =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007082 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00007083 V1->getName()+".mask");
7084 InsertNewInstBefore(XM, I); // X & (CC << C)
7085
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007086 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Chris Lattner150f12a2005-09-18 06:30:59 +00007087 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00007088 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007089
Reid Spencera07cb7d2007-02-02 14:41:37 +00007090 // FALL THROUGH.
7091 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007092 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007093 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
Chris Lattnercb504b92008-11-16 05:38:51 +00007094 match(Op0BO->getOperand(0), m_Shr(m_Value(V1), m_Specific(Op1)))){
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007095 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007096 Op0BO->getOperand(1), Op1,
7097 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007098 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007099 Instruction *X =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007100 BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007101 Op0BO->getOperand(0)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007102 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00007103 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007104 return BinaryOperator::CreateAnd(X, ConstantInt::get(
Zhou Sheng90b96812007-03-30 05:45:18 +00007105 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007106 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007107
Chris Lattner13d4ab42006-05-31 21:14:00 +00007108 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007109 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7110 match(Op0BO->getOperand(0),
7111 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner4d5542c2006-01-06 07:12:35 +00007112 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007113 cast<BinaryOperator>(Op0BO->getOperand(0))
7114 ->getOperand(0)->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007115 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007116 Op0BO->getOperand(1), Op1,
7117 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007118 InsertNewInstBefore(YS, I); // (Y << C)
7119 Instruction *XM =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007120 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00007121 V1->getName()+".mask");
7122 InsertNewInstBefore(XM, I); // X & (CC << C)
7123
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007124 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00007125 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007126
Chris Lattner11021cb2005-09-18 05:12:10 +00007127 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00007128 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007129 }
7130
7131
7132 // If the operand is an bitwise operator with a constant RHS, and the
7133 // shift is the only use, we can pull it out of the shift.
7134 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7135 bool isValid = true; // Valid only for And, Or, Xor
7136 bool highBitSet = false; // Transform if high bit of constant set?
7137
7138 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00007139 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00007140 case Instruction::Add:
7141 isValid = isLeftShift;
7142 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00007143 case Instruction::Or:
7144 case Instruction::Xor:
7145 highBitSet = false;
7146 break;
7147 case Instruction::And:
7148 highBitSet = true;
7149 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007150 }
7151
7152 // If this is a signed shift right, and the high bit is modified
7153 // by the logical operation, do not perform the transformation.
7154 // The highBitSet boolean indicates the value of the high bit of
7155 // the constant which would cause it to be modified for this
7156 // operation.
7157 //
Chris Lattnerc95ba442007-12-06 06:25:04 +00007158 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Shenge9e03f62007-03-28 15:02:20 +00007159 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007160
7161 if (isValid) {
7162 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
7163
7164 Instruction *NewShift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007165 BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007166 InsertNewInstBefore(NewShift, I);
Chris Lattner6934a042007-02-11 01:23:03 +00007167 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007168
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007169 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Chris Lattner4d5542c2006-01-06 07:12:35 +00007170 NewRHS);
7171 }
7172 }
7173 }
7174 }
7175
Chris Lattnerad0124c2006-01-06 07:52:12 +00007176 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00007177 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7178 if (ShiftOp && !ShiftOp->isShift())
7179 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007180
Reid Spencerb83eb642006-10-20 07:07:24 +00007181 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00007182 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007183 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7184 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00007185 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7186 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
7187 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00007188
Zhou Sheng4351c642007-04-02 08:20:41 +00007189 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Reid Spencerb35ae032007-03-23 18:46:34 +00007190 if (AmtSum > TypeBits)
7191 AmtSum = TypeBits;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007192
7193 const IntegerType *Ty = cast<IntegerType>(I.getType());
7194
7195 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00007196 if (I.getOpcode() == ShiftOp->getOpcode()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007197 return BinaryOperator::Create(I.getOpcode(), X,
Chris Lattnerb87056f2007-02-05 00:57:54 +00007198 ConstantInt::get(Ty, AmtSum));
7199 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
7200 I.getOpcode() == Instruction::AShr) {
7201 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007202 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007203 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
7204 I.getOpcode() == Instruction::LShr) {
7205 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
7206 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007207 BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007208 InsertNewInstBefore(Shift, I);
7209
Zhou Shenge9e03f62007-03-28 15:02:20 +00007210 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007211 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007212 }
7213
Chris Lattnerb87056f2007-02-05 00:57:54 +00007214 // Okay, if we get here, one shift must be left, and the other shift must be
7215 // right. See if the amounts are equal.
7216 if (ShiftAmt1 == ShiftAmt2) {
7217 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7218 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00007219 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007220 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007221 }
7222 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7223 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00007224 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007225 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007226 }
7227 // We can simplify ((X << C) >>s C) into a trunc + sext.
7228 // NOTE: we could do this for any C, but that would make 'unusual' integer
7229 // types. For now, just stick to ones well-supported by the code
7230 // generators.
7231 const Type *SExtType = 0;
7232 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00007233 case 1 :
7234 case 8 :
7235 case 16 :
7236 case 32 :
7237 case 64 :
7238 case 128:
7239 SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
7240 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007241 default: break;
7242 }
7243 if (SExtType) {
7244 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7245 InsertNewInstBefore(NewTrunc, I);
7246 return new SExtInst(NewTrunc, Ty);
7247 }
7248 // Otherwise, we can't handle it yet.
7249 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00007250 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007251
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007252 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007253 if (I.getOpcode() == Instruction::Shl) {
7254 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7255 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnere8d56c52006-01-07 01:32:28 +00007256 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007257 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00007258 InsertNewInstBefore(Shift, I);
7259
Reid Spencer55702aa2007-03-25 21:11:44 +00007260 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007261 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007262 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007263
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007264 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007265 if (I.getOpcode() == Instruction::LShr) {
7266 assert(ShiftOp->getOpcode() == Instruction::Shl);
7267 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007268 BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007269 InsertNewInstBefore(Shift, I);
Chris Lattnerad0124c2006-01-06 07:52:12 +00007270
Reid Spencerd5e30f02007-03-26 17:18:58 +00007271 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007272 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00007273 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007274
7275 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7276 } else {
7277 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00007278 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007279
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007280 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007281 if (I.getOpcode() == Instruction::Shl) {
7282 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7283 ShiftOp->getOpcode() == Instruction::AShr);
7284 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007285 BinaryOperator::Create(ShiftOp->getOpcode(), X,
Chris Lattnerb87056f2007-02-05 00:57:54 +00007286 ConstantInt::get(Ty, ShiftDiff));
7287 InsertNewInstBefore(Shift, I);
7288
Reid Spencer55702aa2007-03-25 21:11:44 +00007289 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007290 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007291 }
7292
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007293 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007294 if (I.getOpcode() == Instruction::LShr) {
7295 assert(ShiftOp->getOpcode() == Instruction::Shl);
7296 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007297 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007298 InsertNewInstBefore(Shift, I);
7299
Reid Spencer68d27cf2007-03-26 23:45:51 +00007300 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007301 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007302 }
7303
7304 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00007305 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00007306 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007307 return 0;
7308}
7309
Chris Lattnera1be5662002-05-02 17:06:02 +00007310
Chris Lattnercfd65102005-10-29 04:36:15 +00007311/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7312/// expression. If so, decompose it, returning some value X, such that Val is
7313/// X*Scale+Offset.
7314///
7315static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Jeff Cohen86796be2007-04-04 16:58:57 +00007316 int &Offset) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007317 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00007318 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007319 Offset = CI->getZExtValue();
Chris Lattner6a94de22007-10-12 05:30:59 +00007320 Scale = 0;
Reid Spencerc5b206b2006-12-31 05:48:39 +00007321 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattner6a94de22007-10-12 05:30:59 +00007322 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7323 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7324 if (I->getOpcode() == Instruction::Shl) {
7325 // This is a value scaled by '1 << the shift amt'.
7326 Scale = 1U << RHS->getZExtValue();
7327 Offset = 0;
7328 return I->getOperand(0);
7329 } else if (I->getOpcode() == Instruction::Mul) {
7330 // This value is scaled by 'RHS'.
7331 Scale = RHS->getZExtValue();
7332 Offset = 0;
7333 return I->getOperand(0);
7334 } else if (I->getOpcode() == Instruction::Add) {
7335 // We have X+C. Check to see if we really have (X*C2)+C1,
7336 // where C1 is divisible by C2.
7337 unsigned SubScale;
7338 Value *SubVal =
7339 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
7340 Offset += RHS->getZExtValue();
7341 Scale = SubScale;
7342 return SubVal;
Chris Lattnercfd65102005-10-29 04:36:15 +00007343 }
7344 }
7345 }
7346
7347 // Otherwise, we can't look past this.
7348 Scale = 1;
7349 Offset = 0;
7350 return Val;
7351}
7352
7353
Chris Lattnerb3f83972005-10-24 06:03:58 +00007354/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7355/// try to eliminate the cast by moving the type information into the alloc.
Chris Lattnerd3e28342007-04-27 17:44:50 +00007356Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Chris Lattnerb3f83972005-10-24 06:03:58 +00007357 AllocationInst &AI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007358 const PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007359
Chris Lattnerb53c2382005-10-24 06:22:12 +00007360 // Remove any uses of AI that are dead.
7361 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner535014f2007-02-15 22:52:10 +00007362
Chris Lattnerb53c2382005-10-24 06:22:12 +00007363 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7364 Instruction *User = cast<Instruction>(*UI++);
7365 if (isInstructionTriviallyDead(User)) {
7366 while (UI != E && *UI == User)
7367 ++UI; // If this instruction uses AI more than once, don't break UI.
7368
Chris Lattnerb53c2382005-10-24 06:22:12 +00007369 ++NumDeadInst;
Bill Wendlingb7427032006-11-26 09:46:52 +00007370 DOUT << "IC: DCE: " << *User;
Chris Lattnerf22a5c62007-03-02 19:59:19 +00007371 EraseInstFromFunction(*User);
Chris Lattnerb53c2382005-10-24 06:22:12 +00007372 }
7373 }
7374
Chris Lattnerb3f83972005-10-24 06:03:58 +00007375 // Get the type really allocated and the type casted to.
7376 const Type *AllocElTy = AI.getAllocatedType();
7377 const Type *CastElTy = PTy->getElementType();
7378 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007379
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007380 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7381 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00007382 if (CastElTyAlign < AllocElTyAlign) return 0;
7383
Chris Lattner39387a52005-10-24 06:35:18 +00007384 // If the allocation has multiple uses, only promote it if we are strictly
7385 // increasing the alignment of the resultant allocation. If we keep it the
7386 // same, we open the door to infinite loops of various kinds.
7387 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
7388
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00007389 uint64_t AllocElTySize = TD->getTypePaddedSize(AllocElTy);
7390 uint64_t CastElTySize = TD->getTypePaddedSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007391 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007392
Chris Lattner455fcc82005-10-29 03:19:53 +00007393 // See if we can satisfy the modulus by pulling a scale out of the array
7394 // size argument.
Jeff Cohen86796be2007-04-04 16:58:57 +00007395 unsigned ArraySizeScale;
7396 int ArrayOffset;
Chris Lattnercfd65102005-10-29 04:36:15 +00007397 Value *NumElements = // See if the array size is a decomposable linear expr.
7398 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
7399
Chris Lattner455fcc82005-10-29 03:19:53 +00007400 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7401 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00007402 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7403 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00007404
Chris Lattner455fcc82005-10-29 03:19:53 +00007405 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7406 Value *Amt = 0;
7407 if (Scale == 1) {
7408 Amt = NumElements;
7409 } else {
Reid Spencerb83eb642006-10-20 07:07:24 +00007410 // If the allocation size is constant, form a constant mul expression
Reid Spencerc5b206b2006-12-31 05:48:39 +00007411 Amt = ConstantInt::get(Type::Int32Ty, Scale);
7412 if (isa<ConstantInt>(NumElements))
Zhou Sheng4a1822a2007-04-02 13:45:30 +00007413 Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
Reid Spencerb83eb642006-10-20 07:07:24 +00007414 // otherwise multiply the amount and the number of elements
Chris Lattner455fcc82005-10-29 03:19:53 +00007415 else if (Scale != 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007416 Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
Chris Lattner455fcc82005-10-29 03:19:53 +00007417 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattner8142b0a2005-10-27 06:12:00 +00007418 }
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007419 }
7420
Jeff Cohen86796be2007-04-04 16:58:57 +00007421 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7422 Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007423 Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
Chris Lattnercfd65102005-10-29 04:36:15 +00007424 Amt = InsertNewInstBefore(Tmp, AI);
7425 }
7426
Chris Lattnerb3f83972005-10-24 06:03:58 +00007427 AllocationInst *New;
7428 if (isa<MallocInst>(AI))
Chris Lattner6934a042007-02-11 01:23:03 +00007429 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007430 else
Chris Lattner6934a042007-02-11 01:23:03 +00007431 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007432 InsertNewInstBefore(New, AI);
Chris Lattner6934a042007-02-11 01:23:03 +00007433 New->takeName(&AI);
Chris Lattner39387a52005-10-24 06:35:18 +00007434
7435 // If the allocation has multiple uses, insert a cast and change all things
7436 // that used it to use the new cast. This will also hack on CI, but it will
7437 // die soon.
7438 if (!AI.hasOneUse()) {
7439 AddUsesToWorkList(AI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007440 // New is the allocation instruction, pointer typed. AI is the original
7441 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7442 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner39387a52005-10-24 06:35:18 +00007443 InsertNewInstBefore(NewCast, AI);
7444 AI.replaceAllUsesWith(NewCast);
7445 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00007446 return ReplaceInstUsesWith(CI, New);
7447}
7448
Chris Lattner70074e02006-05-13 02:06:03 +00007449/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerc739cd62007-03-03 05:27:34 +00007450/// and return it as type Ty without inserting any new casts and without
7451/// changing the computed value. This is used by code that tries to decide
7452/// whether promoting or shrinking integer operations to wider or smaller types
7453/// will allow us to eliminate a truncate or extend.
7454///
7455/// This is a truncation operation if Ty is smaller than V->getType(), or an
7456/// extension operation if Ty is larger.
Chris Lattner8114b712008-06-18 04:00:49 +00007457///
7458/// If CastOpc is a truncation, then Ty will be a type smaller than V. We
7459/// should return true if trunc(V) can be computed by computing V in the smaller
7460/// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
7461/// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7462/// efficiently truncated.
7463///
7464/// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7465/// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7466/// the final result.
Evan Cheng4e56ab22009-01-16 02:11:43 +00007467bool InstCombiner::CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
7468 unsigned CastOpc,
7469 int &NumCastsRemoved){
Chris Lattnerc739cd62007-03-03 05:27:34 +00007470 // We can always evaluate constants in another type.
7471 if (isa<ConstantInt>(V))
7472 return true;
Chris Lattner70074e02006-05-13 02:06:03 +00007473
7474 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007475 if (!I) return false;
7476
7477 const IntegerType *OrigTy = cast<IntegerType>(V->getType());
Chris Lattner70074e02006-05-13 02:06:03 +00007478
Chris Lattner951626b2007-08-02 06:11:14 +00007479 // If this is an extension or truncate, we can often eliminate it.
7480 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7481 // If this is a cast from the destination type, we can trivially eliminate
7482 // it, and this will remove a cast overall.
7483 if (I->getOperand(0)->getType() == Ty) {
7484 // If the first operand is itself a cast, and is eliminable, do not count
7485 // this as an eliminable cast. We would prefer to eliminate those two
7486 // casts first.
Chris Lattner8114b712008-06-18 04:00:49 +00007487 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
Chris Lattner951626b2007-08-02 06:11:14 +00007488 ++NumCastsRemoved;
7489 return true;
7490 }
7491 }
7492
7493 // We can't extend or shrink something that has multiple uses: doing so would
7494 // require duplicating the instruction in general, which isn't profitable.
7495 if (!I->hasOneUse()) return false;
7496
Evan Chengf35fd542009-01-15 17:01:23 +00007497 unsigned Opc = I->getOpcode();
7498 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007499 case Instruction::Add:
7500 case Instruction::Sub:
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007501 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00007502 case Instruction::And:
7503 case Instruction::Or:
7504 case Instruction::Xor:
7505 // These operators can all arbitrarily be extended or truncated.
Chris Lattner951626b2007-08-02 06:11:14 +00007506 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007507 NumCastsRemoved) &&
Chris Lattner951626b2007-08-02 06:11:14 +00007508 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007509 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007510
Chris Lattner46b96052006-11-29 07:18:39 +00007511 case Instruction::Shl:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007512 // If we are truncating the result of this SHL, and if it's a shift of a
7513 // constant amount, we can always perform a SHL in a smaller type.
7514 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007515 uint32_t BitWidth = Ty->getBitWidth();
7516 if (BitWidth < OrigTy->getBitWidth() &&
7517 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattner951626b2007-08-02 06:11:14 +00007518 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007519 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007520 }
7521 break;
7522 case Instruction::LShr:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007523 // If this is a truncate of a logical shr, we can truncate it to a smaller
7524 // lshr iff we know that the bits we would otherwise be shifting in are
7525 // already zeros.
7526 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007527 uint32_t OrigBitWidth = OrigTy->getBitWidth();
7528 uint32_t BitWidth = Ty->getBitWidth();
7529 if (BitWidth < OrigBitWidth &&
Chris Lattnerc739cd62007-03-03 05:27:34 +00007530 MaskedValueIsZero(I->getOperand(0),
Zhou Sheng302748d2007-03-30 17:20:39 +00007531 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7532 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattner951626b2007-08-02 06:11:14 +00007533 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007534 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007535 }
7536 }
Chris Lattner46b96052006-11-29 07:18:39 +00007537 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007538 case Instruction::ZExt:
7539 case Instruction::SExt:
Chris Lattner951626b2007-08-02 06:11:14 +00007540 case Instruction::Trunc:
7541 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner5543a852007-08-02 17:23:38 +00007542 // can safely replace it. Note that replacing it does not reduce the number
7543 // of casts in the input.
Evan Chengf35fd542009-01-15 17:01:23 +00007544 if (Opc == CastOpc)
7545 return true;
7546
7547 // sext (zext ty1), ty2 -> zext ty2
Evan Cheng661d9c32009-01-15 17:09:07 +00007548 if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
Chris Lattner70074e02006-05-13 02:06:03 +00007549 return true;
Reid Spencer3da59db2006-11-27 01:05:10 +00007550 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007551 case Instruction::Select: {
7552 SelectInst *SI = cast<SelectInst>(I);
7553 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007554 NumCastsRemoved) &&
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007555 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007556 NumCastsRemoved);
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007557 }
Chris Lattner8114b712008-06-18 04:00:49 +00007558 case Instruction::PHI: {
7559 // We can change a phi if we can change all operands.
7560 PHINode *PN = cast<PHINode>(I);
7561 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
7562 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007563 NumCastsRemoved))
Chris Lattner8114b712008-06-18 04:00:49 +00007564 return false;
7565 return true;
7566 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007567 default:
Chris Lattner70074e02006-05-13 02:06:03 +00007568 // TODO: Can handle more cases here.
7569 break;
7570 }
7571
7572 return false;
7573}
7574
7575/// EvaluateInDifferentType - Given an expression that
7576/// CanEvaluateInDifferentType returns true for, actually insert the code to
7577/// evaluate the expression.
Reid Spencerc55b2432006-12-13 18:21:21 +00007578Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerc739cd62007-03-03 05:27:34 +00007579 bool isSigned) {
Chris Lattner70074e02006-05-13 02:06:03 +00007580 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencerc55b2432006-12-13 18:21:21 +00007581 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Chris Lattner70074e02006-05-13 02:06:03 +00007582
7583 // Otherwise, it must be an instruction.
7584 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00007585 Instruction *Res = 0;
Evan Chengf35fd542009-01-15 17:01:23 +00007586 unsigned Opc = I->getOpcode();
7587 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007588 case Instruction::Add:
7589 case Instruction::Sub:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00007590 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00007591 case Instruction::And:
7592 case Instruction::Or:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007593 case Instruction::Xor:
Chris Lattner46b96052006-11-29 07:18:39 +00007594 case Instruction::AShr:
7595 case Instruction::LShr:
7596 case Instruction::Shl: {
Reid Spencerc55b2432006-12-13 18:21:21 +00007597 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007598 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Evan Chengf35fd542009-01-15 17:01:23 +00007599 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Chris Lattner46b96052006-11-29 07:18:39 +00007600 break;
7601 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007602 case Instruction::Trunc:
7603 case Instruction::ZExt:
7604 case Instruction::SExt:
Reid Spencer3da59db2006-11-27 01:05:10 +00007605 // If the source type of the cast is the type we're trying for then we can
Chris Lattner951626b2007-08-02 06:11:14 +00007606 // just return the source. There's no need to insert it because it is not
7607 // new.
Chris Lattner70074e02006-05-13 02:06:03 +00007608 if (I->getOperand(0)->getType() == Ty)
7609 return I->getOperand(0);
7610
Chris Lattner8114b712008-06-18 04:00:49 +00007611 // Otherwise, must be the same type of cast, so just reinsert a new one.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007612 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
Chris Lattner8114b712008-06-18 04:00:49 +00007613 Ty);
Chris Lattner951626b2007-08-02 06:11:14 +00007614 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007615 case Instruction::Select: {
7616 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7617 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
7618 Res = SelectInst::Create(I->getOperand(0), True, False);
7619 break;
7620 }
Chris Lattner8114b712008-06-18 04:00:49 +00007621 case Instruction::PHI: {
7622 PHINode *OPN = cast<PHINode>(I);
7623 PHINode *NPN = PHINode::Create(Ty);
7624 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
7625 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
7626 NPN->addIncoming(V, OPN->getIncomingBlock(i));
7627 }
7628 Res = NPN;
7629 break;
7630 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007631 default:
Chris Lattner70074e02006-05-13 02:06:03 +00007632 // TODO: Can handle more cases here.
7633 assert(0 && "Unreachable!");
7634 break;
7635 }
7636
Chris Lattner8114b712008-06-18 04:00:49 +00007637 Res->takeName(I);
Chris Lattner70074e02006-05-13 02:06:03 +00007638 return InsertNewInstBefore(Res, *I);
7639}
7640
Reid Spencer3da59db2006-11-27 01:05:10 +00007641/// @brief Implement the transforms common to all CastInst visitors.
7642Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00007643 Value *Src = CI.getOperand(0);
7644
Dan Gohman23d9d272007-05-11 21:10:54 +00007645 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
Reid Spencer3da59db2006-11-27 01:05:10 +00007646 // eliminate it now.
Chris Lattner6e7ba452005-01-01 16:22:27 +00007647 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00007648 if (Instruction::CastOps opc =
7649 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
7650 // The first cast (CSrc) is eliminable so we need to fix up or replace
7651 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007652 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner8fd217c2002-08-02 20:00:25 +00007653 }
7654 }
Chris Lattnera710ddc2004-05-25 04:29:21 +00007655
Reid Spencer3da59db2006-11-27 01:05:10 +00007656 // If we are casting a select then fold the cast into the select
Chris Lattner6e7ba452005-01-01 16:22:27 +00007657 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
7658 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
7659 return NV;
Reid Spencer3da59db2006-11-27 01:05:10 +00007660
7661 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner4e998b22004-09-29 05:07:12 +00007662 if (isa<PHINode>(Src))
7663 if (Instruction *NV = FoldOpIntoPhi(CI))
7664 return NV;
Chris Lattner9fb92132006-04-12 18:09:35 +00007665
Reid Spencer3da59db2006-11-27 01:05:10 +00007666 return 0;
7667}
7668
Chris Lattner46cd5a12009-01-09 05:44:56 +00007669/// FindElementAtOffset - Given a type and a constant offset, determine whether
7670/// or not there is a sequence of GEP indices into the type that will land us at
Chris Lattner3914f722009-01-24 01:00:13 +00007671/// the specified offset. If so, fill them into NewIndices and return the
7672/// resultant element type, otherwise return null.
7673static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset,
7674 SmallVectorImpl<Value*> &NewIndices,
7675 const TargetData *TD) {
7676 if (!Ty->isSized()) return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00007677
7678 // Start with the index over the outer type. Note that the type size
7679 // might be zero (even if the offset isn't zero) if the indexed type
7680 // is something like [0 x {int, int}]
7681 const Type *IntPtrTy = TD->getIntPtrType();
7682 int64_t FirstIdx = 0;
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00007683 if (int64_t TySize = TD->getTypePaddedSize(Ty)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00007684 FirstIdx = Offset/TySize;
Chris Lattner31a69cb2009-01-11 20:41:36 +00007685 Offset -= FirstIdx*TySize;
Chris Lattner46cd5a12009-01-09 05:44:56 +00007686
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00007687 // Handle hosts where % returns negative instead of values [0..TySize).
Chris Lattner46cd5a12009-01-09 05:44:56 +00007688 if (Offset < 0) {
7689 --FirstIdx;
7690 Offset += TySize;
7691 assert(Offset >= 0);
7692 }
7693 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
7694 }
7695
7696 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
7697
7698 // Index into the types. If we fail, set OrigBase to null.
7699 while (Offset) {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00007700 // Indexing into tail padding between struct/array elements.
7701 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
Chris Lattner3914f722009-01-24 01:00:13 +00007702 return 0;
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00007703
Chris Lattner46cd5a12009-01-09 05:44:56 +00007704 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
7705 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00007706 assert(Offset < (int64_t)SL->getSizeInBytes() &&
7707 "Offset must stay within the indexed type");
7708
Chris Lattner46cd5a12009-01-09 05:44:56 +00007709 unsigned Elt = SL->getElementContainingOffset(Offset);
7710 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
7711
7712 Offset -= SL->getElementOffset(Elt);
7713 Ty = STy->getElementType(Elt);
Chris Lattner1c412d92009-01-11 20:23:52 +00007714 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00007715 uint64_t EltSize = TD->getTypePaddedSize(AT->getElementType());
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00007716 assert(EltSize && "Cannot index into a zero-sized array");
7717 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
7718 Offset %= EltSize;
Chris Lattner1c412d92009-01-11 20:23:52 +00007719 Ty = AT->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00007720 } else {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00007721 // Otherwise, we can't index into the middle of this atomic type, bail.
Chris Lattner3914f722009-01-24 01:00:13 +00007722 return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00007723 }
7724 }
7725
Chris Lattner3914f722009-01-24 01:00:13 +00007726 return Ty;
Chris Lattner46cd5a12009-01-09 05:44:56 +00007727}
7728
Chris Lattnerd3e28342007-04-27 17:44:50 +00007729/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
7730Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
7731 Value *Src = CI.getOperand(0);
7732
Chris Lattnerd3e28342007-04-27 17:44:50 +00007733 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner9bc14642007-04-28 00:57:34 +00007734 // If casting the result of a getelementptr instruction with no offset, turn
7735 // this into a cast of the original pointer!
Chris Lattnerd3e28342007-04-27 17:44:50 +00007736 if (GEP->hasAllZeroIndices()) {
7737 // Changing the cast operand is usually not a good idea but it is safe
7738 // here because the pointer operand is being replaced with another
7739 // pointer operand so the opcode doesn't need to change.
Chris Lattner9bc14642007-04-28 00:57:34 +00007740 AddToWorkList(GEP);
Chris Lattnerd3e28342007-04-27 17:44:50 +00007741 CI.setOperand(0, GEP->getOperand(0));
7742 return &CI;
7743 }
Chris Lattner9bc14642007-04-28 00:57:34 +00007744
7745 // If the GEP has a single use, and the base pointer is a bitcast, and the
7746 // GEP computes a constant offset, see if we can convert these three
7747 // instructions into fewer. This typically happens with unions and other
7748 // non-type-safe code.
7749 if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
7750 if (GEP->hasAllConstantIndices()) {
7751 // We are guaranteed to get a constant from EmitGEPOffset.
7752 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
7753 int64_t Offset = OffsetV->getSExtValue();
7754
7755 // Get the base pointer input of the bitcast, and the type it points to.
7756 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
7757 const Type *GEPIdxTy =
7758 cast<PointerType>(OrigBase->getType())->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00007759 SmallVector<Value*, 8> NewIndices;
7760 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD)) {
7761 // If we were able to index down into an element, create the GEP
7762 // and bitcast the result. This eliminates one bitcast, potentially
7763 // two.
7764 Instruction *NGEP = GetElementPtrInst::Create(OrigBase,
7765 NewIndices.begin(),
7766 NewIndices.end(), "");
7767 InsertNewInstBefore(NGEP, CI);
7768 NGEP->takeName(GEP);
Chris Lattner9bc14642007-04-28 00:57:34 +00007769
Chris Lattner46cd5a12009-01-09 05:44:56 +00007770 if (isa<BitCastInst>(CI))
7771 return new BitCastInst(NGEP, CI.getType());
7772 assert(isa<PtrToIntInst>(CI));
7773 return new PtrToIntInst(NGEP, CI.getType());
Chris Lattner9bc14642007-04-28 00:57:34 +00007774 }
7775 }
7776 }
Chris Lattnerd3e28342007-04-27 17:44:50 +00007777 }
7778
7779 return commonCastTransforms(CI);
7780}
7781
7782
Chris Lattnerc739cd62007-03-03 05:27:34 +00007783/// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
7784/// integer types. This function implements the common transforms for all those
Reid Spencer3da59db2006-11-27 01:05:10 +00007785/// cases.
7786/// @brief Implement the transforms common to CastInst with integer operands
7787Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
7788 if (Instruction *Result = commonCastTransforms(CI))
7789 return Result;
7790
7791 Value *Src = CI.getOperand(0);
7792 const Type *SrcTy = Src->getType();
7793 const Type *DestTy = CI.getType();
Zhou Sheng4351c642007-04-02 08:20:41 +00007794 uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
7795 uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00007796
Reid Spencer3da59db2006-11-27 01:05:10 +00007797 // See if we can simplify any instructions used by the LHS whose sole
7798 // purpose is to compute bits we don't care about.
Chris Lattner886ab6c2009-01-31 08:15:18 +00007799 if (SimplifyDemandedInstructionBits(CI))
Reid Spencer3da59db2006-11-27 01:05:10 +00007800 return &CI;
7801
7802 // If the source isn't an instruction or has more than one use then we
7803 // can't do anything more.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007804 Instruction *SrcI = dyn_cast<Instruction>(Src);
7805 if (!SrcI || !Src->hasOneUse())
Reid Spencer3da59db2006-11-27 01:05:10 +00007806 return 0;
7807
Chris Lattnerc739cd62007-03-03 05:27:34 +00007808 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00007809 int NumCastsRemoved = 0;
Chris Lattnerc739cd62007-03-03 05:27:34 +00007810 if (!isa<BitCastInst>(CI) &&
7811 CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
Evan Cheng4e56ab22009-01-16 02:11:43 +00007812 CI.getOpcode(), NumCastsRemoved)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007813 // If this cast is a truncate, evaluting in a different type always
Chris Lattner951626b2007-08-02 06:11:14 +00007814 // eliminates the cast, so it is always a win. If this is a zero-extension,
7815 // we need to do an AND to maintain the clear top-part of the computation,
7816 // so we require that the input have eliminated at least one cast. If this
7817 // is a sign extension, we insert two new casts (to do the extension) so we
Reid Spencer3da59db2006-11-27 01:05:10 +00007818 // require that two casts have been eliminated.
Evan Chengf35fd542009-01-15 17:01:23 +00007819 bool DoXForm = false;
7820 bool JustReplace = false;
Chris Lattnerc739cd62007-03-03 05:27:34 +00007821 switch (CI.getOpcode()) {
7822 default:
7823 // All the others use floating point so we shouldn't actually
7824 // get here because of the check above.
7825 assert(0 && "Unknown cast type");
7826 case Instruction::Trunc:
7827 DoXForm = true;
7828 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00007829 case Instruction::ZExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007830 DoXForm = NumCastsRemoved >= 1;
Evan Cheng4e56ab22009-01-16 02:11:43 +00007831 if (!DoXForm) {
7832 // If it's unnecessary to issue an AND to clear the high bits, it's
7833 // always profitable to do this xform.
7834 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy,
7835 CI.getOpcode() == Instruction::SExt);
7836 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
7837 if (MaskedValueIsZero(TryRes, Mask))
7838 return ReplaceInstUsesWith(CI, TryRes);
7839 else if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
7840 if (TryI->use_empty())
7841 EraseInstFromFunction(*TryI);
7842 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00007843 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00007844 }
Evan Chengf35fd542009-01-15 17:01:23 +00007845 case Instruction::SExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007846 DoXForm = NumCastsRemoved >= 2;
Evan Cheng4e56ab22009-01-16 02:11:43 +00007847 if (!DoXForm && !isa<TruncInst>(SrcI)) {
7848 // If we do not have to emit the truncate + sext pair, then it's always
7849 // profitable to do this xform.
Evan Chengf35fd542009-01-15 17:01:23 +00007850 //
7851 // It's not safe to eliminate the trunc + sext pair if one of the
7852 // eliminated cast is a truncate. e.g.
7853 // t2 = trunc i32 t1 to i16
7854 // t3 = sext i16 t2 to i32
7855 // !=
7856 // i32 t1
Evan Cheng4e56ab22009-01-16 02:11:43 +00007857 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy,
7858 CI.getOpcode() == Instruction::SExt);
7859 unsigned NumSignBits = ComputeNumSignBits(TryRes);
7860 if (NumSignBits > (DestBitSize - SrcBitSize))
7861 return ReplaceInstUsesWith(CI, TryRes);
7862 else if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
7863 if (TryI->use_empty())
7864 EraseInstFromFunction(*TryI);
Evan Chengf35fd542009-01-15 17:01:23 +00007865 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00007866 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007867 }
Evan Chengf35fd542009-01-15 17:01:23 +00007868 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007869
7870 if (DoXForm) {
Reid Spencerc55b2432006-12-13 18:21:21 +00007871 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
7872 CI.getOpcode() == Instruction::SExt);
Evan Cheng4e56ab22009-01-16 02:11:43 +00007873 if (JustReplace)
7874 // Just replace this cast with the result.
7875 return ReplaceInstUsesWith(CI, Res);
7876
Reid Spencer3da59db2006-11-27 01:05:10 +00007877 assert(Res->getType() == DestTy);
7878 switch (CI.getOpcode()) {
7879 default: assert(0 && "Unknown cast type!");
7880 case Instruction::Trunc:
7881 case Instruction::BitCast:
7882 // Just replace this cast with the result.
7883 return ReplaceInstUsesWith(CI, Res);
7884 case Instruction::ZExt: {
Reid Spencer3da59db2006-11-27 01:05:10 +00007885 assert(SrcBitSize < DestBitSize && "Not a zext?");
Evan Cheng4e56ab22009-01-16 02:11:43 +00007886
7887 // If the high bits are already zero, just replace this cast with the
7888 // result.
7889 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
7890 if (MaskedValueIsZero(Res, Mask))
7891 return ReplaceInstUsesWith(CI, Res);
7892
7893 // We need to emit an AND to clear the high bits.
Chris Lattnercd1d6d52007-04-02 05:48:58 +00007894 Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
7895 SrcBitSize));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007896 return BinaryOperator::CreateAnd(Res, C);
Reid Spencer3da59db2006-11-27 01:05:10 +00007897 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00007898 case Instruction::SExt: {
7899 // If the high bits are already filled with sign bit, just replace this
7900 // cast with the result.
7901 unsigned NumSignBits = ComputeNumSignBits(Res);
7902 if (NumSignBits > (DestBitSize - SrcBitSize))
Evan Chengf35fd542009-01-15 17:01:23 +00007903 return ReplaceInstUsesWith(CI, Res);
7904
Reid Spencer3da59db2006-11-27 01:05:10 +00007905 // We need to emit a cast to truncate, then a cast to sext.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007906 return CastInst::Create(Instruction::SExt,
Reid Spencer17212df2006-12-12 09:18:51 +00007907 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
7908 CI), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00007909 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00007910 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007911 }
7912 }
7913
7914 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
7915 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
7916
7917 switch (SrcI->getOpcode()) {
7918 case Instruction::Add:
7919 case Instruction::Mul:
7920 case Instruction::And:
7921 case Instruction::Or:
7922 case Instruction::Xor:
Chris Lattner01deb9d2007-04-03 17:43:25 +00007923 // If we are discarding information, rewrite.
Reid Spencer3da59db2006-11-27 01:05:10 +00007924 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
7925 // Don't insert two casts if they cannot be eliminated. We allow
7926 // two casts to be inserted if the sizes are the same. This could
7927 // only be converting signedness, which is a noop.
7928 if (DestBitSize == SrcBitSize ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00007929 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
7930 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer7eb76382006-12-13 17:19:09 +00007931 Instruction::CastOps opcode = CI.getOpcode();
Eli Friedmand1fd1da2008-11-30 21:09:11 +00007932 Value *Op0c = InsertCastBefore(opcode, Op0, DestTy, *SrcI);
7933 Value *Op1c = InsertCastBefore(opcode, Op1, DestTy, *SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007934 return BinaryOperator::Create(
Reid Spencer17212df2006-12-12 09:18:51 +00007935 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00007936 }
7937 }
7938
7939 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
7940 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
7941 SrcI->getOpcode() == Instruction::Xor &&
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007942 Op1 == ConstantInt::getTrue() &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00007943 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00007944 Value *New = InsertCastBefore(Instruction::ZExt, Op0, DestTy, CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007945 return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
Reid Spencer3da59db2006-11-27 01:05:10 +00007946 }
7947 break;
7948 case Instruction::SDiv:
7949 case Instruction::UDiv:
7950 case Instruction::SRem:
7951 case Instruction::URem:
7952 // If we are just changing the sign, rewrite.
7953 if (DestBitSize == SrcBitSize) {
7954 // Don't insert two casts if they cannot be eliminated. We allow
7955 // two casts to be inserted if the sizes are the same. This could
7956 // only be converting signedness, which is a noop.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007957 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
7958 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00007959 Value *Op0c = InsertCastBefore(Instruction::BitCast,
7960 Op0, DestTy, *SrcI);
7961 Value *Op1c = InsertCastBefore(Instruction::BitCast,
7962 Op1, DestTy, *SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007963 return BinaryOperator::Create(
Reid Spencer3da59db2006-11-27 01:05:10 +00007964 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7965 }
7966 }
7967 break;
7968
7969 case Instruction::Shl:
7970 // Allow changing the sign of the source operand. Do not allow
7971 // changing the size of the shift, UNLESS the shift amount is a
7972 // constant. We must not change variable sized shifts to a smaller
7973 // size, because it is undefined to shift more bits out than exist
7974 // in the value.
7975 if (DestBitSize == SrcBitSize ||
7976 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
Reid Spencer17212df2006-12-12 09:18:51 +00007977 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
7978 Instruction::BitCast : Instruction::Trunc);
Eli Friedmand1fd1da2008-11-30 21:09:11 +00007979 Value *Op0c = InsertCastBefore(opcode, Op0, DestTy, *SrcI);
7980 Value *Op1c = InsertCastBefore(opcode, Op1, DestTy, *SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007981 return BinaryOperator::CreateShl(Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00007982 }
7983 break;
7984 case Instruction::AShr:
7985 // If this is a signed shr, and if all bits shifted in are about to be
7986 // truncated off, turn it into an unsigned shr to allow greater
7987 // simplifications.
7988 if (DestBitSize < SrcBitSize &&
7989 isa<ConstantInt>(Op1)) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007990 uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
Reid Spencer3da59db2006-11-27 01:05:10 +00007991 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
7992 // Insert the new logical shift right.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007993 return BinaryOperator::CreateLShr(Op0, Op1);
Reid Spencer3da59db2006-11-27 01:05:10 +00007994 }
7995 }
7996 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007997 }
7998 return 0;
7999}
8000
Chris Lattner8a9f5712007-04-11 06:57:46 +00008001Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008002 if (Instruction *Result = commonIntCastTransforms(CI))
8003 return Result;
8004
8005 Value *Src = CI.getOperand(0);
8006 const Type *Ty = CI.getType();
Zhou Sheng4351c642007-04-02 08:20:41 +00008007 uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
8008 uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008009
8010 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
8011 switch (SrcI->getOpcode()) {
8012 default: break;
8013 case Instruction::LShr:
8014 // We can shrink lshr to something smaller if we know the bits shifted in
8015 // are already zeros.
8016 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00008017 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008018
8019 // Get a mask for the bits shifting in.
Zhou Shenge82fca02007-03-28 09:19:01 +00008020 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
Reid Spencer17212df2006-12-12 09:18:51 +00008021 Value* SrcIOp0 = SrcI->getOperand(0);
8022 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008023 if (ShAmt >= DestBitWidth) // All zeros.
8024 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
8025
8026 // Okay, we can shrink this. Truncate the input, then return a new
8027 // shift.
Reid Spencer832254e2007-02-02 02:16:23 +00008028 Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
8029 Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
8030 Ty, CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008031 return BinaryOperator::CreateLShr(V1, V2);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008032 }
Chris Lattnere13ab2a2006-12-05 01:26:29 +00008033 } else { // This is a variable shr.
8034
8035 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
8036 // more LLVM instructions, but allows '1 << Y' to be hoisted if
8037 // loop-invariant and CSE'd.
Reid Spencer4fe16d62007-01-11 18:21:29 +00008038 if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
Chris Lattnere13ab2a2006-12-05 01:26:29 +00008039 Value *One = ConstantInt::get(SrcI->getType(), 1);
8040
Reid Spencer832254e2007-02-02 02:16:23 +00008041 Value *V = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008042 BinaryOperator::CreateShl(One, SrcI->getOperand(1),
Reid Spencer832254e2007-02-02 02:16:23 +00008043 "tmp"), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008044 V = InsertNewInstBefore(BinaryOperator::CreateAnd(V,
Chris Lattnere13ab2a2006-12-05 01:26:29 +00008045 SrcI->getOperand(0),
8046 "tmp"), CI);
8047 Value *Zero = Constant::getNullValue(V->getType());
Reid Spencere4d87aa2006-12-23 06:05:41 +00008048 return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
Chris Lattnere13ab2a2006-12-05 01:26:29 +00008049 }
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008050 }
8051 break;
8052 }
8053 }
8054
8055 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008056}
8057
Evan Chengb98a10e2008-03-24 00:21:34 +00008058/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8059/// in order to eliminate the icmp.
8060Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8061 bool DoXform) {
8062 // If we are just checking for a icmp eq of a single bit and zext'ing it
8063 // to an integer, then shift the bit to the appropriate place and then
8064 // cast to integer to avoid the comparison.
8065 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8066 const APInt &Op1CV = Op1C->getValue();
8067
8068 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
8069 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
8070 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8071 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8072 if (!DoXform) return ICI;
8073
8074 Value *In = ICI->getOperand(0);
8075 Value *Sh = ConstantInt::get(In->getType(),
8076 In->getType()->getPrimitiveSizeInBits()-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008077 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
Evan Chengb98a10e2008-03-24 00:21:34 +00008078 In->getName()+".lobit"),
8079 CI);
8080 if (In->getType() != CI.getType())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008081 In = CastInst::CreateIntegerCast(In, CI.getType(),
Evan Chengb98a10e2008-03-24 00:21:34 +00008082 false/*ZExt*/, "tmp", &CI);
8083
8084 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
8085 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008086 In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
Evan Chengb98a10e2008-03-24 00:21:34 +00008087 In->getName()+".not"),
8088 CI);
8089 }
8090
8091 return ReplaceInstUsesWith(CI, In);
8092 }
8093
8094
8095
8096 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
8097 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8098 // zext (X == 1) to i32 --> X iff X has only the low bit set.
8099 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
8100 // zext (X != 0) to i32 --> X iff X has only the low bit set.
8101 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
8102 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
8103 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8104 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
8105 // This only works for EQ and NE
8106 ICI->isEquality()) {
8107 // If Op1C some other power of two, convert:
8108 uint32_t BitWidth = Op1C->getType()->getBitWidth();
8109 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8110 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8111 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8112
8113 APInt KnownZeroMask(~KnownZero);
8114 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8115 if (!DoXform) return ICI;
8116
8117 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8118 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8119 // (X&4) == 2 --> false
8120 // (X&4) != 2 --> true
8121 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
8122 Res = ConstantExpr::getZExt(Res, CI.getType());
8123 return ReplaceInstUsesWith(CI, Res);
8124 }
8125
8126 uint32_t ShiftAmt = KnownZeroMask.logBase2();
8127 Value *In = ICI->getOperand(0);
8128 if (ShiftAmt) {
8129 // Perform a logical shr by shiftamt.
8130 // Insert the shift to put the result in the low bit.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008131 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
Evan Chengb98a10e2008-03-24 00:21:34 +00008132 ConstantInt::get(In->getType(), ShiftAmt),
8133 In->getName()+".lobit"), CI);
8134 }
8135
8136 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
8137 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008138 In = BinaryOperator::CreateXor(In, One, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00008139 InsertNewInstBefore(cast<Instruction>(In), CI);
8140 }
8141
8142 if (CI.getType() == In->getType())
8143 return ReplaceInstUsesWith(CI, In);
8144 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008145 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chengb98a10e2008-03-24 00:21:34 +00008146 }
8147 }
8148 }
8149
8150 return 0;
8151}
8152
Chris Lattner8a9f5712007-04-11 06:57:46 +00008153Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008154 // If one of the common conversion will work ..
8155 if (Instruction *Result = commonIntCastTransforms(CI))
8156 return Result;
8157
8158 Value *Src = CI.getOperand(0);
8159
8160 // If this is a cast of a cast
8161 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00008162 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8163 // types and if the sizes are just right we can convert this into a logical
8164 // 'and' which will be much cheaper than the pair of casts.
8165 if (isa<TruncInst>(CSrc)) {
8166 // Get the sizes of the types involved
8167 Value *A = CSrc->getOperand(0);
Zhou Sheng4351c642007-04-02 08:20:41 +00008168 uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
8169 uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
8170 uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00008171 // If we're actually extending zero bits and the trunc is a no-op
8172 if (MidSize < DstSize && SrcSize == DstSize) {
8173 // Replace both of the casts with an And of the type mask.
Zhou Shenge82fca02007-03-28 09:19:01 +00008174 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Reid Spencerad6676e2007-03-22 20:56:53 +00008175 Constant *AndConst = ConstantInt::get(AndValue);
Reid Spencer3da59db2006-11-27 01:05:10 +00008176 Instruction *And =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008177 BinaryOperator::CreateAnd(CSrc->getOperand(0), AndConst);
Reid Spencer3da59db2006-11-27 01:05:10 +00008178 // Unfortunately, if the type changed, we need to cast it back.
8179 if (And->getType() != CI.getType()) {
8180 And->setName(CSrc->getName()+".mask");
8181 InsertNewInstBefore(And, CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008182 And = CastInst::CreateIntegerCast(And, CI.getType(), false/*ZExt*/);
Reid Spencer3da59db2006-11-27 01:05:10 +00008183 }
8184 return And;
8185 }
8186 }
8187 }
8188
Evan Chengb98a10e2008-03-24 00:21:34 +00008189 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8190 return transformZExtICmp(ICI, CI);
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00008191
Evan Chengb98a10e2008-03-24 00:21:34 +00008192 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8193 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8194 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8195 // of the (zext icmp) will be transformed.
8196 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8197 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8198 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8199 (transformZExtICmp(LHS, CI, false) ||
8200 transformZExtICmp(RHS, CI, false))) {
8201 Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8202 Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008203 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Chris Lattner66bc3252007-04-11 05:45:39 +00008204 }
Evan Chengb98a10e2008-03-24 00:21:34 +00008205 }
8206
Reid Spencer3da59db2006-11-27 01:05:10 +00008207 return 0;
8208}
8209
Chris Lattner8a9f5712007-04-11 06:57:46 +00008210Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattnerba417832007-04-11 06:12:58 +00008211 if (Instruction *I = commonIntCastTransforms(CI))
8212 return I;
8213
Chris Lattner8a9f5712007-04-11 06:57:46 +00008214 Value *Src = CI.getOperand(0);
8215
Dan Gohman1975d032008-10-30 20:40:10 +00008216 // Canonicalize sign-extend from i1 to a select.
8217 if (Src->getType() == Type::Int1Ty)
8218 return SelectInst::Create(Src,
8219 ConstantInt::getAllOnesValue(CI.getType()),
8220 Constant::getNullValue(CI.getType()));
Dan Gohmanf35c8822008-05-20 21:01:12 +00008221
8222 // See if the value being truncated is already sign extended. If so, just
8223 // eliminate the trunc/sext pair.
8224 if (getOpcode(Src) == Instruction::Trunc) {
8225 Value *Op = cast<User>(Src)->getOperand(0);
8226 unsigned OpBits = cast<IntegerType>(Op->getType())->getBitWidth();
8227 unsigned MidBits = cast<IntegerType>(Src->getType())->getBitWidth();
8228 unsigned DestBits = cast<IntegerType>(CI.getType())->getBitWidth();
8229 unsigned NumSignBits = ComputeNumSignBits(Op);
8230
8231 if (OpBits == DestBits) {
8232 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
8233 // bits, it is already ready.
8234 if (NumSignBits > DestBits-MidBits)
8235 return ReplaceInstUsesWith(CI, Op);
8236 } else if (OpBits < DestBits) {
8237 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
8238 // bits, just sext from i32.
8239 if (NumSignBits > OpBits-MidBits)
8240 return new SExtInst(Op, CI.getType(), "tmp");
8241 } else {
8242 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
8243 // bits, just truncate to i32.
8244 if (NumSignBits > OpBits-MidBits)
8245 return new TruncInst(Op, CI.getType(), "tmp");
8246 }
8247 }
Chris Lattner46bbad22008-08-06 07:35:52 +00008248
8249 // If the input is a shl/ashr pair of a same constant, then this is a sign
8250 // extension from a smaller value. If we could trust arbitrary bitwidth
8251 // integers, we could turn this into a truncate to the smaller bit and then
8252 // use a sext for the whole extension. Since we don't, look deeper and check
8253 // for a truncate. If the source and dest are the same type, eliminate the
8254 // trunc and extend and just do shifts. For example, turn:
8255 // %a = trunc i32 %i to i8
8256 // %b = shl i8 %a, 6
8257 // %c = ashr i8 %b, 6
8258 // %d = sext i8 %c to i32
8259 // into:
8260 // %a = shl i32 %i, 30
8261 // %d = ashr i32 %a, 30
8262 Value *A = 0;
8263 ConstantInt *BA = 0, *CA = 0;
8264 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
8265 m_ConstantInt(CA))) &&
8266 BA == CA && isa<TruncInst>(A)) {
8267 Value *I = cast<TruncInst>(A)->getOperand(0);
8268 if (I->getType() == CI.getType()) {
8269 unsigned MidSize = Src->getType()->getPrimitiveSizeInBits();
8270 unsigned SrcDstSize = CI.getType()->getPrimitiveSizeInBits();
8271 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
8272 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
8273 I = InsertNewInstBefore(BinaryOperator::CreateShl(I, ShAmtV,
8274 CI.getName()), CI);
8275 return BinaryOperator::CreateAShr(I, ShAmtV);
8276 }
8277 }
8278
Chris Lattnerba417832007-04-11 06:12:58 +00008279 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008280}
8281
Chris Lattnerb7530652008-01-27 05:29:54 +00008282/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8283/// in the specified FP type without changing its value.
Chris Lattner02a260a2008-04-20 00:41:09 +00008284static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
Dale Johannesen23a98552008-10-09 23:00:39 +00008285 bool losesInfo;
Chris Lattnerb7530652008-01-27 05:29:54 +00008286 APFloat F = CFP->getValueAPF();
Dale Johannesen23a98552008-10-09 23:00:39 +00008287 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8288 if (!losesInfo)
Chris Lattner02a260a2008-04-20 00:41:09 +00008289 return ConstantFP::get(F);
Chris Lattnerb7530652008-01-27 05:29:54 +00008290 return 0;
8291}
8292
8293/// LookThroughFPExtensions - If this is an fp extension instruction, look
8294/// through it until we get the source value.
8295static Value *LookThroughFPExtensions(Value *V) {
8296 if (Instruction *I = dyn_cast<Instruction>(V))
8297 if (I->getOpcode() == Instruction::FPExt)
8298 return LookThroughFPExtensions(I->getOperand(0));
8299
8300 // If this value is a constant, return the constant in the smallest FP type
8301 // that can accurately represent it. This allows us to turn
8302 // (float)((double)X+2.0) into x+2.0f.
8303 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8304 if (CFP->getType() == Type::PPC_FP128Ty)
8305 return V; // No constant folding of this.
8306 // See if the value can be truncated to float and then reextended.
Chris Lattner02a260a2008-04-20 00:41:09 +00008307 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
Chris Lattnerb7530652008-01-27 05:29:54 +00008308 return V;
8309 if (CFP->getType() == Type::DoubleTy)
8310 return V; // Won't shrink.
Chris Lattner02a260a2008-04-20 00:41:09 +00008311 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
Chris Lattnerb7530652008-01-27 05:29:54 +00008312 return V;
8313 // Don't try to shrink to various long double types.
8314 }
8315
8316 return V;
8317}
8318
8319Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8320 if (Instruction *I = commonCastTransforms(CI))
8321 return I;
8322
8323 // If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are
8324 // smaller than the destination type, we can eliminate the truncate by doing
8325 // the add as the smaller type. This applies to add/sub/mul/div as well as
8326 // many builtins (sqrt, etc).
8327 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8328 if (OpI && OpI->hasOneUse()) {
8329 switch (OpI->getOpcode()) {
8330 default: break;
8331 case Instruction::Add:
8332 case Instruction::Sub:
8333 case Instruction::Mul:
8334 case Instruction::FDiv:
8335 case Instruction::FRem:
8336 const Type *SrcTy = OpI->getType();
8337 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
8338 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
8339 if (LHSTrunc->getType() != SrcTy &&
8340 RHSTrunc->getType() != SrcTy) {
8341 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
8342 // If the source types were both smaller than the destination type of
8343 // the cast, do this xform.
8344 if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
8345 RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
8346 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8347 CI.getType(), CI);
8348 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8349 CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008350 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerb7530652008-01-27 05:29:54 +00008351 }
8352 }
8353 break;
8354 }
8355 }
8356 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008357}
8358
8359Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8360 return commonCastTransforms(CI);
8361}
8362
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008363Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00008364 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8365 if (OpI == 0)
8366 return commonCastTransforms(FI);
8367
8368 // fptoui(uitofp(X)) --> X
8369 // fptoui(sitofp(X)) --> X
8370 // This is safe if the intermediate type has enough bits in its mantissa to
8371 // accurately represent all values of X. For example, do not do this with
8372 // i64->float->i64. This is also safe for sitofp case, because any negative
8373 // 'X' value would cause an undefined result for the fptoui.
8374 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8375 OpI->getOperand(0)->getType() == FI.getType() &&
8376 (int)FI.getType()->getPrimitiveSizeInBits() < /*extra bit for sign */
8377 OpI->getType()->getFPMantissaWidth())
8378 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008379
8380 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008381}
8382
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008383Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00008384 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8385 if (OpI == 0)
8386 return commonCastTransforms(FI);
8387
8388 // fptosi(sitofp(X)) --> X
8389 // fptosi(uitofp(X)) --> X
8390 // This is safe if the intermediate type has enough bits in its mantissa to
8391 // accurately represent all values of X. For example, do not do this with
8392 // i64->float->i64. This is also safe for sitofp case, because any negative
8393 // 'X' value would cause an undefined result for the fptoui.
8394 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8395 OpI->getOperand(0)->getType() == FI.getType() &&
8396 (int)FI.getType()->getPrimitiveSizeInBits() <=
8397 OpI->getType()->getFPMantissaWidth())
8398 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008399
8400 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008401}
8402
8403Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8404 return commonCastTransforms(CI);
8405}
8406
8407Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8408 return commonCastTransforms(CI);
8409}
8410
8411Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008412 return commonPointerCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008413}
8414
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008415Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
8416 if (Instruction *I = commonCastTransforms(CI))
8417 return I;
8418
8419 const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
8420 if (!DestPointee->isSized()) return 0;
8421
8422 // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
8423 ConstantInt *Cst;
8424 Value *X;
8425 if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
8426 m_ConstantInt(Cst)))) {
8427 // If the source and destination operands have the same type, see if this
8428 // is a single-index GEP.
8429 if (X->getType() == CI.getType()) {
8430 // Get the size of the pointee type.
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00008431 uint64_t Size = TD->getTypePaddedSize(DestPointee);
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008432
8433 // Convert the constant to intptr type.
8434 APInt Offset = Cst->getValue();
8435 Offset.sextOrTrunc(TD->getPointerSizeInBits());
8436
8437 // If Offset is evenly divisible by Size, we can do this xform.
8438 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8439 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
Gabor Greif051a9502008-04-06 20:25:17 +00008440 return GetElementPtrInst::Create(X, ConstantInt::get(Offset));
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008441 }
8442 }
8443 // TODO: Could handle other cases, e.g. where add is indexing into field of
8444 // struct etc.
8445 } else if (CI.getOperand(0)->hasOneUse() &&
8446 match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
8447 // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
8448 // "inttoptr+GEP" instead of "add+intptr".
8449
8450 // Get the size of the pointee type.
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00008451 uint64_t Size = TD->getTypePaddedSize(DestPointee);
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008452
8453 // Convert the constant to intptr type.
8454 APInt Offset = Cst->getValue();
8455 Offset.sextOrTrunc(TD->getPointerSizeInBits());
8456
8457 // If Offset is evenly divisible by Size, we can do this xform.
8458 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8459 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8460
8461 Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
8462 "tmp"), CI);
Gabor Greif051a9502008-04-06 20:25:17 +00008463 return GetElementPtrInst::Create(P, ConstantInt::get(Offset), "tmp");
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008464 }
8465 }
8466 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008467}
8468
Chris Lattnerd3e28342007-04-27 17:44:50 +00008469Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008470 // If the operands are integer typed then apply the integer transforms,
8471 // otherwise just apply the common ones.
8472 Value *Src = CI.getOperand(0);
8473 const Type *SrcTy = Src->getType();
8474 const Type *DestTy = CI.getType();
8475
Chris Lattner42a75512007-01-15 02:27:26 +00008476 if (SrcTy->isInteger() && DestTy->isInteger()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008477 if (Instruction *Result = commonIntCastTransforms(CI))
8478 return Result;
Chris Lattnerd3e28342007-04-27 17:44:50 +00008479 } else if (isa<PointerType>(SrcTy)) {
8480 if (Instruction *I = commonPointerCastTransforms(CI))
8481 return I;
Reid Spencer3da59db2006-11-27 01:05:10 +00008482 } else {
8483 if (Instruction *Result = commonCastTransforms(CI))
8484 return Result;
8485 }
8486
8487
8488 // Get rid of casts from one type to the same type. These are useless and can
8489 // be replaced by the operand.
8490 if (DestTy == Src->getType())
8491 return ReplaceInstUsesWith(CI, Src);
8492
Reid Spencer3da59db2006-11-27 01:05:10 +00008493 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008494 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8495 const Type *DstElTy = DstPTy->getElementType();
8496 const Type *SrcElTy = SrcPTy->getElementType();
8497
Nate Begeman83ad90a2008-03-31 00:22:16 +00008498 // If the address spaces don't match, don't eliminate the bitcast, which is
8499 // required for changing types.
8500 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8501 return 0;
8502
Chris Lattnerd3e28342007-04-27 17:44:50 +00008503 // If we are casting a malloc or alloca to a pointer to a type of the same
8504 // size, rewrite the allocation instruction to allocate the "right" type.
8505 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8506 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8507 return V;
8508
Chris Lattnerd717c182007-05-05 22:32:24 +00008509 // If the source and destination are pointers, and this cast is equivalent
8510 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
Chris Lattnerd3e28342007-04-27 17:44:50 +00008511 // This can enhance SROA and other transforms that want type-safe pointers.
8512 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
8513 unsigned NumZeros = 0;
8514 while (SrcElTy != DstElTy &&
8515 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8516 SrcElTy->getNumContainedTypes() /* not "{}" */) {
8517 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8518 ++NumZeros;
8519 }
Chris Lattner4e998b22004-09-29 05:07:12 +00008520
Chris Lattnerd3e28342007-04-27 17:44:50 +00008521 // If we found a path from the src to dest, create the getelementptr now.
8522 if (SrcElTy == DstElTy) {
8523 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Gabor Greif051a9502008-04-06 20:25:17 +00008524 return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "",
8525 ((Instruction*) NULL));
Chris Lattner9fb92132006-04-12 18:09:35 +00008526 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008527 }
Chris Lattner24c8e382003-07-24 17:35:25 +00008528
Reid Spencer3da59db2006-11-27 01:05:10 +00008529 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8530 if (SVI->hasOneUse()) {
8531 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
8532 // a bitconvert to a vector with the same # elts.
Reid Spencer9d6565a2007-02-15 02:26:10 +00008533 if (isa<VectorType>(DestTy) &&
Mon P Wangaeb06d22008-11-10 04:46:22 +00008534 cast<VectorType>(DestTy)->getNumElements() ==
8535 SVI->getType()->getNumElements() &&
8536 SVI->getType()->getNumElements() ==
8537 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008538 CastInst *Tmp;
8539 // If either of the operands is a cast from CI.getType(), then
8540 // evaluating the shuffle in the casted destination's type will allow
8541 // us to eliminate at least one cast.
8542 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
8543 Tmp->getOperand(0)->getType() == DestTy) ||
8544 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
8545 Tmp->getOperand(0)->getType() == DestTy)) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00008546 Value *LHS = InsertCastBefore(Instruction::BitCast,
8547 SVI->getOperand(0), DestTy, CI);
8548 Value *RHS = InsertCastBefore(Instruction::BitCast,
8549 SVI->getOperand(1), DestTy, CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008550 // Return a new shuffle vector. Use the same element ID's, as we
8551 // know the vector types match #elts.
8552 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner01575b72006-05-25 23:24:33 +00008553 }
8554 }
8555 }
8556 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00008557 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00008558}
8559
Chris Lattnere576b912004-04-09 23:46:01 +00008560/// GetSelectFoldableOperands - We want to turn code that looks like this:
8561/// %C = or %A, %B
8562/// %D = select %cond, %C, %A
8563/// into:
8564/// %C = select %cond, %B, 0
8565/// %D = or %A, %C
8566///
8567/// Assuming that the specified instruction is an operand to the select, return
8568/// a bitmask indicating which operands of this instruction are foldable if they
8569/// equal the other incoming value of the select.
8570///
8571static unsigned GetSelectFoldableOperands(Instruction *I) {
8572 switch (I->getOpcode()) {
8573 case Instruction::Add:
8574 case Instruction::Mul:
8575 case Instruction::And:
8576 case Instruction::Or:
8577 case Instruction::Xor:
8578 return 3; // Can fold through either operand.
8579 case Instruction::Sub: // Can only fold on the amount subtracted.
8580 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencer3822ff52006-11-08 06:47:33 +00008581 case Instruction::LShr:
8582 case Instruction::AShr:
Misha Brukmanfd939082005-04-21 23:48:37 +00008583 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00008584 default:
8585 return 0; // Cannot fold
8586 }
8587}
8588
8589/// GetSelectFoldableConstant - For the same transformation as the previous
8590/// function, return the identity constant that goes into the select.
8591static Constant *GetSelectFoldableConstant(Instruction *I) {
8592 switch (I->getOpcode()) {
8593 default: assert(0 && "This cannot happen!"); abort();
8594 case Instruction::Add:
8595 case Instruction::Sub:
8596 case Instruction::Or:
8597 case Instruction::Xor:
Chris Lattnere576b912004-04-09 23:46:01 +00008598 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00008599 case Instruction::LShr:
8600 case Instruction::AShr:
Reid Spencer832254e2007-02-02 02:16:23 +00008601 return Constant::getNullValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00008602 case Instruction::And:
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00008603 return Constant::getAllOnesValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00008604 case Instruction::Mul:
8605 return ConstantInt::get(I->getType(), 1);
8606 }
8607}
8608
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008609/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
8610/// have the same opcode and only one use each. Try to simplify this.
8611Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
8612 Instruction *FI) {
8613 if (TI->getNumOperands() == 1) {
8614 // If this is a non-volatile load or a cast from the same type,
8615 // merge.
Reid Spencer3da59db2006-11-27 01:05:10 +00008616 if (TI->isCast()) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008617 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
8618 return 0;
8619 } else {
8620 return 0; // unknown unary op.
8621 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008622
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008623 // Fold this by inserting a select from the input values.
Gabor Greif051a9502008-04-06 20:25:17 +00008624 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
8625 FI->getOperand(0), SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008626 InsertNewInstBefore(NewSI, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008627 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Reid Spencer3da59db2006-11-27 01:05:10 +00008628 TI->getType());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008629 }
8630
Reid Spencer832254e2007-02-02 02:16:23 +00008631 // Only handle binary operators here.
8632 if (!isa<BinaryOperator>(TI))
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008633 return 0;
8634
8635 // Figure out if the operations have any operands in common.
8636 Value *MatchOp, *OtherOpT, *OtherOpF;
8637 bool MatchIsOpZero;
8638 if (TI->getOperand(0) == FI->getOperand(0)) {
8639 MatchOp = TI->getOperand(0);
8640 OtherOpT = TI->getOperand(1);
8641 OtherOpF = FI->getOperand(1);
8642 MatchIsOpZero = true;
8643 } else if (TI->getOperand(1) == FI->getOperand(1)) {
8644 MatchOp = TI->getOperand(1);
8645 OtherOpT = TI->getOperand(0);
8646 OtherOpF = FI->getOperand(0);
8647 MatchIsOpZero = false;
8648 } else if (!TI->isCommutative()) {
8649 return 0;
8650 } else if (TI->getOperand(0) == FI->getOperand(1)) {
8651 MatchOp = TI->getOperand(0);
8652 OtherOpT = TI->getOperand(1);
8653 OtherOpF = FI->getOperand(0);
8654 MatchIsOpZero = true;
8655 } else if (TI->getOperand(1) == FI->getOperand(0)) {
8656 MatchOp = TI->getOperand(1);
8657 OtherOpT = TI->getOperand(0);
8658 OtherOpF = FI->getOperand(1);
8659 MatchIsOpZero = true;
8660 } else {
8661 return 0;
8662 }
8663
8664 // If we reach here, they do have operations in common.
Gabor Greif051a9502008-04-06 20:25:17 +00008665 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
8666 OtherOpF, SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008667 InsertNewInstBefore(NewSI, SI);
8668
8669 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
8670 if (MatchIsOpZero)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008671 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008672 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008673 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008674 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00008675 assert(0 && "Shouldn't get here");
8676 return 0;
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008677}
8678
Dan Gohman81b28ce2008-09-16 18:46:06 +00008679/// visitSelectInstWithICmp - Visit a SelectInst that has an
8680/// ICmpInst as its first operand.
8681///
8682Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
8683 ICmpInst *ICI) {
8684 bool Changed = false;
8685 ICmpInst::Predicate Pred = ICI->getPredicate();
8686 Value *CmpLHS = ICI->getOperand(0);
8687 Value *CmpRHS = ICI->getOperand(1);
8688 Value *TrueVal = SI.getTrueValue();
8689 Value *FalseVal = SI.getFalseValue();
8690
8691 // Check cases where the comparison is with a constant that
8692 // can be adjusted to fit the min/max idiom. We may edit ICI in
8693 // place here, so make sure the select is the only user.
8694 if (ICI->hasOneUse())
Dan Gohman1975d032008-10-30 20:40:10 +00008695 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
Dan Gohman81b28ce2008-09-16 18:46:06 +00008696 switch (Pred) {
8697 default: break;
8698 case ICmpInst::ICMP_ULT:
8699 case ICmpInst::ICMP_SLT: {
8700 // X < MIN ? T : F --> F
8701 if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
8702 return ReplaceInstUsesWith(SI, FalseVal);
8703 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
8704 Constant *AdjustedRHS = SubOne(CI);
8705 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
8706 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
8707 Pred = ICmpInst::getSwappedPredicate(Pred);
8708 CmpRHS = AdjustedRHS;
8709 std::swap(FalseVal, TrueVal);
8710 ICI->setPredicate(Pred);
8711 ICI->setOperand(1, CmpRHS);
8712 SI.setOperand(1, TrueVal);
8713 SI.setOperand(2, FalseVal);
8714 Changed = true;
8715 }
8716 break;
8717 }
8718 case ICmpInst::ICMP_UGT:
8719 case ICmpInst::ICMP_SGT: {
8720 // X > MAX ? T : F --> F
8721 if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
8722 return ReplaceInstUsesWith(SI, FalseVal);
8723 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
8724 Constant *AdjustedRHS = AddOne(CI);
8725 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
8726 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
8727 Pred = ICmpInst::getSwappedPredicate(Pred);
8728 CmpRHS = AdjustedRHS;
8729 std::swap(FalseVal, TrueVal);
8730 ICI->setPredicate(Pred);
8731 ICI->setOperand(1, CmpRHS);
8732 SI.setOperand(1, TrueVal);
8733 SI.setOperand(2, FalseVal);
8734 Changed = true;
8735 }
8736 break;
8737 }
8738 }
8739
Dan Gohman1975d032008-10-30 20:40:10 +00008740 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed
8741 // (x >s -1) ? -1 : 0 -> ashr x, 31 -> all ones if not signed
Chris Lattnercb504b92008-11-16 05:38:51 +00008742 CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
Chris Lattner159c35b2009-01-05 23:53:12 +00008743 if (match(TrueVal, m_ConstantInt<-1>()) &&
8744 match(FalseVal, m_ConstantInt<0>()))
Chris Lattnercb504b92008-11-16 05:38:51 +00008745 Pred = ICI->getPredicate();
Chris Lattner159c35b2009-01-05 23:53:12 +00008746 else if (match(TrueVal, m_ConstantInt<0>()) &&
8747 match(FalseVal, m_ConstantInt<-1>()))
Chris Lattnercb504b92008-11-16 05:38:51 +00008748 Pred = CmpInst::getInversePredicate(ICI->getPredicate());
8749
Dan Gohman1975d032008-10-30 20:40:10 +00008750 if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
8751 // If we are just checking for a icmp eq of a single bit and zext'ing it
8752 // to an integer, then shift the bit to the appropriate place and then
8753 // cast to integer to avoid the comparison.
8754 const APInt &Op1CV = CI->getValue();
8755
8756 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
8757 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
8758 if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
Chris Lattnercb504b92008-11-16 05:38:51 +00008759 (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
Dan Gohman1975d032008-10-30 20:40:10 +00008760 Value *In = ICI->getOperand(0);
8761 Value *Sh = ConstantInt::get(In->getType(),
8762 In->getType()->getPrimitiveSizeInBits()-1);
8763 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
8764 In->getName()+".lobit"),
8765 *ICI);
Dan Gohman21440ac2008-11-02 00:17:33 +00008766 if (In->getType() != SI.getType())
8767 In = CastInst::CreateIntegerCast(In, SI.getType(),
Dan Gohman1975d032008-10-30 20:40:10 +00008768 true/*SExt*/, "tmp", ICI);
8769
8770 if (Pred == ICmpInst::ICMP_SGT)
8771 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
8772 In->getName()+".not"), *ICI);
8773
8774 return ReplaceInstUsesWith(SI, In);
8775 }
8776 }
8777 }
8778
Dan Gohman81b28ce2008-09-16 18:46:06 +00008779 if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
8780 // Transform (X == Y) ? X : Y -> Y
8781 if (Pred == ICmpInst::ICMP_EQ)
8782 return ReplaceInstUsesWith(SI, FalseVal);
8783 // Transform (X != Y) ? X : Y -> X
8784 if (Pred == ICmpInst::ICMP_NE)
8785 return ReplaceInstUsesWith(SI, TrueVal);
8786 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
8787
8788 } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
8789 // Transform (X == Y) ? Y : X -> X
8790 if (Pred == ICmpInst::ICMP_EQ)
8791 return ReplaceInstUsesWith(SI, FalseVal);
8792 // Transform (X != Y) ? Y : X -> Y
8793 if (Pred == ICmpInst::ICMP_NE)
8794 return ReplaceInstUsesWith(SI, TrueVal);
8795 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
8796 }
8797
8798 /// NOTE: if we wanted to, this is where to detect integer ABS
8799
8800 return Changed ? &SI : 0;
8801}
8802
Chris Lattner3d69f462004-03-12 05:52:32 +00008803Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00008804 Value *CondVal = SI.getCondition();
8805 Value *TrueVal = SI.getTrueValue();
8806 Value *FalseVal = SI.getFalseValue();
8807
8808 // select true, X, Y -> X
8809 // select false, X, Y -> Y
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008810 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencer579dca12007-01-12 04:24:46 +00008811 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00008812
8813 // select C, X, X -> X
8814 if (TrueVal == FalseVal)
8815 return ReplaceInstUsesWith(SI, TrueVal);
8816
Chris Lattnere87597f2004-10-16 18:11:37 +00008817 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
8818 return ReplaceInstUsesWith(SI, FalseVal);
8819 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
8820 return ReplaceInstUsesWith(SI, TrueVal);
8821 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
8822 if (isa<Constant>(TrueVal))
8823 return ReplaceInstUsesWith(SI, TrueVal);
8824 else
8825 return ReplaceInstUsesWith(SI, FalseVal);
8826 }
8827
Reid Spencer4fe16d62007-01-11 18:21:29 +00008828 if (SI.getType() == Type::Int1Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00008829 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00008830 if (C->getZExtValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00008831 // Change: A = select B, true, C --> A = or B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008832 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008833 } else {
8834 // Change: A = select B, false, C --> A = and !B, C
8835 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008836 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00008837 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008838 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008839 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00008840 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00008841 if (C->getZExtValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00008842 // Change: A = select B, C, false --> A = and B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008843 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008844 } else {
8845 // Change: A = select B, C, true --> A = or !B, C
8846 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008847 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00008848 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008849 return BinaryOperator::CreateOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008850 }
8851 }
Chris Lattnercfa59752007-11-25 21:27:53 +00008852
8853 // select a, b, a -> a&b
8854 // select a, a, b -> a|b
8855 if (CondVal == TrueVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008856 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattnercfa59752007-11-25 21:27:53 +00008857 else if (CondVal == FalseVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008858 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008859 }
Chris Lattner0c199a72004-04-08 04:43:23 +00008860
Chris Lattner2eefe512004-04-09 19:05:30 +00008861 // Selecting between two integer constants?
8862 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
8863 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattnerba417832007-04-11 06:12:58 +00008864 // select C, 1, 0 -> zext C to int
Reid Spencer2ec619a2007-03-23 21:24:59 +00008865 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008866 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer2ec619a2007-03-23 21:24:59 +00008867 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattnerba417832007-04-11 06:12:58 +00008868 // select C, 0, 1 -> zext !C to int
Chris Lattner2eefe512004-04-09 19:05:30 +00008869 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008870 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00008871 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008872 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00008873 }
Chris Lattner457dd822004-06-09 07:59:58 +00008874
Reid Spencere4d87aa2006-12-23 06:05:41 +00008875 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattnerb8456462006-09-20 04:44:59 +00008876
Reid Spencere4d87aa2006-12-23 06:05:41 +00008877 // (x <s 0) ? -1 : 0 -> ashr x, 31
Reid Spencer2ec619a2007-03-23 21:24:59 +00008878 if (TrueValC->isAllOnesValue() && FalseValC->isZero())
Chris Lattnerb8456462006-09-20 04:44:59 +00008879 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
Chris Lattnerba417832007-04-11 06:12:58 +00008880 if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
Chris Lattnerb8456462006-09-20 04:44:59 +00008881 // The comparison constant and the result are not neccessarily the
Reid Spencer3da59db2006-11-27 01:05:10 +00008882 // same width. Make an all-ones value by inserting a AShr.
Chris Lattnerb8456462006-09-20 04:44:59 +00008883 Value *X = IC->getOperand(0);
Zhou Sheng4351c642007-04-02 08:20:41 +00008884 uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
Reid Spencer832254e2007-02-02 02:16:23 +00008885 Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008886 Instruction *SRA = BinaryOperator::Create(Instruction::AShr, X,
Reid Spencer832254e2007-02-02 02:16:23 +00008887 ShAmt, "ones");
Chris Lattnerb8456462006-09-20 04:44:59 +00008888 InsertNewInstBefore(SRA, SI);
Eli Friedmand1fd1da2008-11-30 21:09:11 +00008889
8890 // Then cast to the appropriate width.
8891 return CastInst::CreateIntegerCast(SRA, SI.getType(), true);
Chris Lattnerb8456462006-09-20 04:44:59 +00008892 }
8893 }
8894
8895
8896 // If one of the constants is zero (we know they can't both be) and we
Chris Lattnerba417832007-04-11 06:12:58 +00008897 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattnerb8456462006-09-20 04:44:59 +00008898 // non-constant value, eliminate this whole mess. This corresponds to
8899 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer2ec619a2007-03-23 21:24:59 +00008900 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattner65b72ba2006-09-18 04:22:48 +00008901 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00008902 cast<Constant>(IC->getOperand(1))->isNullValue())
8903 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
8904 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00008905 isa<ConstantInt>(ICA->getOperand(1)) &&
8906 (ICA->getOperand(1) == TrueValC ||
8907 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00008908 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
8909 // Okay, now we know that everything is set up, we just don't
Reid Spencere4d87aa2006-12-23 06:05:41 +00008910 // know whether we have a icmp_ne or icmp_eq and whether the
8911 // true or false val is the zero.
Reid Spencer2ec619a2007-03-23 21:24:59 +00008912 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencere4d87aa2006-12-23 06:05:41 +00008913 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner457dd822004-06-09 07:59:58 +00008914 Value *V = ICA;
8915 if (ShouldNotVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008916 V = InsertNewInstBefore(BinaryOperator::Create(
Chris Lattner457dd822004-06-09 07:59:58 +00008917 Instruction::Xor, V, ICA->getOperand(1)), SI);
8918 return ReplaceInstUsesWith(SI, V);
8919 }
Chris Lattnerb8456462006-09-20 04:44:59 +00008920 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00008921 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00008922
8923 // See if we are selecting two values based on a comparison of the two values.
Reid Spencere4d87aa2006-12-23 06:05:41 +00008924 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
8925 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattnerd76956d2004-04-10 22:21:27 +00008926 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen5a2174f2007-10-03 17:45:27 +00008927 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8928 // This is not safe in general for floating point:
8929 // consider X== -0, Y== +0.
8930 // It becomes safe if either operand is a nonzero constant.
8931 ConstantFP *CFPt, *CFPf;
8932 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8933 !CFPt->getValueAPF().isZero()) ||
8934 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8935 !CFPf->getValueAPF().isZero()))
Chris Lattnerd76956d2004-04-10 22:21:27 +00008936 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen5a2174f2007-10-03 17:45:27 +00008937 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00008938 // Transform (X != Y) ? X : Y -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00008939 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattnerd76956d2004-04-10 22:21:27 +00008940 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00008941 // NOTE: if we wanted to, this is where to detect MIN/MAX
Chris Lattnerd76956d2004-04-10 22:21:27 +00008942
Reid Spencere4d87aa2006-12-23 06:05:41 +00008943 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattnerd76956d2004-04-10 22:21:27 +00008944 // Transform (X == Y) ? Y : X -> X
Dale Johannesen5a2174f2007-10-03 17:45:27 +00008945 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8946 // This is not safe in general for floating point:
8947 // consider X== -0, Y== +0.
8948 // It becomes safe if either operand is a nonzero constant.
8949 ConstantFP *CFPt, *CFPf;
8950 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8951 !CFPt->getValueAPF().isZero()) ||
8952 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8953 !CFPf->getValueAPF().isZero()))
8954 return ReplaceInstUsesWith(SI, FalseVal);
8955 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00008956 // Transform (X != Y) ? Y : X -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00008957 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8958 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00008959 // NOTE: if we wanted to, this is where to detect MIN/MAX
Reid Spencere4d87aa2006-12-23 06:05:41 +00008960 }
Dan Gohman81b28ce2008-09-16 18:46:06 +00008961 // NOTE: if we wanted to, this is where to detect ABS
Reid Spencere4d87aa2006-12-23 06:05:41 +00008962 }
8963
8964 // See if we are selecting two values based on a comparison of the two values.
Dan Gohman81b28ce2008-09-16 18:46:06 +00008965 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
8966 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
8967 return Result;
Misha Brukmanfd939082005-04-21 23:48:37 +00008968
Chris Lattner87875da2005-01-13 22:52:24 +00008969 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
8970 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
8971 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattner87875da2005-01-13 22:52:24 +00008972 Instruction *AddOp = 0, *SubOp = 0;
8973
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008974 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
8975 if (TI->getOpcode() == FI->getOpcode())
8976 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
8977 return IV;
8978
8979 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
8980 // even legal for FP.
Chris Lattner87875da2005-01-13 22:52:24 +00008981 if (TI->getOpcode() == Instruction::Sub &&
8982 FI->getOpcode() == Instruction::Add) {
8983 AddOp = FI; SubOp = TI;
8984 } else if (FI->getOpcode() == Instruction::Sub &&
8985 TI->getOpcode() == Instruction::Add) {
8986 AddOp = TI; SubOp = FI;
8987 }
8988
8989 if (AddOp) {
8990 Value *OtherAddOp = 0;
8991 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
8992 OtherAddOp = AddOp->getOperand(1);
8993 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
8994 OtherAddOp = AddOp->getOperand(0);
8995 }
8996
8997 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00008998 // So at this point we know we have (Y -> OtherAddOp):
8999 // select C, (add X, Y), (sub X, Z)
9000 Value *NegVal; // Compute -Z
9001 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
9002 NegVal = ConstantExpr::getNeg(C);
9003 } else {
9004 NegVal = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009005 BinaryOperator::CreateNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00009006 }
Chris Lattner97f37a42006-02-24 18:05:58 +00009007
9008 Value *NewTrueOp = OtherAddOp;
9009 Value *NewFalseOp = NegVal;
9010 if (AddOp != TI)
9011 std::swap(NewTrueOp, NewFalseOp);
9012 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009013 SelectInst::Create(CondVal, NewTrueOp,
9014 NewFalseOp, SI.getName() + ".p");
Chris Lattner97f37a42006-02-24 18:05:58 +00009015
9016 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009017 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00009018 }
9019 }
9020 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009021
Chris Lattnere576b912004-04-09 23:46:01 +00009022 // See if we can fold the select into one of our operands.
Chris Lattner42a75512007-01-15 02:27:26 +00009023 if (SI.getType()->isInteger()) {
Chris Lattnere576b912004-04-09 23:46:01 +00009024 // See the comment above GetSelectFoldableOperands for a description of the
9025 // transformation we are doing here.
9026 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
9027 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9028 !isa<Constant>(FalseVal))
9029 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9030 unsigned OpToFold = 0;
9031 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9032 OpToFold = 1;
9033 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9034 OpToFold = 2;
9035 }
9036
9037 if (OpToFold) {
9038 Constant *C = GetSelectFoldableConstant(TVI);
Chris Lattnere576b912004-04-09 23:46:01 +00009039 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009040 SelectInst::Create(SI.getCondition(),
9041 TVI->getOperand(2-OpToFold), C);
Chris Lattnere576b912004-04-09 23:46:01 +00009042 InsertNewInstBefore(NewSel, SI);
Chris Lattner6934a042007-02-11 01:23:03 +00009043 NewSel->takeName(TVI);
Chris Lattnere576b912004-04-09 23:46:01 +00009044 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009045 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
Chris Lattnere576b912004-04-09 23:46:01 +00009046 else {
9047 assert(0 && "Unknown instruction!!");
9048 }
9049 }
9050 }
Chris Lattnera96879a2004-09-29 17:40:11 +00009051
Chris Lattnere576b912004-04-09 23:46:01 +00009052 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
9053 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9054 !isa<Constant>(TrueVal))
9055 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9056 unsigned OpToFold = 0;
9057 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9058 OpToFold = 1;
9059 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9060 OpToFold = 2;
9061 }
9062
9063 if (OpToFold) {
9064 Constant *C = GetSelectFoldableConstant(FVI);
Chris Lattnere576b912004-04-09 23:46:01 +00009065 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009066 SelectInst::Create(SI.getCondition(), C,
9067 FVI->getOperand(2-OpToFold));
Chris Lattnere576b912004-04-09 23:46:01 +00009068 InsertNewInstBefore(NewSel, SI);
Chris Lattner6934a042007-02-11 01:23:03 +00009069 NewSel->takeName(FVI);
Chris Lattnere576b912004-04-09 23:46:01 +00009070 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009071 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
Reid Spencer832254e2007-02-02 02:16:23 +00009072 else
Chris Lattnere576b912004-04-09 23:46:01 +00009073 assert(0 && "Unknown instruction!!");
Chris Lattnere576b912004-04-09 23:46:01 +00009074 }
9075 }
9076 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00009077
9078 if (BinaryOperator::isNot(CondVal)) {
9079 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9080 SI.setOperand(1, FalseVal);
9081 SI.setOperand(2, TrueVal);
9082 return &SI;
9083 }
9084
Chris Lattner3d69f462004-03-12 05:52:32 +00009085 return 0;
9086}
9087
Dan Gohmaneee962e2008-04-10 18:43:06 +00009088/// EnforceKnownAlignment - If the specified pointer points to an object that
9089/// we control, modify the object's alignment to PrefAlign. This isn't
9090/// often possible though. If alignment is important, a more reliable approach
9091/// is to simply align all global variables and allocation instructions to
9092/// their preferred alignment from the beginning.
9093///
9094static unsigned EnforceKnownAlignment(Value *V,
9095 unsigned Align, unsigned PrefAlign) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00009096
Dan Gohmaneee962e2008-04-10 18:43:06 +00009097 User *U = dyn_cast<User>(V);
9098 if (!U) return Align;
9099
9100 switch (getOpcode(U)) {
9101 default: break;
9102 case Instruction::BitCast:
9103 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9104 case Instruction::GetElementPtr: {
Chris Lattner95a959d2006-03-06 20:18:44 +00009105 // If all indexes are zero, it is just the alignment of the base pointer.
9106 bool AllZeroOperands = true;
Gabor Greif52ed3632008-06-12 21:51:29 +00009107 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
Gabor Greif177dd3f2008-06-12 21:37:33 +00009108 if (!isa<Constant>(*i) ||
9109 !cast<Constant>(*i)->isNullValue()) {
Chris Lattner95a959d2006-03-06 20:18:44 +00009110 AllZeroOperands = false;
9111 break;
9112 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00009113
9114 if (AllZeroOperands) {
9115 // Treat this like a bitcast.
Dan Gohmaneee962e2008-04-10 18:43:06 +00009116 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattnerf2369f22007-08-09 19:05:49 +00009117 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009118 break;
Chris Lattner95a959d2006-03-06 20:18:44 +00009119 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009120 }
9121
9122 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9123 // If there is a large requested alignment and we can, bump up the alignment
9124 // of the global.
9125 if (!GV->isDeclaration()) {
9126 GV->setAlignment(PrefAlign);
9127 Align = PrefAlign;
9128 }
9129 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
9130 // If there is a requested alignment and if this is an alloca, round up. We
9131 // don't do this for malloc, because some systems can't respect the request.
9132 if (isa<AllocaInst>(AI)) {
9133 AI->setAlignment(PrefAlign);
9134 Align = PrefAlign;
9135 }
9136 }
9137
9138 return Align;
9139}
9140
9141/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9142/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
9143/// and it is more than the alignment of the ultimate object, see if we can
9144/// increase the alignment of the ultimate object, making this check succeed.
9145unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9146 unsigned PrefAlign) {
9147 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9148 sizeof(PrefAlign) * CHAR_BIT;
9149 APInt Mask = APInt::getAllOnesValue(BitWidth);
9150 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9151 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9152 unsigned TrailZ = KnownZero.countTrailingOnes();
9153 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9154
9155 if (PrefAlign > Align)
9156 Align = EnforceKnownAlignment(V, Align, PrefAlign);
9157
9158 // We don't need to make any adjustment.
9159 return Align;
Chris Lattner95a959d2006-03-06 20:18:44 +00009160}
9161
Chris Lattnerf497b022008-01-13 23:50:23 +00009162Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00009163 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
9164 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattnerf497b022008-01-13 23:50:23 +00009165 unsigned MinAlign = std::min(DstAlign, SrcAlign);
9166 unsigned CopyAlign = MI->getAlignment()->getZExtValue();
9167
9168 if (CopyAlign < MinAlign) {
9169 MI->setAlignment(ConstantInt::get(Type::Int32Ty, MinAlign));
9170 return MI;
9171 }
9172
9173 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9174 // load/store.
9175 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9176 if (MemOpLength == 0) return 0;
9177
Chris Lattner37ac6082008-01-14 00:28:35 +00009178 // Source and destination pointer types are always "i8*" for intrinsic. See
9179 // if the size is something we can handle with a single primitive load/store.
9180 // A single load+store correctly handles overlapping memory in the memmove
9181 // case.
Chris Lattnerf497b022008-01-13 23:50:23 +00009182 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner69ea9d22008-04-30 06:39:11 +00009183 if (Size == 0) return MI; // Delete this mem transfer.
9184
9185 if (Size > 8 || (Size&(Size-1)))
Chris Lattner37ac6082008-01-14 00:28:35 +00009186 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattnerf497b022008-01-13 23:50:23 +00009187
Chris Lattner37ac6082008-01-14 00:28:35 +00009188 // Use an integer load+store unless we can find something better.
Chris Lattnerf497b022008-01-13 23:50:23 +00009189 Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
Chris Lattner37ac6082008-01-14 00:28:35 +00009190
9191 // Memcpy forces the use of i8* for the source and destination. That means
9192 // that if you're using memcpy to move one double around, you'll get a cast
9193 // from double* to i8*. We'd much rather use a double load+store rather than
9194 // an i64 load+store, here because this improves the odds that the source or
9195 // dest address will be promotable. See if we can find a better type than the
9196 // integer datatype.
9197 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9198 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9199 if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9200 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
9201 // down through these levels if so.
Dan Gohman8f8e2692008-05-23 01:52:21 +00009202 while (!SrcETy->isSingleValueType()) {
Chris Lattner37ac6082008-01-14 00:28:35 +00009203 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9204 if (STy->getNumElements() == 1)
9205 SrcETy = STy->getElementType(0);
9206 else
9207 break;
9208 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9209 if (ATy->getNumElements() == 1)
9210 SrcETy = ATy->getElementType();
9211 else
9212 break;
9213 } else
9214 break;
9215 }
9216
Dan Gohman8f8e2692008-05-23 01:52:21 +00009217 if (SrcETy->isSingleValueType())
Chris Lattner37ac6082008-01-14 00:28:35 +00009218 NewPtrTy = PointerType::getUnqual(SrcETy);
9219 }
9220 }
9221
9222
Chris Lattnerf497b022008-01-13 23:50:23 +00009223 // If the memcpy/memmove provides better alignment info than we can
9224 // infer, use it.
9225 SrcAlign = std::max(SrcAlign, CopyAlign);
9226 DstAlign = std::max(DstAlign, CopyAlign);
9227
9228 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
9229 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
Chris Lattner37ac6082008-01-14 00:28:35 +00009230 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9231 InsertNewInstBefore(L, *MI);
9232 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9233
9234 // Set the size of the copy to 0, it will be deleted on the next iteration.
9235 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
9236 return MI;
Chris Lattnerf497b022008-01-13 23:50:23 +00009237}
Chris Lattner3d69f462004-03-12 05:52:32 +00009238
Chris Lattner69ea9d22008-04-30 06:39:11 +00009239Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9240 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
9241 if (MI->getAlignment()->getZExtValue() < Alignment) {
9242 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
9243 return MI;
9244 }
9245
9246 // Extract the length and alignment and fill if they are constant.
9247 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9248 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9249 if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
9250 return 0;
9251 uint64_t Len = LenC->getZExtValue();
9252 Alignment = MI->getAlignment()->getZExtValue();
9253
9254 // If the length is zero, this is a no-op
9255 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9256
9257 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9258 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
9259 const Type *ITy = IntegerType::get(Len*8); // n=1 -> i8.
9260
9261 Value *Dest = MI->getDest();
9262 Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
9263
9264 // Alignment 0 is identity for alignment 1 for memset, but not store.
9265 if (Alignment == 0) Alignment = 1;
9266
9267 // Extract the fill value and store.
9268 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
9269 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill), Dest, false,
9270 Alignment), *MI);
9271
9272 // Set the size of the copy to 0, it will be deleted on the next iteration.
9273 MI->setLength(Constant::getNullValue(LenC->getType()));
9274 return MI;
9275 }
9276
9277 return 0;
9278}
9279
9280
Chris Lattner8b0ea312006-01-13 20:11:04 +00009281/// visitCallInst - CallInst simplification. This mostly only handles folding
9282/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
9283/// the heavy lifting.
9284///
Chris Lattner9fe38862003-06-19 17:00:31 +00009285Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattner8b0ea312006-01-13 20:11:04 +00009286 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9287 if (!II) return visitCallSite(&CI);
9288
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009289 // Intrinsics cannot occur in an invoke, so handle them here instead of in
9290 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00009291 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009292 bool Changed = false;
9293
9294 // memmove/cpy/set of zero bytes is a noop.
9295 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9296 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9297
Chris Lattner35b9e482004-10-12 04:52:52 +00009298 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +00009299 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009300 // Replace the instruction with just byte operations. We would
9301 // transform other cases to loads/stores, but we don't know if
9302 // alignment is sufficient.
9303 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009304 }
9305
Chris Lattner35b9e482004-10-12 04:52:52 +00009306 // If we have a memmove and the source operation is a constant global,
9307 // then the source and dest pointers can't alias, so we can change this
9308 // into a call to memcpy.
Chris Lattnerf497b022008-01-13 23:50:23 +00009309 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009310 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9311 if (GVSrc->isConstant()) {
9312 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner824b9582008-11-21 16:42:48 +00009313 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9314 const Type *Tys[1];
9315 Tys[0] = CI.getOperand(3)->getType();
9316 CI.setOperand(0,
9317 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
Chris Lattner35b9e482004-10-12 04:52:52 +00009318 Changed = true;
9319 }
Chris Lattnera935db82008-05-28 05:30:41 +00009320
9321 // memmove(x,x,size) -> noop.
9322 if (MMI->getSource() == MMI->getDest())
9323 return EraseInstFromFunction(CI);
Chris Lattner95a959d2006-03-06 20:18:44 +00009324 }
Chris Lattner35b9e482004-10-12 04:52:52 +00009325
Chris Lattner95a959d2006-03-06 20:18:44 +00009326 // If we can determine a pointer alignment that is bigger than currently
9327 // set, update the alignment.
9328 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
Chris Lattnerf497b022008-01-13 23:50:23 +00009329 if (Instruction *I = SimplifyMemTransfer(MI))
9330 return I;
Chris Lattner69ea9d22008-04-30 06:39:11 +00009331 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9332 if (Instruction *I = SimplifyMemSet(MSI))
9333 return I;
Chris Lattner95a959d2006-03-06 20:18:44 +00009334 }
9335
Chris Lattner8b0ea312006-01-13 20:11:04 +00009336 if (Changed) return II;
Chris Lattner0521e3c2008-06-18 04:33:20 +00009337 }
9338
9339 switch (II->getIntrinsicID()) {
9340 default: break;
9341 case Intrinsic::bswap:
9342 // bswap(bswap(x)) -> x
9343 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9344 if (Operand->getIntrinsicID() == Intrinsic::bswap)
9345 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9346 break;
9347 case Intrinsic::ppc_altivec_lvx:
9348 case Intrinsic::ppc_altivec_lvxl:
9349 case Intrinsic::x86_sse_loadu_ps:
9350 case Intrinsic::x86_sse2_loadu_pd:
9351 case Intrinsic::x86_sse2_loadu_dq:
9352 // Turn PPC lvx -> load if the pointer is known aligned.
9353 // Turn X86 loadups -> load if the pointer is known aligned.
9354 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9355 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
9356 PointerType::getUnqual(II->getType()),
9357 CI);
9358 return new LoadInst(Ptr);
Chris Lattner867b99f2006-10-05 06:55:50 +00009359 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009360 break;
9361 case Intrinsic::ppc_altivec_stvx:
9362 case Intrinsic::ppc_altivec_stvxl:
9363 // Turn stvx -> store if the pointer is known aligned.
9364 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9365 const Type *OpPtrTy =
9366 PointerType::getUnqual(II->getOperand(1)->getType());
9367 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
9368 return new StoreInst(II->getOperand(1), Ptr);
9369 }
9370 break;
9371 case Intrinsic::x86_sse_storeu_ps:
9372 case Intrinsic::x86_sse2_storeu_pd:
9373 case Intrinsic::x86_sse2_storeu_dq:
Chris Lattner0521e3c2008-06-18 04:33:20 +00009374 // Turn X86 storeu -> store if the pointer is known aligned.
9375 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9376 const Type *OpPtrTy =
9377 PointerType::getUnqual(II->getOperand(2)->getType());
9378 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
9379 return new StoreInst(II->getOperand(2), Ptr);
9380 }
9381 break;
9382
9383 case Intrinsic::x86_sse_cvttss2si: {
9384 // These intrinsics only demands the 0th element of its input vector. If
9385 // we can simplify the input based on that, do so now.
9386 uint64_t UndefElts;
9387 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
9388 UndefElts)) {
9389 II->setOperand(1, V);
9390 return II;
9391 }
9392 break;
9393 }
9394
9395 case Intrinsic::ppc_altivec_vperm:
9396 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9397 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9398 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
Chris Lattner867b99f2006-10-05 06:55:50 +00009399
Chris Lattner0521e3c2008-06-18 04:33:20 +00009400 // Check that all of the elements are integer constants or undefs.
9401 bool AllEltsOk = true;
9402 for (unsigned i = 0; i != 16; ++i) {
9403 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
9404 !isa<UndefValue>(Mask->getOperand(i))) {
9405 AllEltsOk = false;
9406 break;
9407 }
9408 }
9409
9410 if (AllEltsOk) {
9411 // Cast the input vectors to byte vectors.
9412 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
9413 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
9414 Value *Result = UndefValue::get(Op0->getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00009415
Chris Lattner0521e3c2008-06-18 04:33:20 +00009416 // Only extract each element once.
9417 Value *ExtractedElts[32];
9418 memset(ExtractedElts, 0, sizeof(ExtractedElts));
9419
Chris Lattnere2ed0572006-04-06 19:19:17 +00009420 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0521e3c2008-06-18 04:33:20 +00009421 if (isa<UndefValue>(Mask->getOperand(i)))
9422 continue;
9423 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9424 Idx &= 31; // Match the hardware behavior.
9425
9426 if (ExtractedElts[Idx] == 0) {
9427 Instruction *Elt =
9428 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
9429 InsertNewInstBefore(Elt, CI);
9430 ExtractedElts[Idx] = Elt;
Chris Lattnere2ed0572006-04-06 19:19:17 +00009431 }
Chris Lattnere2ed0572006-04-06 19:19:17 +00009432
Chris Lattner0521e3c2008-06-18 04:33:20 +00009433 // Insert this value into the result vector.
9434 Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
9435 i, "tmp");
9436 InsertNewInstBefore(cast<Instruction>(Result), CI);
Chris Lattnere2ed0572006-04-06 19:19:17 +00009437 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009438 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00009439 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009440 }
9441 break;
Chris Lattnere2ed0572006-04-06 19:19:17 +00009442
Chris Lattner0521e3c2008-06-18 04:33:20 +00009443 case Intrinsic::stackrestore: {
9444 // If the save is right next to the restore, remove the restore. This can
9445 // happen when variable allocas are DCE'd.
9446 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9447 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9448 BasicBlock::iterator BI = SS;
9449 if (&*++BI == II)
9450 return EraseInstFromFunction(CI);
Chris Lattnera728ddc2006-01-13 21:28:09 +00009451 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009452 }
9453
9454 // Scan down this block to see if there is another stack restore in the
9455 // same block without an intervening call/alloca.
9456 BasicBlock::iterator BI = II;
9457 TerminatorInst *TI = II->getParent()->getTerminator();
9458 bool CannotRemove = false;
9459 for (++BI; &*BI != TI; ++BI) {
9460 if (isa<AllocaInst>(BI)) {
9461 CannotRemove = true;
9462 break;
9463 }
Chris Lattneraa0bf522008-06-25 05:59:28 +00009464 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
9465 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
9466 // If there is a stackrestore below this one, remove this one.
9467 if (II->getIntrinsicID() == Intrinsic::stackrestore)
9468 return EraseInstFromFunction(CI);
9469 // Otherwise, ignore the intrinsic.
9470 } else {
9471 // If we found a non-intrinsic call, we can't remove the stack
9472 // restore.
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00009473 CannotRemove = true;
9474 break;
9475 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009476 }
Chris Lattnera728ddc2006-01-13 21:28:09 +00009477 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009478
9479 // If the stack restore is in a return/unwind block and if there are no
9480 // allocas or calls between the restore and the return, nuke the restore.
9481 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
9482 return EraseInstFromFunction(CI);
9483 break;
9484 }
Chris Lattner35b9e482004-10-12 04:52:52 +00009485 }
9486
Chris Lattner8b0ea312006-01-13 20:11:04 +00009487 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +00009488}
9489
9490// InvokeInst simplification
9491//
9492Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +00009493 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +00009494}
9495
Dale Johannesenda30ccb2008-04-25 21:16:07 +00009496/// isSafeToEliminateVarargsCast - If this cast does not affect the value
9497/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen1f530a52008-04-23 18:34:37 +00009498static bool isSafeToEliminateVarargsCast(const CallSite CS,
9499 const CastInst * const CI,
9500 const TargetData * const TD,
9501 const int ix) {
9502 if (!CI->isLosslessCast())
9503 return false;
9504
9505 // The size of ByVal arguments is derived from the type, so we
9506 // can't change to a type with a different size. If the size were
9507 // passed explicitly we could avoid this check.
Devang Patel05988662008-09-25 21:00:45 +00009508 if (!CS.paramHasAttr(ix, Attribute::ByVal))
Dale Johannesen1f530a52008-04-23 18:34:37 +00009509 return true;
9510
9511 const Type* SrcTy =
9512 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
9513 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
9514 if (!SrcTy->isSized() || !DstTy->isSized())
9515 return false;
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00009516 if (TD->getTypePaddedSize(SrcTy) != TD->getTypePaddedSize(DstTy))
Dale Johannesen1f530a52008-04-23 18:34:37 +00009517 return false;
9518 return true;
9519}
9520
Chris Lattnera44d8a22003-10-07 22:32:43 +00009521// visitCallSite - Improvements for call and invoke instructions.
9522//
9523Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +00009524 bool Changed = false;
9525
9526 // If the callee is a constexpr cast of a function, attempt to move the cast
9527 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +00009528 if (transformConstExprCastCall(CS)) return 0;
9529
Chris Lattner6c266db2003-10-07 22:54:13 +00009530 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +00009531
Chris Lattner08b22ec2005-05-13 07:09:09 +00009532 if (Function *CalleeF = dyn_cast<Function>(Callee))
9533 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
9534 Instruction *OldCall = CS.getInstruction();
9535 // If the call and callee calling conventions don't match, this call must
9536 // be unreachable, as the call is undefined.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009537 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009538 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
9539 OldCall);
Chris Lattner08b22ec2005-05-13 07:09:09 +00009540 if (!OldCall->use_empty())
9541 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
9542 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
9543 return EraseInstFromFunction(*OldCall);
9544 return 0;
9545 }
9546
Chris Lattner17be6352004-10-18 02:59:09 +00009547 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
9548 // This instruction is not reachable, just remove it. We insert a store to
9549 // undef so that we know that this code is not reachable, despite the fact
9550 // that we can't modify the CFG here.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009551 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009552 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
Chris Lattner17be6352004-10-18 02:59:09 +00009553 CS.getInstruction());
9554
9555 if (!CS.getInstruction()->use_empty())
9556 CS.getInstruction()->
9557 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
9558
9559 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
9560 // Don't break the CFG, insert a dummy cond branch.
Gabor Greif051a9502008-04-06 20:25:17 +00009561 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
9562 ConstantInt::getTrue(), II);
Chris Lattnere87597f2004-10-16 18:11:37 +00009563 }
Chris Lattner17be6352004-10-18 02:59:09 +00009564 return EraseInstFromFunction(*CS.getInstruction());
9565 }
Chris Lattnere87597f2004-10-16 18:11:37 +00009566
Duncan Sandscdb6d922007-09-17 10:26:40 +00009567 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
9568 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
9569 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
9570 return transformCallThroughTrampoline(CS);
9571
Chris Lattner6c266db2003-10-07 22:54:13 +00009572 const PointerType *PTy = cast<PointerType>(Callee->getType());
9573 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
9574 if (FTy->isVarArg()) {
Dale Johannesen63e7eb42008-04-23 01:03:05 +00009575 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Chris Lattner6c266db2003-10-07 22:54:13 +00009576 // See if we can optimize any arguments passed through the varargs area of
9577 // the call.
9578 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen1f530a52008-04-23 18:34:37 +00009579 E = CS.arg_end(); I != E; ++I, ++ix) {
9580 CastInst *CI = dyn_cast<CastInst>(*I);
9581 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
9582 *I = CI->getOperand(0);
9583 Changed = true;
Chris Lattner6c266db2003-10-07 22:54:13 +00009584 }
Dale Johannesen1f530a52008-04-23 18:34:37 +00009585 }
Chris Lattner6c266db2003-10-07 22:54:13 +00009586 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009587
Duncan Sandsf0c33542007-12-19 21:13:37 +00009588 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sandsece2c042007-12-16 15:51:49 +00009589 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsf0c33542007-12-19 21:13:37 +00009590 CS.setDoesNotThrow();
Duncan Sandsece2c042007-12-16 15:51:49 +00009591 Changed = true;
9592 }
9593
Chris Lattner6c266db2003-10-07 22:54:13 +00009594 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +00009595}
9596
Chris Lattner9fe38862003-06-19 17:00:31 +00009597// transformConstExprCastCall - If the callee is a constexpr cast of a function,
9598// attempt to move the cast to the arguments of the call/invoke.
9599//
9600bool InstCombiner::transformConstExprCastCall(CallSite CS) {
9601 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
9602 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +00009603 if (CE->getOpcode() != Instruction::BitCast ||
9604 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +00009605 return false;
Reid Spencer8863f182004-07-18 00:38:32 +00009606 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +00009607 Instruction *Caller = CS.getInstruction();
Devang Patel05988662008-09-25 21:00:45 +00009608 const AttrListPtr &CallerPAL = CS.getAttributes();
Chris Lattner9fe38862003-06-19 17:00:31 +00009609
9610 // Okay, this is a cast from a function to a different type. Unless doing so
9611 // would cause a type conversion of one of our arguments, change this call to
9612 // be a direct call with arguments casted to the appropriate types.
9613 //
9614 const FunctionType *FT = Callee->getFunctionType();
9615 const Type *OldRetTy = Caller->getType();
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009616 const Type *NewRetTy = FT->getReturnType();
Chris Lattner9fe38862003-06-19 17:00:31 +00009617
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009618 if (isa<StructType>(NewRetTy))
Devang Patel75e6f022008-03-11 18:04:06 +00009619 return false; // TODO: Handle multiple return values.
9620
Chris Lattnerf78616b2004-01-14 06:06:08 +00009621 // Check to see if we are changing the return type...
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009622 if (OldRetTy != NewRetTy) {
Bill Wendlinga6c31122008-05-14 22:45:20 +00009623 if (Callee->isDeclaration() &&
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009624 // Conversion is ok if changing from one pointer type to another or from
9625 // a pointer to an integer of the same size.
9626 !((isa<PointerType>(OldRetTy) || OldRetTy == TD->getIntPtrType()) &&
Duncan Sands34b176a2008-06-17 15:55:30 +00009627 (isa<PointerType>(NewRetTy) || NewRetTy == TD->getIntPtrType())))
Chris Lattnerec479922007-01-06 02:09:32 +00009628 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +00009629
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009630 if (!Caller->use_empty() &&
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009631 // void -> non-void is handled specially
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009632 NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009633 return false; // Cannot transform this return value.
9634
Chris Lattner58d74912008-03-12 17:45:29 +00009635 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Devang Patel19c87462008-09-26 22:53:05 +00009636 Attributes RAttrs = CallerPAL.getRetAttributes();
Devang Patel05988662008-09-25 21:00:45 +00009637 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
Duncan Sands6c3470e2008-01-07 17:16:06 +00009638 return false; // Attribute not compatible with transformed value.
9639 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009640
Chris Lattnerf78616b2004-01-14 06:06:08 +00009641 // If the callsite is an invoke instruction, and the return value is used by
9642 // a PHI node in a successor, we cannot change the return type of the call
9643 // because there is no place to put the cast instruction (without breaking
9644 // the critical edge). Bail out in this case.
9645 if (!Caller->use_empty())
9646 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
9647 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
9648 UI != E; ++UI)
9649 if (PHINode *PN = dyn_cast<PHINode>(*UI))
9650 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00009651 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +00009652 return false;
9653 }
Chris Lattner9fe38862003-06-19 17:00:31 +00009654
9655 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
9656 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +00009657
Chris Lattner9fe38862003-06-19 17:00:31 +00009658 CallSite::arg_iterator AI = CS.arg_begin();
9659 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
9660 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +00009661 const Type *ActTy = (*AI)->getType();
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009662
9663 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009664 return false; // Cannot transform this parameter value.
9665
Devang Patel19c87462008-09-26 22:53:05 +00009666 if (CallerPAL.getParamAttributes(i + 1)
9667 & Attribute::typeIncompatible(ParamTy))
Chris Lattner58d74912008-03-12 17:45:29 +00009668 return false; // Attribute not compatible with transformed value.
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009669
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009670 // Converting from one pointer type to another or between a pointer and an
9671 // integer of the same size is safe even if we do not have a body.
Chris Lattnerec479922007-01-06 02:09:32 +00009672 bool isConvertible = ActTy == ParamTy ||
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009673 ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
9674 (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType()));
Reid Spencer5cbf9852007-01-30 20:08:39 +00009675 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +00009676 }
9677
9678 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +00009679 Callee->isDeclaration())
Chris Lattner58d74912008-03-12 17:45:29 +00009680 return false; // Do not delete arguments unless we have a function body.
Chris Lattner9fe38862003-06-19 17:00:31 +00009681
Chris Lattner58d74912008-03-12 17:45:29 +00009682 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
9683 !CallerPAL.isEmpty())
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009684 // In this case we have more arguments than the new function type, but we
Duncan Sandse1e520f2008-01-13 08:02:44 +00009685 // won't be dropping them. Check that these extra arguments have attributes
9686 // that are compatible with being a vararg call argument.
Chris Lattner58d74912008-03-12 17:45:29 +00009687 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
9688 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sandse1e520f2008-01-13 08:02:44 +00009689 break;
Devang Pateleaf42ab2008-09-23 23:03:40 +00009690 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Devang Patel05988662008-09-25 21:00:45 +00009691 if (PAttrs & Attribute::VarArgsIncompatible)
Duncan Sandse1e520f2008-01-13 08:02:44 +00009692 return false;
9693 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009694
Chris Lattner9fe38862003-06-19 17:00:31 +00009695 // Okay, we decided that this is a safe thing to do: go ahead and start
9696 // inserting cast instructions as necessary...
9697 std::vector<Value*> Args;
9698 Args.reserve(NumActualArgs);
Devang Patel05988662008-09-25 21:00:45 +00009699 SmallVector<AttributeWithIndex, 8> attrVec;
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009700 attrVec.reserve(NumCommonArgs);
9701
9702 // Get any return attributes.
Devang Patel19c87462008-09-26 22:53:05 +00009703 Attributes RAttrs = CallerPAL.getRetAttributes();
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009704
9705 // If the return value is not being used, the type may not be compatible
9706 // with the existing attributes. Wipe out any problematic attributes.
Devang Patel05988662008-09-25 21:00:45 +00009707 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009708
9709 // Add the new return attributes.
9710 if (RAttrs)
Devang Patel05988662008-09-25 21:00:45 +00009711 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +00009712
9713 AI = CS.arg_begin();
9714 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
9715 const Type *ParamTy = FT->getParamType(i);
9716 if ((*AI)->getType() == ParamTy) {
9717 Args.push_back(*AI);
9718 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +00009719 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +00009720 false, ParamTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009721 CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
Reid Spencer3da59db2006-11-27 01:05:10 +00009722 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner9fe38862003-06-19 17:00:31 +00009723 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009724
9725 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +00009726 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +00009727 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +00009728 }
9729
9730 // If the function takes more arguments than the call was taking, add them
9731 // now...
9732 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
9733 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
9734
9735 // If we are removing arguments to the function, emit an obnoxious warning...
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009736 if (FT->getNumParams() < NumActualArgs) {
Chris Lattner9fe38862003-06-19 17:00:31 +00009737 if (!FT->isVarArg()) {
Bill Wendlinge8156192006-12-07 01:30:32 +00009738 cerr << "WARNING: While resolving call to function '"
9739 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +00009740 } else {
9741 // Add all of the arguments in their promoted form to the arg list...
9742 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
9743 const Type *PTy = getPromotedType((*AI)->getType());
9744 if (PTy != (*AI)->getType()) {
9745 // Must promote to pass through va_arg area!
Reid Spencerc5b206b2006-12-31 05:48:39 +00009746 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
9747 PTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009748 Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
Chris Lattner9fe38862003-06-19 17:00:31 +00009749 InsertNewInstBefore(Cast, *Caller);
9750 Args.push_back(Cast);
9751 } else {
9752 Args.push_back(*AI);
9753 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009754
Duncan Sandse1e520f2008-01-13 08:02:44 +00009755 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +00009756 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +00009757 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Duncan Sandse1e520f2008-01-13 08:02:44 +00009758 }
Chris Lattner9fe38862003-06-19 17:00:31 +00009759 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009760 }
Chris Lattner9fe38862003-06-19 17:00:31 +00009761
Devang Patel19c87462008-09-26 22:53:05 +00009762 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
9763 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
9764
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009765 if (NewRetTy == Type::VoidTy)
Chris Lattner6934a042007-02-11 01:23:03 +00009766 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +00009767
Devang Patel05988662008-09-25 21:00:45 +00009768 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),attrVec.end());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009769
Chris Lattner9fe38862003-06-19 17:00:31 +00009770 Instruction *NC;
9771 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +00009772 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009773 Args.begin(), Args.end(),
9774 Caller->getName(), Caller);
Reid Spencered3fa852007-07-30 19:53:57 +00009775 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +00009776 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +00009777 } else {
Gabor Greif051a9502008-04-06 20:25:17 +00009778 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
9779 Caller->getName(), Caller);
Duncan Sandsdc024672007-11-27 13:23:08 +00009780 CallInst *CI = cast<CallInst>(Caller);
9781 if (CI->isTailCall())
Chris Lattnera9e92112005-05-06 06:48:21 +00009782 cast<CallInst>(NC)->setTailCall();
Duncan Sandsdc024672007-11-27 13:23:08 +00009783 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +00009784 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +00009785 }
9786
Chris Lattner6934a042007-02-11 01:23:03 +00009787 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +00009788 Value *NV = NC;
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009789 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Chris Lattner9fe38862003-06-19 17:00:31 +00009790 if (NV->getType() != Type::VoidTy) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00009791 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009792 OldRetTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009793 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +00009794
9795 // If this is an invoke instruction, we should insert it after the first
9796 // non-phi, instruction in the normal successor block.
9797 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman02dea8b2008-05-23 21:05:58 +00009798 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Chris Lattnerbb609042003-10-30 00:46:41 +00009799 InsertNewInstBefore(NC, *I);
9800 } else {
9801 // Otherwise, it's a call, just insert cast right after the call instr
9802 InsertNewInstBefore(NC, *Caller);
9803 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009804 AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00009805 } else {
Chris Lattnerc30bda72004-10-17 21:22:38 +00009806 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +00009807 }
9808 }
9809
9810 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9811 Caller->replaceAllUsesWith(NV);
Chris Lattnerf22a5c62007-03-02 19:59:19 +00009812 Caller->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +00009813 RemoveFromWorkList(Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00009814 return true;
9815}
9816
Duncan Sandscdb6d922007-09-17 10:26:40 +00009817// transformCallThroughTrampoline - Turn a call to a function created by the
9818// init_trampoline intrinsic into a direct call to the underlying function.
9819//
9820Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
9821 Value *Callee = CS.getCalledValue();
9822 const PointerType *PTy = cast<PointerType>(Callee->getType());
9823 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Devang Patel05988662008-09-25 21:00:45 +00009824 const AttrListPtr &Attrs = CS.getAttributes();
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009825
9826 // If the call already has the 'nest' attribute somewhere then give up -
9827 // otherwise 'nest' would occur twice after splicing in the chain.
Devang Patel05988662008-09-25 21:00:45 +00009828 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009829 return 0;
Duncan Sandscdb6d922007-09-17 10:26:40 +00009830
9831 IntrinsicInst *Tramp =
9832 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
9833
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +00009834 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sandscdb6d922007-09-17 10:26:40 +00009835 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
9836 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
9837
Devang Patel05988662008-09-25 21:00:45 +00009838 const AttrListPtr &NestAttrs = NestF->getAttributes();
Chris Lattner58d74912008-03-12 17:45:29 +00009839 if (!NestAttrs.isEmpty()) {
Duncan Sandscdb6d922007-09-17 10:26:40 +00009840 unsigned NestIdx = 1;
9841 const Type *NestTy = 0;
Devang Patel05988662008-09-25 21:00:45 +00009842 Attributes NestAttr = Attribute::None;
Duncan Sandscdb6d922007-09-17 10:26:40 +00009843
9844 // Look for a parameter marked with the 'nest' attribute.
9845 for (FunctionType::param_iterator I = NestFTy->param_begin(),
9846 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Devang Patel05988662008-09-25 21:00:45 +00009847 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
Duncan Sandscdb6d922007-09-17 10:26:40 +00009848 // Record the parameter type and any other attributes.
9849 NestTy = *I;
Devang Patel19c87462008-09-26 22:53:05 +00009850 NestAttr = NestAttrs.getParamAttributes(NestIdx);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009851 break;
9852 }
9853
9854 if (NestTy) {
9855 Instruction *Caller = CS.getInstruction();
9856 std::vector<Value*> NewArgs;
9857 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
9858
Devang Patel05988662008-09-25 21:00:45 +00009859 SmallVector<AttributeWithIndex, 8> NewAttrs;
Chris Lattner58d74912008-03-12 17:45:29 +00009860 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009861
Duncan Sandscdb6d922007-09-17 10:26:40 +00009862 // Insert the nest argument into the call argument list, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009863 // mean appending it. Likewise for attributes.
9864
Devang Patel19c87462008-09-26 22:53:05 +00009865 // Add any result attributes.
9866 if (Attributes Attr = Attrs.getRetAttributes())
Devang Patel05988662008-09-25 21:00:45 +00009867 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009868
Duncan Sandscdb6d922007-09-17 10:26:40 +00009869 {
9870 unsigned Idx = 1;
9871 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
9872 do {
9873 if (Idx == NestIdx) {
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009874 // Add the chain argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009875 Value *NestVal = Tramp->getOperand(3);
9876 if (NestVal->getType() != NestTy)
9877 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
9878 NewArgs.push_back(NestVal);
Devang Patel05988662008-09-25 21:00:45 +00009879 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
Duncan Sandscdb6d922007-09-17 10:26:40 +00009880 }
9881
9882 if (I == E)
9883 break;
9884
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009885 // Add the original argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009886 NewArgs.push_back(*I);
Devang Patel19c87462008-09-26 22:53:05 +00009887 if (Attributes Attr = Attrs.getParamAttributes(Idx))
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009888 NewAttrs.push_back
Devang Patel05988662008-09-25 21:00:45 +00009889 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sandscdb6d922007-09-17 10:26:40 +00009890
9891 ++Idx, ++I;
9892 } while (1);
9893 }
9894
Devang Patel19c87462008-09-26 22:53:05 +00009895 // Add any function attributes.
9896 if (Attributes Attr = Attrs.getFnAttributes())
9897 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
9898
Duncan Sandscdb6d922007-09-17 10:26:40 +00009899 // The trampoline may have been bitcast to a bogus type (FTy).
9900 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009901 // with the chain parameter inserted.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009902
Duncan Sandscdb6d922007-09-17 10:26:40 +00009903 std::vector<const Type*> NewTypes;
Duncan Sandscdb6d922007-09-17 10:26:40 +00009904 NewTypes.reserve(FTy->getNumParams()+1);
9905
Duncan Sandscdb6d922007-09-17 10:26:40 +00009906 // Insert the chain's type into the list of parameter types, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009907 // mean appending it.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009908 {
9909 unsigned Idx = 1;
9910 FunctionType::param_iterator I = FTy->param_begin(),
9911 E = FTy->param_end();
9912
9913 do {
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009914 if (Idx == NestIdx)
9915 // Add the chain's type.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009916 NewTypes.push_back(NestTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009917
9918 if (I == E)
9919 break;
9920
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009921 // Add the original type.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009922 NewTypes.push_back(*I);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009923
9924 ++Idx, ++I;
9925 } while (1);
9926 }
9927
9928 // Replace the trampoline call with a direct call. Let the generic
9929 // code sort out any function type mismatches.
9930 FunctionType *NewFTy =
Duncan Sandsdc024672007-11-27 13:23:08 +00009931 FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009932 Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
9933 NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
Devang Patel05988662008-09-25 21:00:45 +00009934 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),NewAttrs.end());
Duncan Sandscdb6d922007-09-17 10:26:40 +00009935
9936 Instruction *NewCaller;
9937 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +00009938 NewCaller = InvokeInst::Create(NewCallee,
9939 II->getNormalDest(), II->getUnwindDest(),
9940 NewArgs.begin(), NewArgs.end(),
9941 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009942 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +00009943 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009944 } else {
Gabor Greif051a9502008-04-06 20:25:17 +00009945 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
9946 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009947 if (cast<CallInst>(Caller)->isTailCall())
9948 cast<CallInst>(NewCaller)->setTailCall();
9949 cast<CallInst>(NewCaller)->
9950 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +00009951 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009952 }
9953 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9954 Caller->replaceAllUsesWith(NewCaller);
9955 Caller->eraseFromParent();
9956 RemoveFromWorkList(Caller);
9957 return 0;
9958 }
9959 }
9960
9961 // Replace the trampoline call with a direct call. Since there is no 'nest'
9962 // parameter, there is no need to adjust the argument list. Let the generic
9963 // code sort out any function type mismatches.
9964 Constant *NewCallee =
9965 NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
9966 CS.setCalledFunction(NewCallee);
9967 return CS.getInstruction();
9968}
9969
Chris Lattner7da52b22006-11-01 04:51:18 +00009970/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
9971/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
9972/// and a single binop.
9973Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
9974 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Chris Lattner38b3dcc2008-12-01 03:42:51 +00009975 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
Chris Lattner7da52b22006-11-01 04:51:18 +00009976 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009977 Value *LHSVal = FirstInst->getOperand(0);
9978 Value *RHSVal = FirstInst->getOperand(1);
9979
9980 const Type *LHSType = LHSVal->getType();
9981 const Type *RHSType = RHSVal->getType();
Chris Lattner7da52b22006-11-01 04:51:18 +00009982
9983 // Scan to see if all operands are the same opcode, all have one use, and all
9984 // kill their operands (i.e. the operands have one use).
Chris Lattner05f18922008-12-01 02:34:36 +00009985 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
Chris Lattner7da52b22006-11-01 04:51:18 +00009986 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnera90a24c2006-11-01 04:55:47 +00009987 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00009988 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattner9c080502006-11-01 07:43:41 +00009989 // types or GEP's with different index types.
9990 I->getOperand(0)->getType() != LHSType ||
9991 I->getOperand(1)->getType() != RHSType)
Chris Lattner7da52b22006-11-01 04:51:18 +00009992 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +00009993
9994 // If they are CmpInst instructions, check their predicates
9995 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
9996 if (cast<CmpInst>(I)->getPredicate() !=
9997 cast<CmpInst>(FirstInst)->getPredicate())
9998 return 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009999
10000 // Keep track of which operand needs a phi node.
10001 if (I->getOperand(0) != LHSVal) LHSVal = 0;
10002 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattner7da52b22006-11-01 04:51:18 +000010003 }
10004
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010005 // Otherwise, this is safe to transform!
Chris Lattner53738a42006-11-08 19:42:28 +000010006
Chris Lattner7da52b22006-11-01 04:51:18 +000010007 Value *InLHS = FirstInst->getOperand(0);
Chris Lattner7da52b22006-11-01 04:51:18 +000010008 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner53738a42006-11-08 19:42:28 +000010009 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010010 if (LHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010011 NewLHS = PHINode::Create(LHSType,
10012 FirstInst->getOperand(0)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010013 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10014 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010015 InsertNewInstBefore(NewLHS, PN);
10016 LHSVal = NewLHS;
10017 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010018
10019 if (RHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010020 NewRHS = PHINode::Create(RHSType,
10021 FirstInst->getOperand(1)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010022 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10023 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010024 InsertNewInstBefore(NewRHS, PN);
10025 RHSVal = NewRHS;
10026 }
10027
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010028 // Add all operands to the new PHIs.
Chris Lattner05f18922008-12-01 02:34:36 +000010029 if (NewLHS || NewRHS) {
10030 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10031 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10032 if (NewLHS) {
10033 Value *NewInLHS = InInst->getOperand(0);
10034 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10035 }
10036 if (NewRHS) {
10037 Value *NewInRHS = InInst->getOperand(1);
10038 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10039 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010040 }
10041 }
10042
Chris Lattner7da52b22006-11-01 04:51:18 +000010043 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010044 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010045 CmpInst *CIOp = cast<CmpInst>(FirstInst);
10046 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
10047 RHSVal);
Chris Lattner7da52b22006-11-01 04:51:18 +000010048}
10049
Chris Lattner05f18922008-12-01 02:34:36 +000010050Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10051 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10052
10053 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
10054 FirstInst->op_end());
10055
10056 // Scan to see if all operands are the same opcode, all have one use, and all
10057 // kill their operands (i.e. the operands have one use).
10058 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10059 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10060 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10061 GEP->getNumOperands() != FirstInst->getNumOperands())
10062 return 0;
10063
10064 // Compare the operand lists.
10065 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10066 if (FirstInst->getOperand(op) == GEP->getOperand(op))
10067 continue;
10068
10069 // Don't merge two GEPs when two operands differ (introducing phi nodes)
10070 // if one of the PHIs has a constant for the index. The index may be
10071 // substantially cheaper to compute for the constants, so making it a
10072 // variable index could pessimize the path. This also handles the case
10073 // for struct indices, which must always be constant.
10074 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10075 isa<ConstantInt>(GEP->getOperand(op)))
10076 return 0;
10077
10078 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10079 return 0;
10080 FixedOperands[op] = 0; // Needs a PHI.
10081 }
10082 }
10083
10084 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
10085 // that is variable.
10086 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10087
10088 bool HasAnyPHIs = false;
10089 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10090 if (FixedOperands[i]) continue; // operand doesn't need a phi.
10091 Value *FirstOp = FirstInst->getOperand(i);
10092 PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10093 FirstOp->getName()+".pn");
10094 InsertNewInstBefore(NewPN, PN);
10095
10096 NewPN->reserveOperandSpace(e);
10097 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10098 OperandPhis[i] = NewPN;
10099 FixedOperands[i] = NewPN;
10100 HasAnyPHIs = true;
10101 }
10102
10103
10104 // Add all operands to the new PHIs.
10105 if (HasAnyPHIs) {
10106 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10107 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10108 BasicBlock *InBB = PN.getIncomingBlock(i);
10109
10110 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10111 if (PHINode *OpPhi = OperandPhis[op])
10112 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10113 }
10114 }
10115
10116 Value *Base = FixedOperands[0];
10117 return GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10118 FixedOperands.end());
10119}
10120
10121
Chris Lattner76c73142006-11-01 07:13:54 +000010122/// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
10123/// of the block that defines it. This means that it must be obvious the value
10124/// of the load is not changed from the point of the load to the end of the
10125/// block it is in.
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010126///
10127/// Finally, it is safe, but not profitable, to sink a load targetting a
10128/// non-address-taken alloca. Doing so will cause us to not promote the alloca
10129/// to a register.
Chris Lattner76c73142006-11-01 07:13:54 +000010130static bool isSafeToSinkLoad(LoadInst *L) {
10131 BasicBlock::iterator BBI = L, E = L->getParent()->end();
10132
10133 for (++BBI; BBI != E; ++BBI)
10134 if (BBI->mayWriteToMemory())
10135 return false;
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010136
10137 // Check for non-address taken alloca. If not address-taken already, it isn't
10138 // profitable to do this xform.
10139 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10140 bool isAddressTaken = false;
10141 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10142 UI != E; ++UI) {
10143 if (isa<LoadInst>(UI)) continue;
10144 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10145 // If storing TO the alloca, then the address isn't taken.
10146 if (SI->getOperand(1) == AI) continue;
10147 }
10148 isAddressTaken = true;
10149 break;
10150 }
10151
10152 if (!isAddressTaken)
10153 return false;
10154 }
10155
Chris Lattner76c73142006-11-01 07:13:54 +000010156 return true;
10157}
10158
Chris Lattner9fe38862003-06-19 17:00:31 +000010159
Chris Lattnerbac32862004-11-14 19:13:23 +000010160// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10161// operator and they all are only used by the PHI, PHI together their
10162// inputs, and do the operation once, to the result of the PHI.
10163Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10164 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10165
10166 // Scan the instruction, looking for input operations that can be folded away.
10167 // If all input operands to the phi are the same instruction (e.g. a cast from
10168 // the same type or "+42") we can pull the operation through the PHI, reducing
10169 // code size and simplifying code.
10170 Constant *ConstantOp = 0;
10171 const Type *CastSrcTy = 0;
Chris Lattner76c73142006-11-01 07:13:54 +000010172 bool isVolatile = false;
Chris Lattnerbac32862004-11-14 19:13:23 +000010173 if (isa<CastInst>(FirstInst)) {
10174 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer832254e2007-02-02 02:16:23 +000010175 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000010176 // Can fold binop, compare or shift here if the RHS is a constant,
10177 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattnerbac32862004-11-14 19:13:23 +000010178 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattner7da52b22006-11-01 04:51:18 +000010179 if (ConstantOp == 0)
10180 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner76c73142006-11-01 07:13:54 +000010181 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10182 isVolatile = LI->isVolatile();
10183 // We can't sink the load if the loaded value could be modified between the
10184 // load and the PHI.
10185 if (LI->getParent() != PN.getIncomingBlock(0) ||
10186 !isSafeToSinkLoad(LI))
10187 return 0;
Chris Lattner71042962008-07-08 17:18:32 +000010188
10189 // If the PHI is of volatile loads and the load block has multiple
10190 // successors, sinking it would remove a load of the volatile value from
10191 // the path through the other successor.
10192 if (isVolatile &&
10193 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10194 return 0;
10195
Chris Lattner9c080502006-11-01 07:43:41 +000010196 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner05f18922008-12-01 02:34:36 +000010197 return FoldPHIArgGEPIntoPHI(PN);
Chris Lattnerbac32862004-11-14 19:13:23 +000010198 } else {
10199 return 0; // Cannot fold this operation.
10200 }
10201
10202 // Check to see if all arguments are the same operation.
10203 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10204 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10205 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencere4d87aa2006-12-23 06:05:41 +000010206 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattnerbac32862004-11-14 19:13:23 +000010207 return 0;
10208 if (CastSrcTy) {
10209 if (I->getOperand(0)->getType() != CastSrcTy)
10210 return 0; // Cast operation must match.
Chris Lattner76c73142006-11-01 07:13:54 +000010211 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000010212 // We can't sink the load if the loaded value could be modified between
10213 // the load and the PHI.
Chris Lattner76c73142006-11-01 07:13:54 +000010214 if (LI->isVolatile() != isVolatile ||
10215 LI->getParent() != PN.getIncomingBlock(i) ||
10216 !isSafeToSinkLoad(LI))
10217 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +000010218
Chris Lattner71042962008-07-08 17:18:32 +000010219 // If the PHI is of volatile loads and the load block has multiple
10220 // successors, sinking it would remove a load of the volatile value from
10221 // the path through the other successor.
Chris Lattner40700fe2008-04-29 17:28:22 +000010222 if (isVolatile &&
10223 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10224 return 0;
10225
10226
Chris Lattnerbac32862004-11-14 19:13:23 +000010227 } else if (I->getOperand(1) != ConstantOp) {
10228 return 0;
10229 }
10230 }
10231
10232 // Okay, they are all the same operation. Create a new PHI node of the
10233 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greif051a9502008-04-06 20:25:17 +000010234 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10235 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +000010236 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +000010237
10238 Value *InVal = FirstInst->getOperand(0);
10239 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +000010240
10241 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +000010242 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10243 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10244 if (NewInVal != InVal)
10245 InVal = 0;
10246 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10247 }
10248
10249 Value *PhiVal;
10250 if (InVal) {
10251 // The new PHI unions all of the same values together. This is really
10252 // common, so we handle it intelligently here for compile-time speed.
10253 PhiVal = InVal;
10254 delete NewPN;
10255 } else {
10256 InsertNewInstBefore(NewPN, PN);
10257 PhiVal = NewPN;
10258 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010259
Chris Lattnerbac32862004-11-14 19:13:23 +000010260 // Insert and return the new operation.
Reid Spencer3da59db2006-11-27 01:05:10 +000010261 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010262 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattner54545ac2008-04-29 17:13:43 +000010263 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010264 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +000010265 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010266 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +000010267 PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +000010268 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10269
10270 // If this was a volatile load that we are merging, make sure to loop through
10271 // and mark all the input loads as non-volatile. If we don't do this, we will
10272 // insert a new volatile load and the old ones will not be deletable.
10273 if (isVolatile)
10274 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10275 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10276
10277 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattnerbac32862004-11-14 19:13:23 +000010278}
Chris Lattnera1be5662002-05-02 17:06:02 +000010279
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010280/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10281/// that is dead.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010282static bool DeadPHICycle(PHINode *PN,
10283 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010284 if (PN->use_empty()) return true;
10285 if (!PN->hasOneUse()) return false;
10286
10287 // Remember this node, and if we find the cycle, return.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010288 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010289 return true;
Chris Lattner92103de2007-08-28 04:23:55 +000010290
10291 // Don't scan crazily complex things.
10292 if (PotentiallyDeadPHIs.size() == 16)
10293 return false;
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010294
10295 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10296 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +000010297
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010298 return false;
10299}
10300
Chris Lattnercf5008a2007-11-06 21:52:06 +000010301/// PHIsEqualValue - Return true if this phi node is always equal to
10302/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
10303/// z = some value; x = phi (y, z); y = phi (x, z)
10304static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
10305 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10306 // See if we already saw this PHI node.
10307 if (!ValueEqualPHIs.insert(PN))
10308 return true;
10309
10310 // Don't scan crazily complex things.
10311 if (ValueEqualPHIs.size() == 16)
10312 return false;
10313
10314 // Scan the operands to see if they are either phi nodes or are equal to
10315 // the value.
10316 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10317 Value *Op = PN->getIncomingValue(i);
10318 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10319 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10320 return false;
10321 } else if (Op != NonPhiInVal)
10322 return false;
10323 }
10324
10325 return true;
10326}
10327
10328
Chris Lattner473945d2002-05-06 18:06:38 +000010329// PHINode simplification
10330//
Chris Lattner7e708292002-06-25 16:13:24 +000010331Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +000010332 // If LCSSA is around, don't mess with Phi nodes
Chris Lattnerf964f322007-03-04 04:27:24 +000010333 if (MustPreserveLCSSA) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +000010334
Owen Anderson7e057142006-07-10 22:03:18 +000010335 if (Value *V = PN.hasConstantValue())
10336 return ReplaceInstUsesWith(PN, V);
10337
Owen Anderson7e057142006-07-10 22:03:18 +000010338 // If all PHI operands are the same operation, pull them through the PHI,
10339 // reducing code size.
10340 if (isa<Instruction>(PN.getIncomingValue(0)) &&
Chris Lattner05f18922008-12-01 02:34:36 +000010341 isa<Instruction>(PN.getIncomingValue(1)) &&
10342 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10343 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10344 // FIXME: The hasOneUse check will fail for PHIs that use the value more
10345 // than themselves more than once.
Owen Anderson7e057142006-07-10 22:03:18 +000010346 PN.getIncomingValue(0)->hasOneUse())
10347 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10348 return Result;
10349
10350 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
10351 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10352 // PHI)... break the cycle.
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010353 if (PN.hasOneUse()) {
10354 Instruction *PHIUser = cast<Instruction>(PN.use_back());
10355 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattner0e5444b2007-03-26 20:40:50 +000010356 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Anderson7e057142006-07-10 22:03:18 +000010357 PotentiallyDeadPHIs.insert(&PN);
10358 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
10359 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10360 }
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010361
10362 // If this phi has a single use, and if that use just computes a value for
10363 // the next iteration of a loop, delete the phi. This occurs with unused
10364 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
10365 // common case here is good because the only other things that catch this
10366 // are induction variable analysis (sometimes) and ADCE, which is only run
10367 // late.
10368 if (PHIUser->hasOneUse() &&
10369 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10370 PHIUser->use_back() == &PN) {
10371 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10372 }
10373 }
Owen Anderson7e057142006-07-10 22:03:18 +000010374
Chris Lattnercf5008a2007-11-06 21:52:06 +000010375 // We sometimes end up with phi cycles that non-obviously end up being the
10376 // same value, for example:
10377 // z = some value; x = phi (y, z); y = phi (x, z)
10378 // where the phi nodes don't necessarily need to be in the same block. Do a
10379 // quick check to see if the PHI node only contains a single non-phi value, if
10380 // so, scan to see if the phi cycle is actually equal to that value.
10381 {
10382 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10383 // Scan for the first non-phi operand.
10384 while (InValNo != NumOperandVals &&
10385 isa<PHINode>(PN.getIncomingValue(InValNo)))
10386 ++InValNo;
10387
10388 if (InValNo != NumOperandVals) {
10389 Value *NonPhiInVal = PN.getOperand(InValNo);
10390
10391 // Scan the rest of the operands to see if there are any conflicts, if so
10392 // there is no need to recursively scan other phis.
10393 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10394 Value *OpVal = PN.getIncomingValue(InValNo);
10395 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10396 break;
10397 }
10398
10399 // If we scanned over all operands, then we have one unique value plus
10400 // phi values. Scan PHI nodes to see if they all merge in each other or
10401 // the value.
10402 if (InValNo == NumOperandVals) {
10403 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10404 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10405 return ReplaceInstUsesWith(PN, NonPhiInVal);
10406 }
10407 }
10408 }
Chris Lattner60921c92003-12-19 05:58:40 +000010409 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +000010410}
10411
Reid Spencer17212df2006-12-12 09:18:51 +000010412static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
10413 Instruction *InsertPoint,
10414 InstCombiner *IC) {
Reid Spencerabaa8ca2007-01-08 16:32:00 +000010415 unsigned PtrSize = DTy->getPrimitiveSizeInBits();
10416 unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +000010417 // We must cast correctly to the pointer type. Ensure that we
10418 // sign extend the integer value if it is smaller as this is
10419 // used for address computation.
10420 Instruction::CastOps opcode =
10421 (VTySize < PtrSize ? Instruction::SExt :
10422 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
10423 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
Chris Lattner28977af2004-04-05 01:30:19 +000010424}
10425
Chris Lattnera1be5662002-05-02 17:06:02 +000010426
Chris Lattner7e708292002-06-25 16:13:24 +000010427Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +000010428 Value *PtrOp = GEP.getOperand(0);
Chris Lattner9bc14642007-04-28 00:57:34 +000010429 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
Chris Lattner7e708292002-06-25 16:13:24 +000010430 // If so, eliminate the noop.
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010431 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +000010432 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010433
Chris Lattnere87597f2004-10-16 18:11:37 +000010434 if (isa<UndefValue>(GEP.getOperand(0)))
10435 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
10436
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010437 bool HasZeroPointerIndex = false;
10438 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
10439 HasZeroPointerIndex = C->isNullValue();
10440
10441 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +000010442 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +000010443
Chris Lattner28977af2004-04-05 01:30:19 +000010444 // Eliminate unneeded casts for indices.
10445 bool MadeChange = false;
Chris Lattnerdb9654e2007-03-25 20:43:09 +000010446
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010447 gep_type_iterator GTI = gep_type_begin(GEP);
Gabor Greif177dd3f2008-06-12 21:37:33 +000010448 for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end();
10449 i != e; ++i, ++GTI) {
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010450 if (isa<SequentialType>(*GTI)) {
Gabor Greif177dd3f2008-06-12 21:37:33 +000010451 if (CastInst *CI = dyn_cast<CastInst>(*i)) {
Chris Lattner76b7a062007-01-15 07:02:54 +000010452 if (CI->getOpcode() == Instruction::ZExt ||
10453 CI->getOpcode() == Instruction::SExt) {
10454 const Type *SrcTy = CI->getOperand(0)->getType();
10455 // We can eliminate a cast from i32 to i64 iff the target
10456 // is a 32-bit pointer target.
10457 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
10458 MadeChange = true;
Gabor Greif177dd3f2008-06-12 21:37:33 +000010459 *i = CI->getOperand(0);
Chris Lattner28977af2004-04-05 01:30:19 +000010460 }
10461 }
10462 }
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010463 // If we are using a wider index than needed for this platform, shrink it
Dan Gohman4f833d42008-09-11 23:06:38 +000010464 // to what we need. If narrower, sign-extend it to what we need.
10465 // If the incoming value needs a cast instruction,
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010466 // insert it. This explicit cast can make subsequent optimizations more
10467 // obvious.
Gabor Greif177dd3f2008-06-12 21:37:33 +000010468 Value *Op = *i;
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010469 if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
Chris Lattner4f1134e2004-04-17 18:16:10 +000010470 if (Constant *C = dyn_cast<Constant>(Op)) {
Gabor Greif177dd3f2008-06-12 21:37:33 +000010471 *i = ConstantExpr::getTrunc(C, TD->getIntPtrType());
Chris Lattner4f1134e2004-04-17 18:16:10 +000010472 MadeChange = true;
10473 } else {
Reid Spencer17212df2006-12-12 09:18:51 +000010474 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
10475 GEP);
Gabor Greif177dd3f2008-06-12 21:37:33 +000010476 *i = Op;
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010477 MadeChange = true;
10478 }
Dan Gohman4f833d42008-09-11 23:06:38 +000010479 } else if (TD->getTypeSizeInBits(Op->getType()) < TD->getPointerSizeInBits()) {
10480 if (Constant *C = dyn_cast<Constant>(Op)) {
10481 *i = ConstantExpr::getSExt(C, TD->getIntPtrType());
10482 MadeChange = true;
10483 } else {
10484 Op = InsertCastBefore(Instruction::SExt, Op, TD->getIntPtrType(),
10485 GEP);
10486 *i = Op;
10487 MadeChange = true;
10488 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010489 }
Chris Lattner28977af2004-04-05 01:30:19 +000010490 }
Chris Lattnerdb9654e2007-03-25 20:43:09 +000010491 }
Chris Lattner28977af2004-04-05 01:30:19 +000010492 if (MadeChange) return &GEP;
10493
Chris Lattner90ac28c2002-08-02 19:29:35 +000010494 // Combine Indices - If the source pointer to this getelementptr instruction
10495 // is a getelementptr instruction, combine the indices of the two
10496 // getelementptr instructions into a single instruction.
10497 //
Chris Lattner72588fc2007-02-15 22:48:32 +000010498 SmallVector<Value*, 8> SrcGEPOperands;
Chris Lattner574da9b2005-01-13 20:14:25 +000010499 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner72588fc2007-02-15 22:48:32 +000010500 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
Chris Lattnerebd985c2004-03-25 22:59:29 +000010501
10502 if (!SrcGEPOperands.empty()) {
Chris Lattner620ce142004-05-07 22:09:22 +000010503 // Note that if our source is a gep chain itself that we wait for that
10504 // chain to be resolved before we perform this transformation. This
10505 // avoids us creating a TON of code in some cases.
10506 //
10507 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
10508 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
10509 return 0; // Wait until our source is folded to completion.
10510
Chris Lattner72588fc2007-02-15 22:48:32 +000010511 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +000010512
10513 // Find out whether the last index in the source GEP is a sequential idx.
10514 bool EndsWithSequential = false;
10515 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
10516 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +000010517 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000010518
Chris Lattner90ac28c2002-08-02 19:29:35 +000010519 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +000010520 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +000010521 // Replace: gep (gep %P, long B), long A, ...
10522 // With: T = long A+B; gep %P, T, ...
10523 //
Chris Lattner620ce142004-05-07 22:09:22 +000010524 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner28977af2004-04-05 01:30:19 +000010525 if (SO1 == Constant::getNullValue(SO1->getType())) {
10526 Sum = GO1;
10527 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
10528 Sum = SO1;
10529 } else {
10530 // If they aren't the same type, convert both to an integer of the
10531 // target's pointer size.
10532 if (SO1->getType() != GO1->getType()) {
10533 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +000010534 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +000010535 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +000010536 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +000010537 } else {
Duncan Sands514ab342007-11-01 20:53:16 +000010538 unsigned PS = TD->getPointerSizeInBits();
10539 if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +000010540 // Convert GO1 to SO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +000010541 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000010542
Duncan Sands514ab342007-11-01 20:53:16 +000010543 } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +000010544 // Convert SO1 to GO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +000010545 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000010546 } else {
10547 const Type *PT = TD->getIntPtrType();
Reid Spencer17212df2006-12-12 09:18:51 +000010548 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
10549 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000010550 }
10551 }
10552 }
Chris Lattner620ce142004-05-07 22:09:22 +000010553 if (isa<Constant>(SO1) && isa<Constant>(GO1))
10554 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
10555 else {
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010556 Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Chris Lattner48595f12004-06-10 02:07:29 +000010557 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner620ce142004-05-07 22:09:22 +000010558 }
Chris Lattner28977af2004-04-05 01:30:19 +000010559 }
Chris Lattner620ce142004-05-07 22:09:22 +000010560
10561 // Recycle the GEP we already have if possible.
10562 if (SrcGEPOperands.size() == 2) {
10563 GEP.setOperand(0, SrcGEPOperands[0]);
10564 GEP.setOperand(1, Sum);
10565 return &GEP;
10566 } else {
10567 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
10568 SrcGEPOperands.end()-1);
10569 Indices.push_back(Sum);
10570 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
10571 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010572 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +000010573 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanfd939082005-04-21 23:48:37 +000010574 SrcGEPOperands.size() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +000010575 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerebd985c2004-03-25 22:59:29 +000010576 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
10577 SrcGEPOperands.end());
Chris Lattner90ac28c2002-08-02 19:29:35 +000010578 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
10579 }
10580
10581 if (!Indices.empty())
Gabor Greif051a9502008-04-06 20:25:17 +000010582 return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
10583 Indices.end(), GEP.getName());
Chris Lattner9b761232002-08-17 22:21:59 +000010584
Chris Lattner620ce142004-05-07 22:09:22 +000010585 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattner9b761232002-08-17 22:21:59 +000010586 // GEP of global variable. If all of the indices for this GEP are
10587 // constants, we can promote this to a constexpr instead of an instruction.
10588
10589 // Scan for nonconstants...
Chris Lattner55eb1c42007-01-31 04:40:53 +000010590 SmallVector<Constant*, 8> Indices;
Chris Lattner9b761232002-08-17 22:21:59 +000010591 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
10592 for (; I != E && isa<Constant>(*I); ++I)
10593 Indices.push_back(cast<Constant>(*I));
10594
10595 if (I == E) { // If they are all constants...
Chris Lattner55eb1c42007-01-31 04:40:53 +000010596 Constant *CE = ConstantExpr::getGetElementPtr(GV,
10597 &Indices[0],Indices.size());
Chris Lattner9b761232002-08-17 22:21:59 +000010598
10599 // Replace all uses of the GEP with the new constexpr...
10600 return ReplaceInstUsesWith(GEP, CE);
10601 }
Reid Spencer3da59db2006-11-27 01:05:10 +000010602 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
Chris Lattnereed48272005-09-13 00:40:14 +000010603 if (!isa<PointerType>(X->getType())) {
10604 // Not interesting. Source pointer must be a cast from pointer.
10605 } else if (HasZeroPointerIndex) {
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010606 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
10607 // into : GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +000010608 //
10609 // This occurs when the program declares an array extern like "int X[];"
10610 //
10611 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
10612 const PointerType *XTy = cast<PointerType>(X->getType());
10613 if (const ArrayType *XATy =
10614 dyn_cast<ArrayType>(XTy->getElementType()))
10615 if (const ArrayType *CATy =
10616 dyn_cast<ArrayType>(CPTy->getElementType()))
10617 if (CATy->getElementType() == XATy->getElementType()) {
10618 // At this point, we know that the cast source type is a pointer
10619 // to an array of the same type as the destination pointer
10620 // array. Because the array type is never stepped over (there
10621 // is a leading zero) we can fold the cast into this GEP.
10622 GEP.setOperand(0, X);
10623 return &GEP;
10624 }
10625 } else if (GEP.getNumOperands() == 2) {
10626 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010627 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
10628 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnereed48272005-09-13 00:40:14 +000010629 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
10630 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
10631 if (isa<ArrayType>(SrcElTy) &&
Duncan Sandsceb4d1a2009-01-12 20:38:59 +000010632 TD->getTypePaddedSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
10633 TD->getTypePaddedSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +000010634 Value *Idx[2];
10635 Idx[0] = Constant::getNullValue(Type::Int32Ty);
10636 Idx[1] = GEP.getOperand(1);
Chris Lattnereed48272005-09-13 00:40:14 +000010637 Value *V = InsertNewInstBefore(
Gabor Greif051a9502008-04-06 20:25:17 +000010638 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
Reid Spencer3da59db2006-11-27 01:05:10 +000010639 // V and GEP are both pointer types --> BitCast
10640 return new BitCastInst(V, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010641 }
Chris Lattner7835cdd2005-09-13 18:36:04 +000010642
10643 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010644 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +000010645 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010646 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +000010647
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010648 if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
Chris Lattner7835cdd2005-09-13 18:36:04 +000010649 uint64_t ArrayEltSize =
Duncan Sandsceb4d1a2009-01-12 20:38:59 +000010650 TD->getTypePaddedSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000010651
10652 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
10653 // allow either a mul, shift, or constant here.
10654 Value *NewIdx = 0;
10655 ConstantInt *Scale = 0;
10656 if (ArrayEltSize == 1) {
10657 NewIdx = GEP.getOperand(1);
10658 Scale = ConstantInt::get(NewIdx->getType(), 1);
10659 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattner6e2f8432005-09-14 17:32:56 +000010660 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000010661 Scale = CI;
10662 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
10663 if (Inst->getOpcode() == Instruction::Shl &&
10664 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +000010665 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
10666 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
10667 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +000010668 NewIdx = Inst->getOperand(0);
10669 } else if (Inst->getOpcode() == Instruction::Mul &&
10670 isa<ConstantInt>(Inst->getOperand(1))) {
10671 Scale = cast<ConstantInt>(Inst->getOperand(1));
10672 NewIdx = Inst->getOperand(0);
10673 }
10674 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010675
Chris Lattner7835cdd2005-09-13 18:36:04 +000010676 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010677 // out, perform the transformation. Note, we don't know whether Scale is
10678 // signed or not. We'll use unsigned version of division/modulo
10679 // operation after making sure Scale doesn't have the sign bit set.
10680 if (Scale && Scale->getSExtValue() >= 0LL &&
10681 Scale->getZExtValue() % ArrayEltSize == 0) {
10682 Scale = ConstantInt::get(Scale->getType(),
10683 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +000010684 if (Scale->getZExtValue() != 1) {
Reid Spencer17212df2006-12-12 09:18:51 +000010685 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010686 false /*ZExt*/);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010687 Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
Chris Lattner7835cdd2005-09-13 18:36:04 +000010688 NewIdx = InsertNewInstBefore(Sc, GEP);
10689 }
10690
10691 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +000010692 Value *Idx[2];
10693 Idx[0] = Constant::getNullValue(Type::Int32Ty);
10694 Idx[1] = NewIdx;
Reid Spencer3da59db2006-11-27 01:05:10 +000010695 Instruction *NewGEP =
Gabor Greif051a9502008-04-06 20:25:17 +000010696 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +000010697 NewGEP = InsertNewInstBefore(NewGEP, GEP);
10698 // The NewGEP must be pointer typed, so must the old one -> BitCast
10699 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000010700 }
10701 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010702 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000010703 }
Chris Lattner58407792009-01-09 04:53:57 +000010704
Chris Lattner46cd5a12009-01-09 05:44:56 +000010705 /// See if we can simplify:
10706 /// X = bitcast A to B*
10707 /// Y = gep X, <...constant indices...>
10708 /// into a gep of the original struct. This is important for SROA and alias
10709 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattner58407792009-01-09 04:53:57 +000010710 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +000010711 if (!isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
10712 // Determine how much the GEP moves the pointer. We are guaranteed to get
10713 // a constant back from EmitGEPOffset.
10714 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
10715 int64_t Offset = OffsetV->getSExtValue();
10716
10717 // If this GEP instruction doesn't move the pointer, just replace the GEP
10718 // with a bitcast of the real input to the dest type.
10719 if (Offset == 0) {
10720 // If the bitcast is of an allocation, and the allocation will be
10721 // converted to match the type of the cast, don't touch this.
10722 if (isa<AllocationInst>(BCI->getOperand(0))) {
10723 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
10724 if (Instruction *I = visitBitCast(*BCI)) {
10725 if (I != BCI) {
10726 I->takeName(BCI);
10727 BCI->getParent()->getInstList().insert(BCI, I);
10728 ReplaceInstUsesWith(*BCI, I);
10729 }
10730 return &GEP;
Chris Lattner58407792009-01-09 04:53:57 +000010731 }
Chris Lattner58407792009-01-09 04:53:57 +000010732 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000010733 return new BitCastInst(BCI->getOperand(0), GEP.getType());
Chris Lattner58407792009-01-09 04:53:57 +000010734 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000010735
10736 // Otherwise, if the offset is non-zero, we need to find out if there is a
10737 // field at Offset in 'A's type. If so, we can pull the cast through the
10738 // GEP.
10739 SmallVector<Value*, 8> NewIndices;
10740 const Type *InTy =
10741 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
10742 if (FindElementAtOffset(InTy, Offset, NewIndices, TD)) {
10743 Instruction *NGEP =
10744 GetElementPtrInst::Create(BCI->getOperand(0), NewIndices.begin(),
10745 NewIndices.end());
10746 if (NGEP->getType() == GEP.getType()) return NGEP;
10747 InsertNewInstBefore(NGEP, GEP);
10748 NGEP->takeName(&GEP);
10749 return new BitCastInst(NGEP, GEP.getType());
10750 }
Chris Lattner58407792009-01-09 04:53:57 +000010751 }
10752 }
10753
Chris Lattner8a2a3112001-12-14 16:52:21 +000010754 return 0;
10755}
10756
Chris Lattner0864acf2002-11-04 16:18:53 +000010757Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
10758 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010759 if (AI.isArrayAllocation()) { // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +000010760 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
10761 const Type *NewTy =
10762 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattner0006bd72002-11-09 00:49:43 +000010763 AllocationInst *New = 0;
Chris Lattner0864acf2002-11-04 16:18:53 +000010764
10765 // Create and insert the replacement instruction...
10766 if (isa<MallocInst>(AI))
Nate Begeman14b05292005-11-05 09:21:28 +000010767 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000010768 else {
10769 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman14b05292005-11-05 09:21:28 +000010770 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000010771 }
Chris Lattner7c881df2004-03-19 06:08:10 +000010772
10773 InsertNewInstBefore(New, AI);
Misha Brukmanfd939082005-04-21 23:48:37 +000010774
Chris Lattner0864acf2002-11-04 16:18:53 +000010775 // Scan to the end of the allocation instructions, to skip over a block of
10776 // allocas if possible...
10777 //
10778 BasicBlock::iterator It = New;
10779 while (isa<AllocationInst>(*It)) ++It;
10780
10781 // Now that I is pointing to the first non-allocation-inst in the block,
10782 // insert our getelementptr instruction...
10783 //
Reid Spencerc5b206b2006-12-31 05:48:39 +000010784 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
David Greeneb8f74792007-09-04 15:46:09 +000010785 Value *Idx[2];
10786 Idx[0] = NullIdx;
10787 Idx[1] = NullIdx;
Gabor Greif051a9502008-04-06 20:25:17 +000010788 Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
10789 New->getName()+".sub", It);
Chris Lattner0864acf2002-11-04 16:18:53 +000010790
10791 // Now make everything use the getelementptr instead of the original
10792 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +000010793 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +000010794 } else if (isa<UndefValue>(AI.getArraySize())) {
10795 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +000010796 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010797 }
Chris Lattner7c881df2004-03-19 06:08:10 +000010798
Dan Gohman6893cd72009-01-13 20:18:38 +000010799 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
10800 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
10801 // Note that we only do this for alloca's, because malloc should allocate and
10802 // return a unique pointer, even for a zero byte allocation.
10803 if (TD->getTypePaddedSize(AI.getAllocatedType()) == 0)
10804 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
10805
10806 // If the alignment is 0 (unspecified), assign it the preferred alignment.
10807 if (AI.getAlignment() == 0)
10808 AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
10809 }
Chris Lattner7c881df2004-03-19 06:08:10 +000010810
Chris Lattner0864acf2002-11-04 16:18:53 +000010811 return 0;
10812}
10813
Chris Lattner67b1e1b2003-12-07 01:24:23 +000010814Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
10815 Value *Op = FI.getOperand(0);
10816
Chris Lattner17be6352004-10-18 02:59:09 +000010817 // free undef -> unreachable.
10818 if (isa<UndefValue>(Op)) {
10819 // Insert a new store to null because we cannot modify the CFG here.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +000010820 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +000010821 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
Chris Lattner17be6352004-10-18 02:59:09 +000010822 return EraseInstFromFunction(FI);
10823 }
Chris Lattner6fe55412007-04-14 00:20:02 +000010824
Chris Lattner6160e852004-02-28 04:57:37 +000010825 // If we have 'free null' delete the instruction. This can happen in stl code
10826 // when lots of inlining happens.
Chris Lattner17be6352004-10-18 02:59:09 +000010827 if (isa<ConstantPointerNull>(Op))
Chris Lattner7bcc0e72004-02-28 05:22:00 +000010828 return EraseInstFromFunction(FI);
Chris Lattner6fe55412007-04-14 00:20:02 +000010829
10830 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
10831 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
10832 FI.setOperand(0, CI->getOperand(0));
10833 return &FI;
10834 }
10835
10836 // Change free (gep X, 0,0,0,0) into free(X)
10837 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10838 if (GEPI->hasAllZeroIndices()) {
10839 AddToWorkList(GEPI);
10840 FI.setOperand(0, GEPI->getOperand(0));
10841 return &FI;
10842 }
10843 }
10844
10845 // Change free(malloc) into nothing, if the malloc has a single use.
10846 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
10847 if (MI->hasOneUse()) {
10848 EraseInstFromFunction(FI);
10849 return EraseInstFromFunction(*MI);
10850 }
Chris Lattner6160e852004-02-28 04:57:37 +000010851
Chris Lattner67b1e1b2003-12-07 01:24:23 +000010852 return 0;
10853}
10854
10855
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010856/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patel99db6ad2007-10-18 19:52:32 +000010857static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling587c01d2008-02-26 10:53:30 +000010858 const TargetData *TD) {
Chris Lattnerb89e0712004-07-13 01:49:43 +000010859 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +000010860 Value *CastOp = CI->getOperand(0);
Chris Lattnerb89e0712004-07-13 01:49:43 +000010861
Devang Patel99db6ad2007-10-18 19:52:32 +000010862 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
10863 // Instead of loading constant c string, use corresponding integer value
10864 // directly if string length is small enough.
Evan Cheng0ff39b32008-06-30 07:31:25 +000010865 std::string Str;
10866 if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
Devang Patel99db6ad2007-10-18 19:52:32 +000010867 unsigned len = Str.length();
10868 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
10869 unsigned numBits = Ty->getPrimitiveSizeInBits();
10870 // Replace LI with immediate integer store.
10871 if ((numBits >> 3) == len + 1) {
Bill Wendling587c01d2008-02-26 10:53:30 +000010872 APInt StrVal(numBits, 0);
10873 APInt SingleChar(numBits, 0);
10874 if (TD->isLittleEndian()) {
10875 for (signed i = len-1; i >= 0; i--) {
10876 SingleChar = (uint64_t) Str[i];
10877 StrVal = (StrVal << 8) | SingleChar;
10878 }
10879 } else {
10880 for (unsigned i = 0; i < len; i++) {
10881 SingleChar = (uint64_t) Str[i];
10882 StrVal = (StrVal << 8) | SingleChar;
10883 }
10884 // Append NULL at the end.
10885 SingleChar = 0;
10886 StrVal = (StrVal << 8) | SingleChar;
10887 }
10888 Value *NL = ConstantInt::get(StrVal);
10889 return IC.ReplaceInstUsesWith(LI, NL);
Devang Patel99db6ad2007-10-18 19:52:32 +000010890 }
10891 }
10892 }
10893
Chris Lattnerb89e0712004-07-13 01:49:43 +000010894 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000010895 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattnerb89e0712004-07-13 01:49:43 +000010896 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000010897
Reid Spencer42230162007-01-22 05:51:25 +000010898 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000010899 isa<VectorType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +000010900 // If the source is an array, the code below will not succeed. Check to
10901 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
10902 // constants.
10903 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10904 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10905 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +000010906 Value *Idxs[2];
10907 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10908 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerf9527852005-01-31 04:50:46 +000010909 SrcTy = cast<PointerType>(CastOp->getType());
10910 SrcPTy = SrcTy->getElementType();
10911 }
10912
Reid Spencer42230162007-01-22 05:51:25 +000010913 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000010914 isa<VectorType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +000010915 // Do not allow turning this into a load of an integer, which is then
10916 // casted to a pointer, this pessimizes pointer analysis a lot.
10917 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Reid Spencer42230162007-01-22 05:51:25 +000010918 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10919 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +000010920
Chris Lattnerf9527852005-01-31 04:50:46 +000010921 // Okay, we are casting from one integer or pointer type to another of
10922 // the same size. Instead of casting the pointer before the load, cast
10923 // the result of the loaded value.
10924 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
10925 CI->getName(),
10926 LI.isVolatile()),LI);
10927 // Now cast the result of the load.
Reid Spencerd977d862006-12-12 23:36:14 +000010928 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerf9527852005-01-31 04:50:46 +000010929 }
Chris Lattnerb89e0712004-07-13 01:49:43 +000010930 }
10931 }
10932 return 0;
10933}
10934
Chris Lattnerc10aced2004-09-19 18:43:46 +000010935/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattner8a375202004-09-19 19:18:10 +000010936/// from this value cannot trap. If it is not obviously safe to load from the
10937/// specified pointer, we do a quick local scan of the basic block containing
10938/// ScanFrom, to determine if the address is already accessed.
10939static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
Duncan Sands892c7e42007-09-19 10:10:31 +000010940 // If it is an alloca it is always safe to load from.
10941 if (isa<AllocaInst>(V)) return true;
10942
Duncan Sands46318cd2007-09-19 10:25:38 +000010943 // If it is a global variable it is mostly safe to load from.
Duncan Sands892c7e42007-09-19 10:10:31 +000010944 if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
Duncan Sands46318cd2007-09-19 10:25:38 +000010945 // Don't try to evaluate aliases. External weak GV can be null.
Duncan Sands892c7e42007-09-19 10:10:31 +000010946 return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
Chris Lattner8a375202004-09-19 19:18:10 +000010947
10948 // Otherwise, be a little bit agressive by scanning the local block where we
10949 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +000010950 // from/to. If so, the previous load or store would have already trapped,
10951 // so there is no harm doing an extra load (also, CSE will later eliminate
10952 // the load entirely).
Chris Lattner8a375202004-09-19 19:18:10 +000010953 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
10954
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +000010955 while (BBI != E) {
Chris Lattner8a375202004-09-19 19:18:10 +000010956 --BBI;
10957
Chris Lattner2de3fec2008-06-20 05:12:56 +000010958 // If we see a free or a call (which might do a free) the pointer could be
10959 // marked invalid.
10960 if (isa<FreeInst>(BBI) || isa<CallInst>(BBI))
10961 return false;
10962
Chris Lattner8a375202004-09-19 19:18:10 +000010963 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
10964 if (LI->getOperand(0) == V) return true;
Chris Lattner2de3fec2008-06-20 05:12:56 +000010965 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
Chris Lattner8a375202004-09-19 19:18:10 +000010966 if (SI->getOperand(1) == V) return true;
Chris Lattner2de3fec2008-06-20 05:12:56 +000010967 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010968
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +000010969 }
Chris Lattner8a375202004-09-19 19:18:10 +000010970 return false;
Chris Lattnerc10aced2004-09-19 18:43:46 +000010971}
10972
Chris Lattner833b8a42003-06-26 05:06:25 +000010973Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
10974 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +000010975
Dan Gohman9941f742007-07-20 16:34:21 +000010976 // Attempt to improve the alignment.
Dan Gohmaneee962e2008-04-10 18:43:06 +000010977 unsigned KnownAlign = GetOrEnforceKnownAlignment(Op);
10978 if (KnownAlign >
10979 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
10980 LI.getAlignment()))
Dan Gohman9941f742007-07-20 16:34:21 +000010981 LI.setAlignment(KnownAlign);
10982
Chris Lattner37366c12005-05-01 04:24:53 +000010983 // load (cast X) --> cast (load X) iff safe
Reid Spencer3ed469c2006-11-02 20:25:50 +000010984 if (isa<CastInst>(Op))
Devang Patel99db6ad2007-10-18 19:52:32 +000010985 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattner37366c12005-05-01 04:24:53 +000010986 return Res;
10987
10988 // None of the following transforms are legal for volatile loads.
10989 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +000010990
Dan Gohman2276a7b2008-10-15 23:19:35 +000010991 // Do really simple store-to-load forwarding and load CSE, to catch cases
10992 // where there are several consequtive memory accesses to the same location,
10993 // separated by a few arithmetic operations.
10994 BasicBlock::iterator BBI = &LI;
Chris Lattner4aebaee2008-11-27 08:56:30 +000010995 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
10996 return ReplaceInstUsesWith(LI, AvailableVal);
Chris Lattner37366c12005-05-01 04:24:53 +000010997
Christopher Lambb15147e2007-12-29 07:56:53 +000010998 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10999 const Value *GEPI0 = GEPI->getOperand(0);
11000 // TODO: Consider a target hook for valid address spaces for this xform.
11001 if (isa<ConstantPointerNull>(GEPI0) &&
11002 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
Chris Lattner37366c12005-05-01 04:24:53 +000011003 // Insert a new store to null instruction before the load to indicate
11004 // that this code is not reachable. We do this instead of inserting
11005 // an unreachable instruction directly because we cannot modify the
11006 // CFG.
11007 new StoreInst(UndefValue::get(LI.getType()),
11008 Constant::getNullValue(Op->getType()), &LI);
11009 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11010 }
Christopher Lambb15147e2007-12-29 07:56:53 +000011011 }
Chris Lattner37366c12005-05-01 04:24:53 +000011012
Chris Lattnere87597f2004-10-16 18:11:37 +000011013 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner37366c12005-05-01 04:24:53 +000011014 // load null/undef -> undef
Christopher Lambb15147e2007-12-29 07:56:53 +000011015 // TODO: Consider a target hook for valid address spaces for this xform.
11016 if (isa<UndefValue>(C) || (C->isNullValue() &&
11017 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
Chris Lattner17be6352004-10-18 02:59:09 +000011018 // Insert a new store to null instruction before the load to indicate that
11019 // this code is not reachable. We do this instead of inserting an
11020 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattner37366c12005-05-01 04:24:53 +000011021 new StoreInst(UndefValue::get(LI.getType()),
11022 Constant::getNullValue(Op->getType()), &LI);
Chris Lattnere87597f2004-10-16 18:11:37 +000011023 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner17be6352004-10-18 02:59:09 +000011024 }
Chris Lattner833b8a42003-06-26 05:06:25 +000011025
Chris Lattnere87597f2004-10-16 18:11:37 +000011026 // Instcombine load (constant global) into the value loaded.
11027 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Reid Spencer5cbf9852007-01-30 20:08:39 +000011028 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattnere87597f2004-10-16 18:11:37 +000011029 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +000011030
Chris Lattnere87597f2004-10-16 18:11:37 +000011031 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011032 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
Chris Lattnere87597f2004-10-16 18:11:37 +000011033 if (CE->getOpcode() == Instruction::GetElementPtr) {
11034 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Reid Spencer5cbf9852007-01-30 20:08:39 +000011035 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattner363f2a22005-09-26 05:28:06 +000011036 if (Constant *V =
11037 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattnere87597f2004-10-16 18:11:37 +000011038 return ReplaceInstUsesWith(LI, V);
Chris Lattner37366c12005-05-01 04:24:53 +000011039 if (CE->getOperand(0)->isNullValue()) {
11040 // Insert a new store to null instruction before the load to indicate
11041 // that this code is not reachable. We do this instead of inserting
11042 // an unreachable instruction directly because we cannot modify the
11043 // CFG.
11044 new StoreInst(UndefValue::get(LI.getType()),
11045 Constant::getNullValue(Op->getType()), &LI);
11046 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11047 }
11048
Reid Spencer3da59db2006-11-27 01:05:10 +000011049 } else if (CE->isCast()) {
Devang Patel99db6ad2007-10-18 19:52:32 +000011050 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattnere87597f2004-10-16 18:11:37 +000011051 return Res;
11052 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011053 }
Chris Lattnere87597f2004-10-16 18:11:37 +000011054 }
Chris Lattner8d2e8882007-08-11 18:48:48 +000011055
11056 // If this load comes from anywhere in a constant global, and if the global
11057 // is all undef or zero, we know what it loads.
Duncan Sands5d0392c2008-10-01 15:25:41 +000011058 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
Chris Lattner8d2e8882007-08-11 18:48:48 +000011059 if (GV->isConstant() && GV->hasInitializer()) {
11060 if (GV->getInitializer()->isNullValue())
11061 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
11062 else if (isa<UndefValue>(GV->getInitializer()))
11063 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11064 }
11065 }
Chris Lattnerf499eac2004-04-08 20:39:49 +000011066
Chris Lattner37366c12005-05-01 04:24:53 +000011067 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000011068 // Change select and PHI nodes to select values instead of addresses: this
11069 // helps alias analysis out a lot, allows many others simplifications, and
11070 // exposes redundancy in the code.
11071 //
11072 // Note that we cannot do the transformation unless we know that the
11073 // introduced loads cannot trap! Something like this is valid as long as
11074 // the condition is always false: load (select bool %C, int* null, int* %G),
11075 // but it would not be valid if we transformed it to load from null
11076 // unconditionally.
11077 //
11078 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11079 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +000011080 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11081 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000011082 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000011083 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +000011084 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000011085 SI->getOperand(2)->getName()+".val"), LI);
Gabor Greif051a9502008-04-06 20:25:17 +000011086 return SelectInst::Create(SI->getCondition(), V1, V2);
Chris Lattnerc10aced2004-09-19 18:43:46 +000011087 }
11088
Chris Lattner684fe212004-09-23 15:46:00 +000011089 // load (select (cond, null, P)) -> load P
11090 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11091 if (C->isNullValue()) {
11092 LI.setOperand(0, SI->getOperand(2));
11093 return &LI;
11094 }
11095
11096 // load (select (cond, P, null)) -> load P
11097 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11098 if (C->isNullValue()) {
11099 LI.setOperand(0, SI->getOperand(1));
11100 return &LI;
11101 }
Chris Lattnerc10aced2004-09-19 18:43:46 +000011102 }
11103 }
Chris Lattner833b8a42003-06-26 05:06:25 +000011104 return 0;
11105}
11106
Reid Spencer55af2b52007-01-19 21:20:31 +000011107/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattner3914f722009-01-24 01:00:13 +000011108/// when possible. This makes it generally easy to do alias analysis and/or
11109/// SROA/mem2reg of the memory object.
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011110static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11111 User *CI = cast<User>(SI.getOperand(1));
11112 Value *CastOp = CI->getOperand(0);
11113
11114 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011115 const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11116 if (SrcTy == 0) return 0;
11117
11118 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011119
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011120 if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11121 return 0;
11122
Chris Lattner3914f722009-01-24 01:00:13 +000011123 /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11124 /// to its first element. This allows us to handle things like:
11125 /// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11126 /// on 32-bit hosts.
11127 SmallVector<Value*, 4> NewGEPIndices;
11128
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011129 // If the source is an array, the code below will not succeed. Check to
11130 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11131 // constants.
Chris Lattner3914f722009-01-24 01:00:13 +000011132 if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11133 // Index through pointer.
11134 Constant *Zero = Constant::getNullValue(Type::Int32Ty);
11135 NewGEPIndices.push_back(Zero);
11136
11137 while (1) {
11138 if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
Torok Edwin08ffee52009-01-24 17:16:04 +000011139 if (!STy->getNumElements()) /* Struct can be empty {} */
Torok Edwin629e92b2009-01-24 11:30:49 +000011140 break;
Chris Lattner3914f722009-01-24 01:00:13 +000011141 NewGEPIndices.push_back(Zero);
11142 SrcPTy = STy->getElementType(0);
11143 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11144 NewGEPIndices.push_back(Zero);
11145 SrcPTy = ATy->getElementType();
11146 } else {
11147 break;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011148 }
Chris Lattner3914f722009-01-24 01:00:13 +000011149 }
11150
11151 SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
11152 }
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011153
11154 if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11155 return 0;
11156
Chris Lattner71759c42009-01-16 20:12:52 +000011157 // If the pointers point into different address spaces or if they point to
11158 // values with different sizes, we can't do the transformation.
11159 if (SrcTy->getAddressSpace() !=
11160 cast<PointerType>(CI->getType())->getAddressSpace() ||
11161 IC.getTargetData().getTypeSizeInBits(SrcPTy) !=
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011162 IC.getTargetData().getTypeSizeInBits(DestPTy))
11163 return 0;
11164
11165 // Okay, we are casting from one integer or pointer type to another of
11166 // the same size. Instead of casting the pointer before
11167 // the store, cast the value to be stored.
11168 Value *NewCast;
11169 Value *SIOp0 = SI.getOperand(0);
11170 Instruction::CastOps opcode = Instruction::BitCast;
11171 const Type* CastSrcTy = SIOp0->getType();
11172 const Type* CastDstTy = SrcPTy;
11173 if (isa<PointerType>(CastDstTy)) {
11174 if (CastSrcTy->isInteger())
11175 opcode = Instruction::IntToPtr;
11176 } else if (isa<IntegerType>(CastDstTy)) {
11177 if (isa<PointerType>(SIOp0->getType()))
11178 opcode = Instruction::PtrToInt;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011179 }
Chris Lattner3914f722009-01-24 01:00:13 +000011180
11181 // SIOp0 is a pointer to aggregate and this is a store to the first field,
11182 // emit a GEP to index into its first field.
11183 if (!NewGEPIndices.empty()) {
11184 if (Constant *C = dyn_cast<Constant>(CastOp))
11185 CastOp = ConstantExpr::getGetElementPtr(C, &NewGEPIndices[0],
11186 NewGEPIndices.size());
11187 else
11188 CastOp = IC.InsertNewInstBefore(
11189 GetElementPtrInst::Create(CastOp, NewGEPIndices.begin(),
11190 NewGEPIndices.end()), SI);
11191 }
11192
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011193 if (Constant *C = dyn_cast<Constant>(SIOp0))
11194 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
11195 else
11196 NewCast = IC.InsertNewInstBefore(
11197 CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
11198 SI);
11199 return new StoreInst(NewCast, CastOp);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011200}
11201
Chris Lattner4aebaee2008-11-27 08:56:30 +000011202/// equivalentAddressValues - Test if A and B will obviously have the same
11203/// value. This includes recognizing that %t0 and %t1 will have the same
11204/// value in code like this:
11205/// %t0 = getelementptr @a, 0, 3
11206/// store i32 0, i32* %t0
11207/// %t1 = getelementptr @a, 0, 3
11208/// %t2 = load i32* %t1
11209///
11210static bool equivalentAddressValues(Value *A, Value *B) {
11211 // Test if the values are trivially equivalent.
11212 if (A == B) return true;
11213
11214 // Test if the values come form identical arithmetic instructions.
11215 if (isa<BinaryOperator>(A) ||
11216 isa<CastInst>(A) ||
11217 isa<PHINode>(A) ||
11218 isa<GetElementPtrInst>(A))
11219 if (Instruction *BI = dyn_cast<Instruction>(B))
11220 if (cast<Instruction>(A)->isIdenticalTo(BI))
11221 return true;
11222
11223 // Otherwise they may not be equivalent.
11224 return false;
11225}
11226
Chris Lattner2f503e62005-01-31 05:36:43 +000011227Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11228 Value *Val = SI.getOperand(0);
11229 Value *Ptr = SI.getOperand(1);
11230
11231 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner9ca96412006-02-08 03:25:32 +000011232 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000011233 ++NumCombined;
11234 return 0;
11235 }
Chris Lattner836692d2007-01-15 06:51:56 +000011236
11237 // If the RHS is an alloca with a single use, zapify the store, making the
11238 // alloca dead.
Chris Lattnercea1fdd2008-04-29 04:58:38 +000011239 if (Ptr->hasOneUse() && !SI.isVolatile()) {
Chris Lattner836692d2007-01-15 06:51:56 +000011240 if (isa<AllocaInst>(Ptr)) {
11241 EraseInstFromFunction(SI);
11242 ++NumCombined;
11243 return 0;
11244 }
11245
11246 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
11247 if (isa<AllocaInst>(GEP->getOperand(0)) &&
11248 GEP->getOperand(0)->hasOneUse()) {
11249 EraseInstFromFunction(SI);
11250 ++NumCombined;
11251 return 0;
11252 }
11253 }
Chris Lattner2f503e62005-01-31 05:36:43 +000011254
Dan Gohman9941f742007-07-20 16:34:21 +000011255 // Attempt to improve the alignment.
Dan Gohmaneee962e2008-04-10 18:43:06 +000011256 unsigned KnownAlign = GetOrEnforceKnownAlignment(Ptr);
11257 if (KnownAlign >
11258 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11259 SI.getAlignment()))
Dan Gohman9941f742007-07-20 16:34:21 +000011260 SI.setAlignment(KnownAlign);
11261
Chris Lattner9ca96412006-02-08 03:25:32 +000011262 // Do really simple DSE, to catch cases where there are several consequtive
11263 // stores to the same location, separated by a few arithmetic operations. This
11264 // situation often occurs with bitfield accesses.
11265 BasicBlock::iterator BBI = &SI;
11266 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11267 --ScanInsts) {
11268 --BBI;
11269
11270 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11271 // Prev store isn't volatile, and stores to the same location?
Chris Lattner4aebaee2008-11-27 08:56:30 +000011272 if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11273 SI.getOperand(1))) {
Chris Lattner9ca96412006-02-08 03:25:32 +000011274 ++NumDeadStore;
11275 ++BBI;
11276 EraseInstFromFunction(*PrevSI);
11277 continue;
11278 }
11279 break;
11280 }
11281
Chris Lattnerb4db97f2006-05-26 19:19:20 +000011282 // If this is a load, we have to stop. However, if the loaded value is from
11283 // the pointer we're loading and is producing the pointer we're storing,
11284 // then *this* store is dead (X = load P; store X -> P).
11285 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Dan Gohman2276a7b2008-10-15 23:19:35 +000011286 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11287 !SI.isVolatile()) {
Chris Lattnerb4db97f2006-05-26 19:19:20 +000011288 EraseInstFromFunction(SI);
11289 ++NumCombined;
11290 return 0;
11291 }
11292 // Otherwise, this is a load from some other location. Stores before it
11293 // may not be dead.
11294 break;
11295 }
11296
Chris Lattner9ca96412006-02-08 03:25:32 +000011297 // Don't skip over loads or things that can modify memory.
Chris Lattner0ef546e2008-05-08 17:20:30 +000011298 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +000011299 break;
11300 }
11301
11302
11303 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +000011304
11305 // store X, null -> turns into 'unreachable' in SimplifyCFG
11306 if (isa<ConstantPointerNull>(Ptr)) {
11307 if (!isa<UndefValue>(Val)) {
11308 SI.setOperand(0, UndefValue::get(Val->getType()));
11309 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattnerdbab3862007-03-02 21:28:56 +000011310 AddToWorkList(U); // Dropped a use.
Chris Lattner2f503e62005-01-31 05:36:43 +000011311 ++NumCombined;
11312 }
11313 return 0; // Do not modify these!
11314 }
11315
11316 // store undef, Ptr -> noop
11317 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +000011318 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000011319 ++NumCombined;
11320 return 0;
11321 }
11322
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011323 // If the pointer destination is a cast, see if we can fold the cast into the
11324 // source instead.
Reid Spencer3ed469c2006-11-02 20:25:50 +000011325 if (isa<CastInst>(Ptr))
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011326 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11327 return Res;
11328 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer3da59db2006-11-27 01:05:10 +000011329 if (CE->isCast())
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011330 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11331 return Res;
11332
Chris Lattner408902b2005-09-12 23:23:25 +000011333
11334 // If this store is the last instruction in the basic block, and if the block
11335 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner9ca96412006-02-08 03:25:32 +000011336 BBI = &SI; ++BBI;
Chris Lattner408902b2005-09-12 23:23:25 +000011337 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011338 if (BI->isUnconditional())
11339 if (SimplifyStoreAtEndOfBlock(SI))
11340 return 0; // xform done!
Chris Lattner408902b2005-09-12 23:23:25 +000011341
Chris Lattner2f503e62005-01-31 05:36:43 +000011342 return 0;
11343}
11344
Chris Lattner3284d1f2007-04-15 00:07:55 +000011345/// SimplifyStoreAtEndOfBlock - Turn things like:
11346/// if () { *P = v1; } else { *P = v2 }
11347/// into a phi node with a store in the successor.
11348///
Chris Lattner31755a02007-04-15 01:02:18 +000011349/// Simplify things like:
11350/// *P = v1; if () { *P = v2; }
11351/// into a phi node with a store in the successor.
11352///
Chris Lattner3284d1f2007-04-15 00:07:55 +000011353bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11354 BasicBlock *StoreBB = SI.getParent();
11355
11356 // Check to see if the successor block has exactly two incoming edges. If
11357 // so, see if the other predecessor contains a store to the same location.
11358 // if so, insert a PHI node (if needed) and move the stores down.
Chris Lattner31755a02007-04-15 01:02:18 +000011359 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Chris Lattner3284d1f2007-04-15 00:07:55 +000011360
11361 // Determine whether Dest has exactly two predecessors and, if so, compute
11362 // the other predecessor.
Chris Lattner31755a02007-04-15 01:02:18 +000011363 pred_iterator PI = pred_begin(DestBB);
11364 BasicBlock *OtherBB = 0;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011365 if (*PI != StoreBB)
Chris Lattner31755a02007-04-15 01:02:18 +000011366 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011367 ++PI;
Chris Lattner31755a02007-04-15 01:02:18 +000011368 if (PI == pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011369 return false;
11370
11371 if (*PI != StoreBB) {
Chris Lattner31755a02007-04-15 01:02:18 +000011372 if (OtherBB)
Chris Lattner3284d1f2007-04-15 00:07:55 +000011373 return false;
Chris Lattner31755a02007-04-15 01:02:18 +000011374 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011375 }
Chris Lattner31755a02007-04-15 01:02:18 +000011376 if (++PI != pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011377 return false;
Eli Friedman66fe80a2008-06-13 21:17:49 +000011378
11379 // Bail out if all the relevant blocks aren't distinct (this can happen,
11380 // for example, if SI is in an infinite loop)
11381 if (StoreBB == DestBB || OtherBB == DestBB)
11382 return false;
11383
Chris Lattner31755a02007-04-15 01:02:18 +000011384 // Verify that the other block ends in a branch and is not otherwise empty.
11385 BasicBlock::iterator BBI = OtherBB->getTerminator();
Chris Lattner3284d1f2007-04-15 00:07:55 +000011386 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
Chris Lattner31755a02007-04-15 01:02:18 +000011387 if (!OtherBr || BBI == OtherBB->begin())
Chris Lattner3284d1f2007-04-15 00:07:55 +000011388 return false;
11389
Chris Lattner31755a02007-04-15 01:02:18 +000011390 // If the other block ends in an unconditional branch, check for the 'if then
11391 // else' case. there is an instruction before the branch.
11392 StoreInst *OtherStore = 0;
11393 if (OtherBr->isUnconditional()) {
11394 // If this isn't a store, or isn't a store to the same location, bail out.
11395 --BBI;
11396 OtherStore = dyn_cast<StoreInst>(BBI);
11397 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
11398 return false;
11399 } else {
Chris Lattnerd717c182007-05-05 22:32:24 +000011400 // Otherwise, the other block ended with a conditional branch. If one of the
Chris Lattner31755a02007-04-15 01:02:18 +000011401 // destinations is StoreBB, then we have the if/then case.
11402 if (OtherBr->getSuccessor(0) != StoreBB &&
11403 OtherBr->getSuccessor(1) != StoreBB)
11404 return false;
11405
11406 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
Chris Lattnerd717c182007-05-05 22:32:24 +000011407 // if/then triangle. See if there is a store to the same ptr as SI that
11408 // lives in OtherBB.
Chris Lattner31755a02007-04-15 01:02:18 +000011409 for (;; --BBI) {
11410 // Check to see if we find the matching store.
11411 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
11412 if (OtherStore->getOperand(1) != SI.getOperand(1))
11413 return false;
11414 break;
11415 }
Eli Friedman6903a242008-06-13 22:02:12 +000011416 // If we find something that may be using or overwriting the stored
11417 // value, or if we run out of instructions, we can't do the xform.
11418 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
Chris Lattner31755a02007-04-15 01:02:18 +000011419 BBI == OtherBB->begin())
11420 return false;
11421 }
11422
11423 // In order to eliminate the store in OtherBr, we have to
Eli Friedman6903a242008-06-13 22:02:12 +000011424 // make sure nothing reads or overwrites the stored value in
11425 // StoreBB.
Chris Lattner31755a02007-04-15 01:02:18 +000011426 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
11427 // FIXME: This should really be AA driven.
Eli Friedman6903a242008-06-13 22:02:12 +000011428 if (I->mayReadFromMemory() || I->mayWriteToMemory())
Chris Lattner31755a02007-04-15 01:02:18 +000011429 return false;
11430 }
11431 }
Chris Lattner3284d1f2007-04-15 00:07:55 +000011432
Chris Lattner31755a02007-04-15 01:02:18 +000011433 // Insert a PHI node now if we need it.
Chris Lattner3284d1f2007-04-15 00:07:55 +000011434 Value *MergedVal = OtherStore->getOperand(0);
11435 if (MergedVal != SI.getOperand(0)) {
Gabor Greif051a9502008-04-06 20:25:17 +000011436 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Chris Lattner3284d1f2007-04-15 00:07:55 +000011437 PN->reserveOperandSpace(2);
11438 PN->addIncoming(SI.getOperand(0), SI.getParent());
Chris Lattner31755a02007-04-15 01:02:18 +000011439 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
11440 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Chris Lattner3284d1f2007-04-15 00:07:55 +000011441 }
11442
11443 // Advance to a place where it is safe to insert the new store and
11444 // insert it.
Dan Gohman02dea8b2008-05-23 21:05:58 +000011445 BBI = DestBB->getFirstNonPHI();
Chris Lattner3284d1f2007-04-15 00:07:55 +000011446 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
11447 OtherStore->isVolatile()), *BBI);
11448
11449 // Nuke the old stores.
11450 EraseInstFromFunction(SI);
11451 EraseInstFromFunction(*OtherStore);
11452 ++NumCombined;
11453 return true;
11454}
11455
Chris Lattner2f503e62005-01-31 05:36:43 +000011456
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000011457Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
11458 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +000011459 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000011460 BasicBlock *TrueDest;
11461 BasicBlock *FalseDest;
11462 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
11463 !isa<Constant>(X)) {
11464 // Swap Destinations and condition...
11465 BI.setCondition(X);
11466 BI.setSuccessor(0, FalseDest);
11467 BI.setSuccessor(1, TrueDest);
11468 return &BI;
11469 }
11470
Reid Spencere4d87aa2006-12-23 06:05:41 +000011471 // Cannonicalize fcmp_one -> fcmp_oeq
11472 FCmpInst::Predicate FPred; Value *Y;
11473 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
11474 TrueDest, FalseDest)))
11475 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
11476 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
11477 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000011478 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
Chris Lattner6934a042007-02-11 01:23:03 +000011479 Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
11480 NewSCC->takeName(I);
Reid Spencere4d87aa2006-12-23 06:05:41 +000011481 // Swap Destinations and condition...
11482 BI.setCondition(NewSCC);
11483 BI.setSuccessor(0, FalseDest);
11484 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000011485 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000011486 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000011487 AddToWorkList(NewSCC);
Reid Spencere4d87aa2006-12-23 06:05:41 +000011488 return &BI;
11489 }
11490
11491 // Cannonicalize icmp_ne -> icmp_eq
11492 ICmpInst::Predicate IPred;
11493 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
11494 TrueDest, FalseDest)))
11495 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
11496 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
11497 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
11498 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000011499 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
Chris Lattner6934a042007-02-11 01:23:03 +000011500 Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
11501 NewSCC->takeName(I);
Chris Lattner40f5d702003-06-04 05:10:11 +000011502 // Swap Destinations and condition...
Chris Lattneracd1f0f2004-07-30 07:50:03 +000011503 BI.setCondition(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000011504 BI.setSuccessor(0, FalseDest);
11505 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000011506 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000011507 I->eraseFromParent();;
Chris Lattnerdbab3862007-03-02 21:28:56 +000011508 AddToWorkList(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000011509 return &BI;
11510 }
Misha Brukmanfd939082005-04-21 23:48:37 +000011511
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000011512 return 0;
11513}
Chris Lattner0864acf2002-11-04 16:18:53 +000011514
Chris Lattner46238a62004-07-03 00:26:11 +000011515Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
11516 Value *Cond = SI.getCondition();
11517 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
11518 if (I->getOpcode() == Instruction::Add)
11519 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
11520 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
11521 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattnere87597f2004-10-16 18:11:37 +000011522 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +000011523 AddRHS));
11524 SI.setOperand(0, I->getOperand(0));
Chris Lattnerdbab3862007-03-02 21:28:56 +000011525 AddToWorkList(I);
Chris Lattner46238a62004-07-03 00:26:11 +000011526 return &SI;
11527 }
11528 }
11529 return 0;
11530}
11531
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000011532Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000011533 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000011534
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000011535 if (!EV.hasIndices())
11536 return ReplaceInstUsesWith(EV, Agg);
11537
11538 if (Constant *C = dyn_cast<Constant>(Agg)) {
11539 if (isa<UndefValue>(C))
11540 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
11541
11542 if (isa<ConstantAggregateZero>(C))
11543 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
11544
11545 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
11546 // Extract the element indexed by the first index out of the constant
11547 Value *V = C->getOperand(*EV.idx_begin());
11548 if (EV.getNumIndices() > 1)
11549 // Extract the remaining indices out of the constant indexed by the
11550 // first index
11551 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
11552 else
11553 return ReplaceInstUsesWith(EV, V);
11554 }
11555 return 0; // Can't handle other constants
11556 }
11557 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
11558 // We're extracting from an insertvalue instruction, compare the indices
11559 const unsigned *exti, *exte, *insi, *inse;
11560 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
11561 exte = EV.idx_end(), inse = IV->idx_end();
11562 exti != exte && insi != inse;
11563 ++exti, ++insi) {
11564 if (*insi != *exti)
11565 // The insert and extract both reference distinctly different elements.
11566 // This means the extract is not influenced by the insert, and we can
11567 // replace the aggregate operand of the extract with the aggregate
11568 // operand of the insert. i.e., replace
11569 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
11570 // %E = extractvalue { i32, { i32 } } %I, 0
11571 // with
11572 // %E = extractvalue { i32, { i32 } } %A, 0
11573 return ExtractValueInst::Create(IV->getAggregateOperand(),
11574 EV.idx_begin(), EV.idx_end());
11575 }
11576 if (exti == exte && insi == inse)
11577 // Both iterators are at the end: Index lists are identical. Replace
11578 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
11579 // %C = extractvalue { i32, { i32 } } %B, 1, 0
11580 // with "i32 42"
11581 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
11582 if (exti == exte) {
11583 // The extract list is a prefix of the insert list. i.e. replace
11584 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
11585 // %E = extractvalue { i32, { i32 } } %I, 1
11586 // with
11587 // %X = extractvalue { i32, { i32 } } %A, 1
11588 // %E = insertvalue { i32 } %X, i32 42, 0
11589 // by switching the order of the insert and extract (though the
11590 // insertvalue should be left in, since it may have other uses).
11591 Value *NewEV = InsertNewInstBefore(
11592 ExtractValueInst::Create(IV->getAggregateOperand(),
11593 EV.idx_begin(), EV.idx_end()),
11594 EV);
11595 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
11596 insi, inse);
11597 }
11598 if (insi == inse)
11599 // The insert list is a prefix of the extract list
11600 // We can simply remove the common indices from the extract and make it
11601 // operate on the inserted value instead of the insertvalue result.
11602 // i.e., replace
11603 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
11604 // %E = extractvalue { i32, { i32 } } %I, 1, 0
11605 // with
11606 // %E extractvalue { i32 } { i32 42 }, 0
11607 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
11608 exti, exte);
11609 }
11610 // Can't simplify extracts from other values. Note that nested extracts are
11611 // already simplified implicitely by the above (extract ( extract (insert) )
11612 // will be translated into extract ( insert ( extract ) ) first and then just
11613 // the value inserted, if appropriate).
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000011614 return 0;
11615}
11616
Chris Lattner220b0cf2006-03-05 00:22:33 +000011617/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
11618/// is to leave as a vector operation.
11619static bool CheapToScalarize(Value *V, bool isConstant) {
11620 if (isa<ConstantAggregateZero>(V))
11621 return true;
Reid Spencer9d6565a2007-02-15 02:26:10 +000011622 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000011623 if (isConstant) return true;
11624 // If all elts are the same, we can extract.
11625 Constant *Op0 = C->getOperand(0);
11626 for (unsigned i = 1; i < C->getNumOperands(); ++i)
11627 if (C->getOperand(i) != Op0)
11628 return false;
11629 return true;
11630 }
11631 Instruction *I = dyn_cast<Instruction>(V);
11632 if (!I) return false;
11633
11634 // Insert element gets simplified to the inserted element or is deleted if
11635 // this is constant idx extract element and its a constant idx insertelt.
11636 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
11637 isa<ConstantInt>(I->getOperand(2)))
11638 return true;
11639 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
11640 return true;
11641 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
11642 if (BO->hasOneUse() &&
11643 (CheapToScalarize(BO->getOperand(0), isConstant) ||
11644 CheapToScalarize(BO->getOperand(1), isConstant)))
11645 return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +000011646 if (CmpInst *CI = dyn_cast<CmpInst>(I))
11647 if (CI->hasOneUse() &&
11648 (CheapToScalarize(CI->getOperand(0), isConstant) ||
11649 CheapToScalarize(CI->getOperand(1), isConstant)))
11650 return true;
Chris Lattner220b0cf2006-03-05 00:22:33 +000011651
11652 return false;
11653}
11654
Chris Lattnerd2b7cec2007-02-14 05:52:17 +000011655/// Read and decode a shufflevector mask.
11656///
11657/// It turns undef elements into values that are larger than the number of
11658/// elements in the input.
Chris Lattner863bcff2006-05-25 23:48:38 +000011659static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
11660 unsigned NElts = SVI->getType()->getNumElements();
11661 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
11662 return std::vector<unsigned>(NElts, 0);
11663 if (isa<UndefValue>(SVI->getOperand(2)))
11664 return std::vector<unsigned>(NElts, 2*NElts);
11665
11666 std::vector<unsigned> Result;
Reid Spencer9d6565a2007-02-15 02:26:10 +000011667 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Gabor Greif177dd3f2008-06-12 21:37:33 +000011668 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
11669 if (isa<UndefValue>(*i))
Chris Lattner863bcff2006-05-25 23:48:38 +000011670 Result.push_back(NElts*2); // undef -> 8
11671 else
Gabor Greif177dd3f2008-06-12 21:37:33 +000011672 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
Chris Lattner863bcff2006-05-25 23:48:38 +000011673 return Result;
11674}
11675
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011676/// FindScalarElement - Given a vector and an element number, see if the scalar
11677/// value is already around as a register, for example if it were inserted then
11678/// extracted from the vector.
11679static Value *FindScalarElement(Value *V, unsigned EltNo) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000011680 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
11681 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +000011682 unsigned Width = PTy->getNumElements();
11683 if (EltNo >= Width) // Out of range access.
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011684 return UndefValue::get(PTy->getElementType());
11685
11686 if (isa<UndefValue>(V))
11687 return UndefValue::get(PTy->getElementType());
11688 else if (isa<ConstantAggregateZero>(V))
11689 return Constant::getNullValue(PTy->getElementType());
Reid Spencer9d6565a2007-02-15 02:26:10 +000011690 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011691 return CP->getOperand(EltNo);
11692 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
11693 // If this is an insert to a variable element, we don't know what it is.
Reid Spencerb83eb642006-10-20 07:07:24 +000011694 if (!isa<ConstantInt>(III->getOperand(2)))
11695 return 0;
11696 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011697
11698 // If this is an insert to the element we are looking for, return the
11699 // inserted value.
Reid Spencerb83eb642006-10-20 07:07:24 +000011700 if (EltNo == IIElt)
11701 return III->getOperand(1);
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011702
11703 // Otherwise, the insertelement doesn't modify the value, recurse on its
11704 // vector input.
11705 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner389a6f52006-04-10 23:06:36 +000011706 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Mon P Wangaeb06d22008-11-10 04:46:22 +000011707 unsigned LHSWidth =
11708 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
Chris Lattner863bcff2006-05-25 23:48:38 +000011709 unsigned InEl = getShuffleMask(SVI)[EltNo];
Mon P Wangaeb06d22008-11-10 04:46:22 +000011710 if (InEl < LHSWidth)
Chris Lattner863bcff2006-05-25 23:48:38 +000011711 return FindScalarElement(SVI->getOperand(0), InEl);
Mon P Wangaeb06d22008-11-10 04:46:22 +000011712 else if (InEl < LHSWidth*2)
11713 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth);
Chris Lattner863bcff2006-05-25 23:48:38 +000011714 else
11715 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011716 }
11717
11718 // Otherwise, we don't know.
11719 return 0;
11720}
11721
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011722Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Dan Gohman07a96762007-07-16 14:29:03 +000011723 // If vector val is undef, replace extract with scalar undef.
Chris Lattner1f13c882006-03-31 18:25:14 +000011724 if (isa<UndefValue>(EI.getOperand(0)))
11725 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
11726
Dan Gohman07a96762007-07-16 14:29:03 +000011727 // If vector val is constant 0, replace extract with scalar 0.
Chris Lattner1f13c882006-03-31 18:25:14 +000011728 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
11729 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
11730
Reid Spencer9d6565a2007-02-15 02:26:10 +000011731 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Matthijs Kooijmanb4d6a5a2008-06-11 09:00:12 +000011732 // If vector val is constant with all elements the same, replace EI with
11733 // that element. When the elements are not identical, we cannot replace yet
11734 // (we do that below, but only when the index is constant).
Chris Lattner220b0cf2006-03-05 00:22:33 +000011735 Constant *op0 = C->getOperand(0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011736 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +000011737 if (C->getOperand(i) != op0) {
11738 op0 = 0;
11739 break;
11740 }
11741 if (op0)
11742 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011743 }
Chris Lattner220b0cf2006-03-05 00:22:33 +000011744
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011745 // If extracting a specified index from the vector, see if we can recursively
11746 // find a previously computed scalar that was inserted into the vector.
Reid Spencerb83eb642006-10-20 07:07:24 +000011747 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner85464092007-04-09 01:37:55 +000011748 unsigned IndexVal = IdxC->getZExtValue();
11749 unsigned VectorWidth =
11750 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
11751
11752 // If this is extracting an invalid index, turn this into undef, to avoid
11753 // crashing the code below.
11754 if (IndexVal >= VectorWidth)
11755 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
11756
Chris Lattner867b99f2006-10-05 06:55:50 +000011757 // This instruction only demands the single element from the input vector.
11758 // If the input vector has a single use, simplify it based on this use
11759 // property.
Chris Lattner85464092007-04-09 01:37:55 +000011760 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Chris Lattner867b99f2006-10-05 06:55:50 +000011761 uint64_t UndefElts;
11762 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Reid Spencerb83eb642006-10-20 07:07:24 +000011763 1 << IndexVal,
Chris Lattner867b99f2006-10-05 06:55:50 +000011764 UndefElts)) {
11765 EI.setOperand(0, V);
11766 return &EI;
11767 }
11768 }
11769
Reid Spencerb83eb642006-10-20 07:07:24 +000011770 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011771 return ReplaceInstUsesWith(EI, Elt);
Chris Lattnerb7300fa2007-04-14 23:02:14 +000011772
11773 // If the this extractelement is directly using a bitcast from a vector of
11774 // the same number of elements, see if we can find the source element from
11775 // it. In this case, we will end up needing to bitcast the scalars.
11776 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
11777 if (const VectorType *VT =
11778 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
11779 if (VT->getNumElements() == VectorWidth)
11780 if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
11781 return new BitCastInst(Elt, EI.getType());
11782 }
Chris Lattner389a6f52006-04-10 23:06:36 +000011783 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011784
Chris Lattner73fa49d2006-05-25 22:53:38 +000011785 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011786 if (I->hasOneUse()) {
11787 // Push extractelement into predecessor operation if legal and
11788 // profitable to do so
11789 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000011790 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
11791 if (CheapToScalarize(BO, isConstantElt)) {
11792 ExtractElementInst *newEI0 =
11793 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
11794 EI.getName()+".lhs");
11795 ExtractElementInst *newEI1 =
11796 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
11797 EI.getName()+".rhs");
11798 InsertNewInstBefore(newEI0, EI);
11799 InsertNewInstBefore(newEI1, EI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000011800 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Chris Lattner220b0cf2006-03-05 00:22:33 +000011801 }
Reid Spencer3ed469c2006-11-02 20:25:50 +000011802 } else if (isa<LoadInst>(I)) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +000011803 unsigned AS =
11804 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +000011805 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
11806 PointerType::get(EI.getType(), AS),EI);
Gabor Greifb1dbcd82008-05-15 10:04:30 +000011807 GetElementPtrInst *GEP =
11808 GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011809 InsertNewInstBefore(GEP, EI);
11810 return new LoadInst(GEP);
Chris Lattner73fa49d2006-05-25 22:53:38 +000011811 }
11812 }
11813 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
11814 // Extracting the inserted element?
11815 if (IE->getOperand(2) == EI.getOperand(1))
11816 return ReplaceInstUsesWith(EI, IE->getOperand(1));
11817 // If the inserted and extracted elements are constants, they must not
11818 // be the same value, extract from the pre-inserted value instead.
11819 if (isa<Constant>(IE->getOperand(2)) &&
11820 isa<Constant>(EI.getOperand(1))) {
11821 AddUsesToWorkList(EI);
11822 EI.setOperand(0, IE->getOperand(0));
11823 return &EI;
11824 }
11825 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
11826 // If this is extracting an element from a shufflevector, figure out where
11827 // it came from and extract from the appropriate input element instead.
Reid Spencerb83eb642006-10-20 07:07:24 +000011828 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
11829 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner863bcff2006-05-25 23:48:38 +000011830 Value *Src;
Mon P Wangaeb06d22008-11-10 04:46:22 +000011831 unsigned LHSWidth =
11832 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
11833
11834 if (SrcIdx < LHSWidth)
Chris Lattner863bcff2006-05-25 23:48:38 +000011835 Src = SVI->getOperand(0);
Mon P Wangaeb06d22008-11-10 04:46:22 +000011836 else if (SrcIdx < LHSWidth*2) {
11837 SrcIdx -= LHSWidth;
Chris Lattner863bcff2006-05-25 23:48:38 +000011838 Src = SVI->getOperand(1);
11839 } else {
11840 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +000011841 }
Chris Lattner867b99f2006-10-05 06:55:50 +000011842 return new ExtractElementInst(Src, SrcIdx);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011843 }
11844 }
Chris Lattner73fa49d2006-05-25 22:53:38 +000011845 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011846 return 0;
11847}
11848
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011849/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
11850/// elements from either LHS or RHS, return the shuffle mask and true.
11851/// Otherwise, return false.
11852static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
11853 std::vector<Constant*> &Mask) {
11854 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
11855 "Invalid CollectSingleShuffleElements");
Reid Spencer9d6565a2007-02-15 02:26:10 +000011856 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011857
11858 if (isa<UndefValue>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000011859 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011860 return true;
11861 } else if (V == LHS) {
11862 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000011863 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011864 return true;
11865 } else if (V == RHS) {
11866 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000011867 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011868 return true;
11869 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
11870 // If this is an insert of an extract from some other vector, include it.
11871 Value *VecOp = IEI->getOperand(0);
11872 Value *ScalarOp = IEI->getOperand(1);
11873 Value *IdxOp = IEI->getOperand(2);
11874
Chris Lattnerd929f062006-04-27 21:14:21 +000011875 if (!isa<ConstantInt>(IdxOp))
11876 return false;
Reid Spencerb83eb642006-10-20 07:07:24 +000011877 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerd929f062006-04-27 21:14:21 +000011878
11879 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
11880 // Okay, we can handle this if the vector we are insertinting into is
11881 // transitively ok.
11882 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
11883 // If so, update the mask to reflect the inserted undef.
Reid Spencerc5b206b2006-12-31 05:48:39 +000011884 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
Chris Lattnerd929f062006-04-27 21:14:21 +000011885 return true;
11886 }
11887 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
11888 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011889 EI->getOperand(0)->getType() == V->getType()) {
11890 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000011891 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011892
11893 // This must be extracting from either LHS or RHS.
11894 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
11895 // Okay, we can handle this if the vector we are insertinting into is
11896 // transitively ok.
11897 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
11898 // If so, update the mask to reflect the inserted value.
11899 if (EI->getOperand(0) == LHS) {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000011900 Mask[InsertedIdx % NumElts] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000011901 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011902 } else {
11903 assert(EI->getOperand(0) == RHS);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000011904 Mask[InsertedIdx % NumElts] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000011905 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011906
11907 }
11908 return true;
11909 }
11910 }
11911 }
11912 }
11913 }
11914 // TODO: Handle shufflevector here!
11915
11916 return false;
11917}
11918
11919/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
11920/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
11921/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +000011922static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011923 Value *&RHS) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000011924 assert(isa<VectorType>(V->getType()) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011925 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +000011926 "Invalid shuffle!");
Reid Spencer9d6565a2007-02-15 02:26:10 +000011927 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattnerefb47352006-04-15 01:39:45 +000011928
11929 if (isa<UndefValue>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000011930 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000011931 return V;
11932 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000011933 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
Chris Lattnerefb47352006-04-15 01:39:45 +000011934 return V;
11935 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
11936 // If this is an insert of an extract from some other vector, include it.
11937 Value *VecOp = IEI->getOperand(0);
11938 Value *ScalarOp = IEI->getOperand(1);
11939 Value *IdxOp = IEI->getOperand(2);
11940
11941 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
11942 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
11943 EI->getOperand(0)->getType() == V->getType()) {
11944 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000011945 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
11946 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000011947
11948 // Either the extracted from or inserted into vector must be RHSVec,
11949 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011950 if (EI->getOperand(0) == RHS || RHS == 0) {
11951 RHS = EI->getOperand(0);
11952 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000011953 Mask[InsertedIdx % NumElts] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000011954 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000011955 return V;
11956 }
11957
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011958 if (VecOp == RHS) {
11959 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +000011960 // Everything but the extracted element is replaced with the RHS.
11961 for (unsigned i = 0; i != NumElts; ++i) {
11962 if (i != InsertedIdx)
Reid Spencerc5b206b2006-12-31 05:48:39 +000011963 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
Chris Lattnerefb47352006-04-15 01:39:45 +000011964 }
11965 return V;
11966 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011967
11968 // If this insertelement is a chain that comes from exactly these two
11969 // vectors, return the vector and the effective shuffle.
11970 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
11971 return EI->getOperand(0);
11972
Chris Lattnerefb47352006-04-15 01:39:45 +000011973 }
11974 }
11975 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011976 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +000011977
11978 // Otherwise, can't do anything fancy. Return an identity vector.
11979 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000011980 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattnerefb47352006-04-15 01:39:45 +000011981 return V;
11982}
11983
11984Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
11985 Value *VecOp = IE.getOperand(0);
11986 Value *ScalarOp = IE.getOperand(1);
11987 Value *IdxOp = IE.getOperand(2);
11988
Chris Lattner599ded12007-04-09 01:11:16 +000011989 // Inserting an undef or into an undefined place, remove this.
11990 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
11991 ReplaceInstUsesWith(IE, VecOp);
11992
Chris Lattnerefb47352006-04-15 01:39:45 +000011993 // If the inserted element was extracted from some other vector, and if the
11994 // indexes are constant, try to turn this into a shufflevector operation.
11995 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
11996 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
11997 EI->getOperand(0)->getType() == IE.getType()) {
11998 unsigned NumVectorElts = IE.getType()->getNumElements();
Chris Lattnere34e9a22007-04-14 23:32:02 +000011999 unsigned ExtractedIdx =
12000 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Reid Spencerb83eb642006-10-20 07:07:24 +000012001 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000012002
12003 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12004 return ReplaceInstUsesWith(IE, VecOp);
12005
12006 if (InsertedIdx >= NumVectorElts) // Out of range insert.
12007 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
12008
12009 // If we are extracting a value from a vector, then inserting it right
12010 // back into the same place, just use the input vector.
12011 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12012 return ReplaceInstUsesWith(IE, VecOp);
12013
12014 // We could theoretically do this for ANY input. However, doing so could
12015 // turn chains of insertelement instructions into a chain of shufflevector
12016 // instructions, and right now we do not merge shufflevectors. As such,
12017 // only do this in a situation where it is clear that there is benefit.
12018 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
12019 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
12020 // the values of VecOp, except then one read from EIOp0.
12021 // Build a new shuffle mask.
12022 std::vector<Constant*> Mask;
12023 if (isa<UndefValue>(VecOp))
Reid Spencerc5b206b2006-12-31 05:48:39 +000012024 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000012025 else {
12026 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Reid Spencerc5b206b2006-12-31 05:48:39 +000012027 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
Chris Lattnerefb47352006-04-15 01:39:45 +000012028 NumVectorElts));
12029 }
Reid Spencerc5b206b2006-12-31 05:48:39 +000012030 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000012031 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Reid Spencer9d6565a2007-02-15 02:26:10 +000012032 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000012033 }
12034
12035 // If this insertelement isn't used by some other insertelement, turn it
12036 // (and any insertelements it points to), into one big shuffle.
12037 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12038 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012039 Value *RHS = 0;
12040 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
12041 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
12042 // We now have a shuffle of LHS, RHS, Mask.
Reid Spencer9d6565a2007-02-15 02:26:10 +000012043 return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000012044 }
12045 }
12046 }
12047
12048 return 0;
12049}
12050
12051
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012052Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12053 Value *LHS = SVI.getOperand(0);
12054 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +000012055 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012056
12057 bool MadeChange = false;
Mon P Wangaeb06d22008-11-10 04:46:22 +000012058
Chris Lattner867b99f2006-10-05 06:55:50 +000012059 // Undefined shuffle mask -> undefined value.
Chris Lattner863bcff2006-05-25 23:48:38 +000012060 if (isa<UndefValue>(SVI.getOperand(2)))
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012061 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
Dan Gohman488fbfc2008-09-09 18:11:14 +000012062
12063 uint64_t UndefElts;
12064 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
Mon P Wangaeb06d22008-11-10 04:46:22 +000012065
12066 if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12067 return 0;
12068
Dan Gohman488fbfc2008-09-09 18:11:14 +000012069 uint64_t AllOnesEltMask = ~0ULL >> (64-VWidth);
12070 if (VWidth <= 64 &&
Dan Gohman3139ff82008-09-11 22:47:57 +000012071 SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
12072 LHS = SVI.getOperand(0);
12073 RHS = SVI.getOperand(1);
Dan Gohman488fbfc2008-09-09 18:11:14 +000012074 MadeChange = true;
Dan Gohman3139ff82008-09-11 22:47:57 +000012075 }
Chris Lattnerefb47352006-04-15 01:39:45 +000012076
Chris Lattner863bcff2006-05-25 23:48:38 +000012077 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
12078 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12079 if (LHS == RHS || isa<UndefValue>(LHS)) {
12080 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012081 // shuffle(undef,undef,mask) -> undef.
12082 return ReplaceInstUsesWith(SVI, LHS);
12083 }
12084
Chris Lattner863bcff2006-05-25 23:48:38 +000012085 // Remap any references to RHS to use LHS.
12086 std::vector<Constant*> Elts;
12087 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000012088 if (Mask[i] >= 2*e)
Reid Spencerc5b206b2006-12-31 05:48:39 +000012089 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012090 else {
12091 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
Dan Gohman4ce96272008-08-06 18:17:32 +000012092 (Mask[i] < e && isa<UndefValue>(LHS))) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000012093 Mask[i] = 2*e; // Turn into undef.
Dan Gohman4ce96272008-08-06 18:17:32 +000012094 Elts.push_back(UndefValue::get(Type::Int32Ty));
12095 } else {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012096 Mask[i] = Mask[i] % e; // Force to LHS.
Dan Gohman4ce96272008-08-06 18:17:32 +000012097 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
12098 }
Chris Lattner7b2e27922006-05-26 00:29:06 +000012099 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012100 }
Chris Lattner863bcff2006-05-25 23:48:38 +000012101 SVI.setOperand(0, SVI.getOperand(1));
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012102 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Reid Spencer9d6565a2007-02-15 02:26:10 +000012103 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012104 LHS = SVI.getOperand(0);
12105 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012106 MadeChange = true;
12107 }
12108
Chris Lattner7b2e27922006-05-26 00:29:06 +000012109 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +000012110 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +000012111
Chris Lattner863bcff2006-05-25 23:48:38 +000012112 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12113 if (Mask[i] >= e*2) continue; // Ignore undef values.
12114 // Is this an identity shuffle of the LHS value?
12115 isLHSID &= (Mask[i] == i);
12116
12117 // Is this an identity shuffle of the RHS value?
12118 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +000012119 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012120
Chris Lattner863bcff2006-05-25 23:48:38 +000012121 // Eliminate identity shuffles.
12122 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12123 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012124
Chris Lattner7b2e27922006-05-26 00:29:06 +000012125 // If the LHS is a shufflevector itself, see if we can combine it with this
12126 // one without producing an unusual shuffle. Here we are really conservative:
12127 // we are absolutely afraid of producing a shuffle mask not in the input
12128 // program, because the code gen may not be smart enough to turn a merged
12129 // shuffle into two specific shuffles: it may produce worse code. As such,
12130 // we only merge two shuffles if the result is one of the two input shuffle
12131 // masks. In this case, merging the shuffles just removes one instruction,
12132 // which we know is safe. This is good for things like turning:
12133 // (splat(splat)) -> splat.
12134 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12135 if (isa<UndefValue>(RHS)) {
12136 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12137
12138 std::vector<unsigned> NewMask;
12139 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12140 if (Mask[i] >= 2*e)
12141 NewMask.push_back(2*e);
12142 else
12143 NewMask.push_back(LHSMask[Mask[i]]);
12144
12145 // If the result mask is equal to the src shuffle or this shuffle mask, do
12146 // the replacement.
12147 if (NewMask == LHSMask || NewMask == Mask) {
Mon P Wangfe6d2cd2009-01-26 04:39:00 +000012148 unsigned LHSInNElts =
12149 cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
Chris Lattner7b2e27922006-05-26 00:29:06 +000012150 std::vector<Constant*> Elts;
12151 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
Mon P Wangfe6d2cd2009-01-26 04:39:00 +000012152 if (NewMask[i] >= LHSInNElts*2) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000012153 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012154 } else {
Reid Spencerc5b206b2006-12-31 05:48:39 +000012155 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012156 }
12157 }
12158 return new ShuffleVectorInst(LHSSVI->getOperand(0),
12159 LHSSVI->getOperand(1),
Reid Spencer9d6565a2007-02-15 02:26:10 +000012160 ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012161 }
12162 }
12163 }
Chris Lattnerc5eff442007-01-30 22:32:46 +000012164
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012165 return MadeChange ? &SVI : 0;
12166}
12167
12168
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012169
Chris Lattnerea1c4542004-12-08 23:43:58 +000012170
12171/// TryToSinkInstruction - Try to move the specified instruction from its
12172/// current block into the beginning of DestBlock, which can only happen if it's
12173/// safe to move the instruction past all of the instructions between it and the
12174/// end of its block.
12175static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12176 assert(I->hasOneUse() && "Invariants didn't hold!");
12177
Chris Lattner108e9022005-10-27 17:13:11 +000012178 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Chris Lattnerbfc538c2008-05-09 15:07:33 +000012179 if (isa<PHINode>(I) || I->mayWriteToMemory() || isa<TerminatorInst>(I))
12180 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +000012181
Chris Lattnerea1c4542004-12-08 23:43:58 +000012182 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +000012183 if (isa<AllocaInst>(I) && I->getParent() ==
12184 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +000012185 return false;
12186
Chris Lattner96a52a62004-12-09 07:14:34 +000012187 // We can only sink load instructions if there is nothing between the load and
12188 // the end of block that could change the value.
Chris Lattner2539e332008-05-08 17:37:37 +000012189 if (I->mayReadFromMemory()) {
12190 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Chris Lattner96a52a62004-12-09 07:14:34 +000012191 Scan != E; ++Scan)
12192 if (Scan->mayWriteToMemory())
12193 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +000012194 }
Chris Lattnerea1c4542004-12-08 23:43:58 +000012195
Dan Gohman02dea8b2008-05-23 21:05:58 +000012196 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Chris Lattnerea1c4542004-12-08 23:43:58 +000012197
Chris Lattner4bc5f802005-08-08 19:11:57 +000012198 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +000012199 ++NumSunkInst;
12200 return true;
12201}
12202
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012203
12204/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12205/// all reachable code to the worklist.
12206///
12207/// This has a couple of tricks to make the code faster and more powerful. In
12208/// particular, we constant fold and DCE instructions as we go, to avoid adding
12209/// them to the worklist (this significantly speeds up instcombine on code where
12210/// many instructions are dead or constant). Additionally, if we find a branch
12211/// whose condition is a known constant, we only visit the reachable successors.
12212///
12213static void AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +000012214 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +000012215 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012216 const TargetData *TD) {
Chris Lattner2806dff2008-08-15 04:03:01 +000012217 SmallVector<BasicBlock*, 256> Worklist;
Chris Lattner2c7718a2007-03-23 19:17:18 +000012218 Worklist.push_back(BB);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012219
Chris Lattner2c7718a2007-03-23 19:17:18 +000012220 while (!Worklist.empty()) {
12221 BB = Worklist.back();
12222 Worklist.pop_back();
12223
12224 // We have now visited this block! If we've already been here, ignore it.
12225 if (!Visited.insert(BB)) continue;
Devang Patel7fe1dec2008-11-19 18:56:50 +000012226
12227 DbgInfoIntrinsic *DBI_Prev = NULL;
Chris Lattner2c7718a2007-03-23 19:17:18 +000012228 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12229 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012230
Chris Lattner2c7718a2007-03-23 19:17:18 +000012231 // DCE instruction if trivially dead.
12232 if (isInstructionTriviallyDead(Inst)) {
12233 ++NumDeadInst;
12234 DOUT << "IC: DCE: " << *Inst;
12235 Inst->eraseFromParent();
12236 continue;
12237 }
12238
12239 // ConstantProp instruction if trivially constant.
12240 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
12241 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
12242 Inst->replaceAllUsesWith(C);
12243 ++NumConstProp;
12244 Inst->eraseFromParent();
12245 continue;
12246 }
Chris Lattner3ccc6bc2007-07-20 22:06:41 +000012247
Devang Patel7fe1dec2008-11-19 18:56:50 +000012248 // If there are two consecutive llvm.dbg.stoppoint calls then
12249 // it is likely that the optimizer deleted code in between these
12250 // two intrinsics.
12251 DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12252 if (DBI_Next) {
12253 if (DBI_Prev
12254 && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12255 && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
12256 IC.RemoveFromWorkList(DBI_Prev);
12257 DBI_Prev->eraseFromParent();
12258 }
12259 DBI_Prev = DBI_Next;
12260 }
12261
Chris Lattner2c7718a2007-03-23 19:17:18 +000012262 IC.AddToWorkList(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012263 }
Chris Lattner2c7718a2007-03-23 19:17:18 +000012264
12265 // Recursively visit successors. If this is a branch or switch on a
12266 // constant, only visit the reachable successor.
12267 TerminatorInst *TI = BB->getTerminator();
12268 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12269 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12270 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky91436992008-03-09 08:50:23 +000012271 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewycky280a6e62008-04-25 16:53:59 +000012272 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000012273 continue;
12274 }
12275 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12276 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12277 // See if this is an explicit destination.
12278 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12279 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky91436992008-03-09 08:50:23 +000012280 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewycky280a6e62008-04-25 16:53:59 +000012281 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000012282 continue;
12283 }
12284
12285 // Otherwise it is the default destination.
12286 Worklist.push_back(SI->getSuccessor(0));
12287 continue;
12288 }
12289 }
12290
12291 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12292 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012293 }
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012294}
12295
Chris Lattnerec9c3582007-03-03 02:04:50 +000012296bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012297 bool Changed = false;
Chris Lattnerbc61e662003-11-02 05:57:39 +000012298 TD = &getAnalysis<TargetData>();
Chris Lattnerec9c3582007-03-03 02:04:50 +000012299
12300 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12301 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +000012302
Chris Lattnerb3d59702005-07-07 20:40:38 +000012303 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012304 // Do a depth-first traversal of the function, populate the worklist with
12305 // the reachable instructions. Ignore blocks that are not reachable. Keep
12306 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +000012307 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerdbab3862007-03-02 21:28:56 +000012308 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +000012309
Chris Lattnerb3d59702005-07-07 20:40:38 +000012310 // Do a quick scan over the function. If we find any blocks that are
12311 // unreachable, remove any instructions inside of them. This prevents
12312 // the instcombine code from having to deal with some bad special cases.
12313 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12314 if (!Visited.count(BB)) {
12315 Instruction *Term = BB->getTerminator();
12316 while (Term != BB->begin()) { // Remove instrs bottom-up
12317 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +000012318
Bill Wendlingb7427032006-11-26 09:46:52 +000012319 DOUT << "IC: DCE: " << *I;
Chris Lattnerb3d59702005-07-07 20:40:38 +000012320 ++NumDeadInst;
12321
12322 if (!I->use_empty())
12323 I->replaceAllUsesWith(UndefValue::get(I->getType()));
12324 I->eraseFromParent();
Chris Lattner1e19d602009-01-31 07:04:22 +000012325 Changed = true;
Chris Lattnerb3d59702005-07-07 20:40:38 +000012326 }
12327 }
12328 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000012329
Chris Lattnerdbab3862007-03-02 21:28:56 +000012330 while (!Worklist.empty()) {
12331 Instruction *I = RemoveOneFromWorkList();
12332 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +000012333
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012334 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +000012335 if (isInstructionTriviallyDead(I)) {
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012336 // Add operands to the worklist.
Chris Lattner4bb7c022003-10-06 17:11:01 +000012337 if (I->getNumOperands() < 4)
Chris Lattner7bcc0e72004-02-28 05:22:00 +000012338 AddUsesToWorkList(*I);
Chris Lattner62b14df2002-09-02 04:59:56 +000012339 ++NumDeadInst;
Chris Lattner4bb7c022003-10-06 17:11:01 +000012340
Bill Wendlingb7427032006-11-26 09:46:52 +000012341 DOUT << "IC: DCE: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000012342
12343 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000012344 RemoveFromWorkList(I);
Chris Lattner1e19d602009-01-31 07:04:22 +000012345 Changed = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +000012346 continue;
12347 }
Chris Lattner62b14df2002-09-02 04:59:56 +000012348
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012349 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattner0a19ffa2007-01-30 23:16:15 +000012350 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Bill Wendlingb7427032006-11-26 09:46:52 +000012351 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000012352
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012353 // Add operands to the worklist.
Chris Lattner7bcc0e72004-02-28 05:22:00 +000012354 AddUsesToWorkList(*I);
Chris Lattnerc736d562002-12-05 22:41:53 +000012355 ReplaceInstUsesWith(*I, C);
12356
Chris Lattner62b14df2002-09-02 04:59:56 +000012357 ++NumConstProp;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012358 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000012359 RemoveFromWorkList(I);
Chris Lattner1e19d602009-01-31 07:04:22 +000012360 Changed = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +000012361 continue;
Chris Lattner62b14df2002-09-02 04:59:56 +000012362 }
Chris Lattner4bb7c022003-10-06 17:11:01 +000012363
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +000012364 if (TD && I->getType()->getTypeID() == Type::VoidTyID) {
12365 // See if we can constant fold its operands.
Chris Lattner1e19d602009-01-31 07:04:22 +000012366 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
12367 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i))
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +000012368 if (Constant *NewC = ConstantFoldConstantExpression(CE, TD))
Chris Lattner1e19d602009-01-31 07:04:22 +000012369 if (NewC != CE) {
12370 i->set(NewC);
12371 Changed = true;
12372 }
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +000012373 }
12374
Chris Lattnerea1c4542004-12-08 23:43:58 +000012375 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohmanfc74abf2008-07-23 00:34:11 +000012376 if (I->hasOneUse()) {
Chris Lattnerea1c4542004-12-08 23:43:58 +000012377 BasicBlock *BB = I->getParent();
12378 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
12379 if (UserParent != BB) {
12380 bool UserIsSuccessor = false;
12381 // See if the user is one of our successors.
12382 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
12383 if (*SI == UserParent) {
12384 UserIsSuccessor = true;
12385 break;
12386 }
12387
12388 // If the user is one of our immediate successors, and if that successor
12389 // only has us as a predecessors (we'd have to split the critical edge
12390 // otherwise), we can keep going.
12391 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
12392 next(pred_begin(UserParent)) == pred_end(UserParent))
12393 // Okay, the CFG is simple enough, try to sink this instruction.
12394 Changed |= TryToSinkInstruction(I, UserParent);
12395 }
12396 }
12397
Chris Lattner8a2a3112001-12-14 16:52:21 +000012398 // Now that we have an instruction, try combining it to simplify it...
Reid Spencera9b81012007-03-26 17:44:01 +000012399#ifndef NDEBUG
12400 std::string OrigI;
12401#endif
12402 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
Chris Lattner90ac28c2002-08-02 19:29:35 +000012403 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +000012404 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012405 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000012406 if (Result != I) {
Bill Wendlingb7427032006-11-26 09:46:52 +000012407 DOUT << "IC: Old = " << *I
12408 << " New = " << *Result;
Chris Lattner0cea42a2004-03-13 23:54:27 +000012409
Chris Lattnerf523d062004-06-09 05:08:07 +000012410 // Everything uses the new instruction now.
12411 I->replaceAllUsesWith(Result);
12412
12413 // Push the new instruction and any users onto the worklist.
Chris Lattnerdbab3862007-03-02 21:28:56 +000012414 AddToWorkList(Result);
Chris Lattnerf523d062004-06-09 05:08:07 +000012415 AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000012416
Chris Lattner6934a042007-02-11 01:23:03 +000012417 // Move the name to the new instruction first.
12418 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000012419
12420 // Insert the new instruction into the basic block...
12421 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +000012422 BasicBlock::iterator InsertPos = I;
12423
12424 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
12425 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
12426 ++InsertPos;
12427
12428 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000012429
Chris Lattner00d51312004-05-01 23:27:23 +000012430 // Make sure that we reprocess all operands now that we reduced their
12431 // use counts.
Chris Lattnerdbab3862007-03-02 21:28:56 +000012432 AddUsesToWorkList(*I);
Chris Lattner216d4d82004-05-01 23:19:52 +000012433
Chris Lattnerf523d062004-06-09 05:08:07 +000012434 // Instructions can end up on the worklist more than once. Make sure
12435 // we do not process an instruction that has been deleted.
Chris Lattnerdbab3862007-03-02 21:28:56 +000012436 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000012437
12438 // Erase the old instruction.
12439 InstParent->getInstList().erase(I);
Chris Lattner7e708292002-06-25 16:13:24 +000012440 } else {
Evan Chengc7baf682007-03-27 16:44:48 +000012441#ifndef NDEBUG
Reid Spencera9b81012007-03-26 17:44:01 +000012442 DOUT << "IC: Mod = " << OrigI
12443 << " New = " << *I;
Evan Chengc7baf682007-03-27 16:44:48 +000012444#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +000012445
Chris Lattner90ac28c2002-08-02 19:29:35 +000012446 // If the instruction was modified, it's possible that it is now dead.
12447 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +000012448 if (isInstructionTriviallyDead(I)) {
12449 // Make sure we process all operands now that we are reducing their
12450 // use counts.
Chris Lattnerec9c3582007-03-03 02:04:50 +000012451 AddUsesToWorkList(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000012452
Chris Lattner00d51312004-05-01 23:27:23 +000012453 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012454 // occurrences of this instruction.
Chris Lattnerdbab3862007-03-02 21:28:56 +000012455 RemoveFromWorkList(I);
Chris Lattner2f503e62005-01-31 05:36:43 +000012456 I->eraseFromParent();
Chris Lattnerf523d062004-06-09 05:08:07 +000012457 } else {
Chris Lattnerec9c3582007-03-03 02:04:50 +000012458 AddToWorkList(I);
12459 AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +000012460 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000012461 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012462 Changed = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +000012463 }
12464 }
12465
Chris Lattnerec9c3582007-03-03 02:04:50 +000012466 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattnera9ff5eb2007-08-05 08:47:58 +000012467
12468 // Do an explicit clear, this shrinks the map if needed.
12469 WorklistMap.clear();
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012470 return Changed;
Chris Lattnerbd0ef772002-02-26 21:46:54 +000012471}
12472
Chris Lattnerec9c3582007-03-03 02:04:50 +000012473
12474bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +000012475 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
12476
Chris Lattnerec9c3582007-03-03 02:04:50 +000012477 bool EverMadeChange = false;
12478
12479 // Iterate while there is work to do.
12480 unsigned Iteration = 0;
Bill Wendlinga6c31122008-05-14 22:45:20 +000012481 while (DoOneIteration(F, Iteration++))
Chris Lattnerec9c3582007-03-03 02:04:50 +000012482 EverMadeChange = true;
12483 return EverMadeChange;
12484}
12485
Brian Gaeke96d4bf72004-07-27 17:43:21 +000012486FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012487 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +000012488}