blob: b80fc4991afd15ad3b036792c026b68cf9c0d958 [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);
Chris Lattnera0e69692009-03-24 18:35:40 +0000221 Instruction *visitPtrToInt(PtrToIntInst &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);
Evan Chengde621922009-03-31 20:42:45 +0000226 Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
Dan Gohman81b28ce2008-09-16 18:46:06 +0000227 Instruction *visitSelectInst(SelectInst &SI);
228 Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
Chris Lattner9fe38862003-06-19 17:00:31 +0000229 Instruction *visitCallInst(CallInst &CI);
230 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner7e708292002-06-25 16:13:24 +0000231 Instruction *visitPHINode(PHINode &PN);
232 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner0864acf2002-11-04 16:18:53 +0000233 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner67b1e1b2003-12-07 01:24:23 +0000234 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner833b8a42003-06-26 05:06:25 +0000235 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner2f503e62005-01-31 05:36:43 +0000236 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattnerc4d10eb2003-06-04 04:46:00 +0000237 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner46238a62004-07-03 00:26:11 +0000238 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattnerefb47352006-04-15 01:39:45 +0000239 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchino1d7456d2006-01-13 22:48:06 +0000240 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +0000241 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000242 Instruction *visitExtractValueInst(ExtractValueInst &EV);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000243
244 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner7e708292002-06-25 16:13:24 +0000245 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner8b170942002-08-09 23:47:40 +0000246
Chris Lattner9fe38862003-06-19 17:00:31 +0000247 private:
Chris Lattnera44d8a22003-10-07 22:32:43 +0000248 Instruction *visitCallSite(CallSite CS);
Chris Lattner9fe38862003-06-19 17:00:31 +0000249 bool transformConstExprCastCall(CallSite CS);
Duncan Sandscdb6d922007-09-17 10:26:40 +0000250 Instruction *transformCallThroughTrampoline(CallSite CS);
Evan Chengb98a10e2008-03-24 00:21:34 +0000251 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
252 bool DoXform = true);
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000253 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
Dale Johannesen4945c652009-03-03 21:26:39 +0000254 DbgDeclareInst *hasOneUsePlusDeclare(Value *V);
255
Chris Lattner9fe38862003-06-19 17:00:31 +0000256
Chris Lattner28977af2004-04-05 01:30:19 +0000257 public:
Chris Lattner8b170942002-08-09 23:47:40 +0000258 // InsertNewInstBefore - insert an instruction New before instruction Old
259 // in the program. Add the new instruction to the worklist.
260 //
Chris Lattner955f3312004-09-28 21:48:02 +0000261 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattnere6f9a912002-08-23 18:32:43 +0000262 assert(New && New->getParent() == 0 &&
263 "New instruction already inserted into a basic block!");
Chris Lattner8b170942002-08-09 23:47:40 +0000264 BasicBlock *BB = Old.getParent();
265 BB->getInstList().insert(&Old, New); // Insert inst
Chris Lattnerdbab3862007-03-02 21:28:56 +0000266 AddToWorkList(New);
Chris Lattner4cb170c2004-02-23 06:38:22 +0000267 return New;
Chris Lattner8b170942002-08-09 23:47:40 +0000268 }
269
Chris Lattner0c967662004-09-24 15:21:34 +0000270 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
271 /// This also adds the cast to the worklist. Finally, this returns the
272 /// cast.
Reid Spencer17212df2006-12-12 09:18:51 +0000273 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
274 Instruction &Pos) {
Chris Lattner0c967662004-09-24 15:21:34 +0000275 if (V->getType() == Ty) return V;
Misha Brukmanfd939082005-04-21 23:48:37 +0000276
Chris Lattnere2ed0572006-04-06 19:19:17 +0000277 if (Constant *CV = dyn_cast<Constant>(V))
Reid Spencer17212df2006-12-12 09:18:51 +0000278 return ConstantExpr::getCast(opc, CV, Ty);
Chris Lattnere2ed0572006-04-06 19:19:17 +0000279
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000280 Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000281 AddToWorkList(C);
Chris Lattner0c967662004-09-24 15:21:34 +0000282 return C;
283 }
Chris Lattner6d0339d2008-01-13 22:23:22 +0000284
285 Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
286 return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
287 }
288
Chris Lattner0c967662004-09-24 15:21:34 +0000289
Chris Lattner8b170942002-08-09 23:47:40 +0000290 // ReplaceInstUsesWith - This method is to be used when an instruction is
291 // found to be dead, replacable with another preexisting expression. Here
292 // we add all uses of I to the worklist, replace all uses of I with the new
293 // value, then return I, so that the inst combiner will know that I was
294 // modified.
295 //
296 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000297 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner15a76c02004-04-05 02:10:19 +0000298 if (&I != V) {
299 I.replaceAllUsesWith(V);
300 return &I;
301 } else {
302 // If we are replacing the instruction with itself, this must be in a
303 // segment of unreachable code, so just clobber the instruction.
Chris Lattner17be6352004-10-18 02:59:09 +0000304 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +0000305 return &I;
306 }
Chris Lattner8b170942002-08-09 23:47:40 +0000307 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000308
309 // EraseInstFromFunction - When dealing with an instruction that has side
310 // effects or produces a void value, we can't rely on DCE to delete the
311 // instruction. Instead, visit methods should return the value returned by
312 // this function.
313 Instruction *EraseInstFromFunction(Instruction &I) {
314 assert(I.use_empty() && "Cannot erase instruction that is used!");
315 AddUsesToWorkList(I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000316 RemoveFromWorkList(&I);
Chris Lattner954f66a2004-11-18 21:41:39 +0000317 I.eraseFromParent();
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000318 return 0; // Don't do anything with FI
319 }
Chris Lattner173234a2008-06-02 01:18:21 +0000320
321 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
322 APInt &KnownOne, unsigned Depth = 0) const {
323 return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
324 }
325
326 bool MaskedValueIsZero(Value *V, const APInt &Mask,
327 unsigned Depth = 0) const {
328 return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
329 }
330 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
331 return llvm::ComputeNumSignBits(Op, TD, Depth);
332 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000333
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000334 private:
Chris Lattner24c8e382003-07-24 17:35:25 +0000335
Reid Spencere4d87aa2006-12-23 06:05:41 +0000336 /// SimplifyCommutative - This performs a few simplifications for
337 /// commutative operators.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000338 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000339
Reid Spencere4d87aa2006-12-23 06:05:41 +0000340 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
341 /// most-complex to least-complex order.
342 bool SimplifyCompare(CmpInst &I);
343
Chris Lattner886ab6c2009-01-31 08:15:18 +0000344 /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
345 /// based on the demanded bits.
346 Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
347 APInt& KnownZero, APInt& KnownOne,
348 unsigned Depth);
349 bool SimplifyDemandedBits(Use &U, APInt DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +0000350 APInt& KnownZero, APInt& KnownOne,
Chris Lattner886ab6c2009-01-31 08:15:18 +0000351 unsigned Depth=0);
352
353 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
354 /// SimplifyDemandedBits knows about. See if the instruction has any
355 /// properties that allow us to simplify its operands.
356 bool SimplifyDemandedInstructionBits(Instruction &Inst);
357
Evan Cheng388df622009-02-03 10:05:09 +0000358 Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
359 APInt& UndefElts, unsigned Depth = 0);
Chris Lattner867b99f2006-10-05 06:55:50 +0000360
Chris Lattner4e998b22004-09-29 05:07:12 +0000361 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
362 // PHI node as operand #0, see if we can fold the instruction into the PHI
363 // (which is only possible if all operands to the PHI are constants).
364 Instruction *FoldOpIntoPhi(Instruction &I);
365
Chris Lattnerbac32862004-11-14 19:13:23 +0000366 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
367 // operator and they all are only used by the PHI, PHI together their
368 // inputs, and do the operation once, to the result of the PHI.
369 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
Chris Lattner7da52b22006-11-01 04:51:18 +0000370 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
Chris Lattner05f18922008-12-01 02:34:36 +0000371 Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
372
Chris Lattner7da52b22006-11-01 04:51:18 +0000373
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000374 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
375 ConstantInt *AndRHS, BinaryOperator &TheAnd);
Chris Lattnerc8e77562005-09-18 04:24:45 +0000376
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000377 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
Chris Lattnerc8e77562005-09-18 04:24:45 +0000378 bool isSub, Instruction &I);
Chris Lattnera96879a2004-09-29 17:40:11 +0000379 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000380 bool isSigned, bool Inside, Instruction &IB);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000381 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
Chris Lattnerafe91a52006-06-15 19:07:26 +0000382 Instruction *MatchBSwap(BinaryOperator &I);
Chris Lattner3284d1f2007-04-15 00:07:55 +0000383 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000384 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +0000385 Instruction *SimplifyMemSet(MemSetInst *MI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000386
Chris Lattnerafe91a52006-06-15 19:07:26 +0000387
Reid Spencerc55b2432006-12-13 18:21:21 +0000388 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000389
Dan Gohmaneee962e2008-04-10 18:43:06 +0000390 bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
Evan Cheng4e56ab22009-01-16 02:11:43 +0000391 unsigned CastOpc, int &NumCastsRemoved);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000392 unsigned GetOrEnforceKnownAlignment(Value *V,
393 unsigned PrefAlign = 0);
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000394
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000395 };
396}
397
Dan Gohman844731a2008-05-13 00:00:25 +0000398char InstCombiner::ID = 0;
399static RegisterPass<InstCombiner>
400X("instcombine", "Combine redundant instructions");
401
Chris Lattner4f98c562003-03-10 21:43:22 +0000402// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattnere87597f2004-10-16 18:11:37 +0000403// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattner4f98c562003-03-10 21:43:22 +0000404static unsigned getComplexity(Value *V) {
405 if (isa<Instruction>(V)) {
406 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattnere87597f2004-10-16 18:11:37 +0000407 return 3;
408 return 4;
Chris Lattner4f98c562003-03-10 21:43:22 +0000409 }
Chris Lattnere87597f2004-10-16 18:11:37 +0000410 if (isa<Argument>(V)) return 3;
411 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattner4f98c562003-03-10 21:43:22 +0000412}
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000413
Chris Lattnerc8802d22003-03-11 00:12:48 +0000414// isOnlyUse - Return true if this instruction will be deleted if we stop using
415// it.
416static bool isOnlyUse(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000417 return V->hasOneUse() || isa<Constant>(V);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000418}
419
Chris Lattner4cb170c2004-02-23 06:38:22 +0000420// getPromotedType - Return the specified type promoted as it would be to pass
421// though a va_arg area...
422static const Type *getPromotedType(const Type *Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000423 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
424 if (ITy->getBitWidth() < 32)
425 return Type::Int32Ty;
Chris Lattner2b7e0ad2007-05-23 01:17:04 +0000426 }
Reid Spencera54b7cb2007-01-12 07:05:14 +0000427 return Ty;
Chris Lattner4cb170c2004-02-23 06:38:22 +0000428}
429
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000430/// getBitCastOperand - If the specified operand is a CastInst, a constant
431/// expression bitcast, or a GetElementPtrInst with all zero indices, return the
432/// operand value, otherwise return null.
Reid Spencer3da59db2006-11-27 01:05:10 +0000433static Value *getBitCastOperand(Value *V) {
434 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000435 // BitCastInst?
Chris Lattnereed48272005-09-13 00:40:14 +0000436 return I->getOperand(0);
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000437 else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(V)) {
438 // GetElementPtrInst?
439 if (GEP->hasAllZeroIndices())
440 return GEP->getOperand(0);
441 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
Reid Spencer3da59db2006-11-27 01:05:10 +0000442 if (CE->getOpcode() == Instruction::BitCast)
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000443 // BitCast ConstantExp?
Chris Lattnereed48272005-09-13 00:40:14 +0000444 return CE->getOperand(0);
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000445 else if (CE->getOpcode() == Instruction::GetElementPtr) {
446 // GetElementPtr ConstantExp?
447 for (User::op_iterator I = CE->op_begin() + 1, E = CE->op_end();
448 I != E; ++I) {
449 ConstantInt *CI = dyn_cast<ConstantInt>(I);
450 if (!CI || !CI->isZero())
451 // Any non-zero indices? Not cast-like.
452 return 0;
453 }
454 // All-zero indices? This is just like casting.
455 return CE->getOperand(0);
456 }
457 }
Chris Lattnereed48272005-09-13 00:40:14 +0000458 return 0;
459}
460
Reid Spencer3da59db2006-11-27 01:05:10 +0000461/// This function is a wrapper around CastInst::isEliminableCastPair. It
462/// simply extracts arguments and returns what that function returns.
Reid Spencer3da59db2006-11-27 01:05:10 +0000463static Instruction::CastOps
464isEliminableCastPair(
465 const CastInst *CI, ///< The first cast instruction
466 unsigned opcode, ///< The opcode of the second cast instruction
467 const Type *DstTy, ///< The target type for the second cast instruction
468 TargetData *TD ///< The target data for pointer size
469) {
470
471 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
472 const Type *MidTy = CI->getType(); // B from above
Chris Lattner33a61132006-05-06 09:00:16 +0000473
Reid Spencer3da59db2006-11-27 01:05:10 +0000474 // Get the opcodes of the two Cast instructions
475 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
476 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner33a61132006-05-06 09:00:16 +0000477
Chris Lattnera0e69692009-03-24 18:35:40 +0000478 unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
479 DstTy, TD->getIntPtrType());
480
481 // We don't want to form an inttoptr or ptrtoint that converts to an integer
482 // type that differs from the pointer size.
483 if ((Res == Instruction::IntToPtr && SrcTy != TD->getIntPtrType()) ||
484 (Res == Instruction::PtrToInt && DstTy != TD->getIntPtrType()))
485 Res = 0;
486
487 return Instruction::CastOps(Res);
Chris Lattner33a61132006-05-06 09:00:16 +0000488}
489
490/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
491/// in any code being generated. It does not require codegen if V is simple
492/// enough or if the cast can be folded into other casts.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000493static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
494 const Type *Ty, TargetData *TD) {
Chris Lattner33a61132006-05-06 09:00:16 +0000495 if (V->getType() == Ty || isa<Constant>(V)) return false;
496
Chris Lattner01575b72006-05-25 23:24:33 +0000497 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner33a61132006-05-06 09:00:16 +0000498 if (const CastInst *CI = dyn_cast<CastInst>(V))
Reid Spencere4d87aa2006-12-23 06:05:41 +0000499 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner33a61132006-05-06 09:00:16 +0000500 return false;
501 return true;
502}
503
Chris Lattner4f98c562003-03-10 21:43:22 +0000504// SimplifyCommutative - This performs a few simplifications for commutative
505// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000506//
Chris Lattner4f98c562003-03-10 21:43:22 +0000507// 1. Order operands such that they are listed from right (least complex) to
508// left (most complex). This puts constants before unary operators before
509// binary operators.
510//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000511// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
512// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000513//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000514bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000515 bool Changed = false;
516 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
517 Changed = !I.swapOperands();
Misha Brukmanfd939082005-04-21 23:48:37 +0000518
Chris Lattner4f98c562003-03-10 21:43:22 +0000519 if (!I.isAssociative()) return Changed;
520 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000521 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
522 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
523 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner2a9c8472003-05-27 16:40:51 +0000524 Constant *Folded = ConstantExpr::get(I.getOpcode(),
525 cast<Constant>(I.getOperand(1)),
526 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000527 I.setOperand(0, Op->getOperand(0));
528 I.setOperand(1, Folded);
529 return true;
530 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
531 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
532 isOnlyUse(Op) && isOnlyUse(Op1)) {
533 Constant *C1 = cast<Constant>(Op->getOperand(1));
534 Constant *C2 = cast<Constant>(Op1->getOperand(1));
535
536 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner2a9c8472003-05-27 16:40:51 +0000537 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000538 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Chris Lattnerc8802d22003-03-11 00:12:48 +0000539 Op1->getOperand(0),
540 Op1->getName(), &I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000541 AddToWorkList(New);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000542 I.setOperand(0, New);
543 I.setOperand(1, Folded);
544 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000545 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000546 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000547 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000548}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000549
Reid Spencere4d87aa2006-12-23 06:05:41 +0000550/// SimplifyCompare - For a CmpInst this function just orders the operands
551/// so that theyare listed from right (least complex) to left (most complex).
552/// This puts constants before unary operators before binary operators.
553bool InstCombiner::SimplifyCompare(CmpInst &I) {
554 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
555 return false;
556 I.swapOperands();
557 // Compare instructions are not associative so there's nothing else we can do.
558 return true;
559}
560
Chris Lattner8d969642003-03-10 23:06:50 +0000561// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
562// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000563//
Chris Lattner8d969642003-03-10 23:06:50 +0000564static inline Value *dyn_castNegVal(Value *V) {
565 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000566 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000567
Chris Lattner0ce85802004-12-14 20:08:06 +0000568 // Constants can be considered to be negated values if they can be folded.
569 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
570 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000571
572 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
573 if (C->getType()->getElementType()->isInteger())
574 return ConstantExpr::getNeg(C);
575
Chris Lattner8d969642003-03-10 23:06:50 +0000576 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000577}
578
Chris Lattner8d969642003-03-10 23:06:50 +0000579static inline Value *dyn_castNotVal(Value *V) {
580 if (BinaryOperator::isNot(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000581 return BinaryOperator::getNotArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000582
583 // Constants can be considered to be not'ed values...
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000584 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Zhou Sheng4a1822a2007-04-02 13:45:30 +0000585 return ConstantInt::get(~C->getValue());
Chris Lattner8d969642003-03-10 23:06:50 +0000586 return 0;
587}
588
Chris Lattnerc8802d22003-03-11 00:12:48 +0000589// dyn_castFoldableMul - If this value is a multiply that can be folded into
590// other computations (because it has a constant operand), return the
Chris Lattner50af16a2004-11-13 19:50:12 +0000591// non-constant operand of the multiply, and set CST to point to the multiplier.
592// Otherwise, return null.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000593//
Chris Lattner50af16a2004-11-13 19:50:12 +0000594static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattner42a75512007-01-15 02:27:26 +0000595 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner50af16a2004-11-13 19:50:12 +0000596 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000597 if (I->getOpcode() == Instruction::Mul)
Chris Lattner50e60c72004-11-15 05:54:07 +0000598 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000599 return I->getOperand(0);
Chris Lattner50af16a2004-11-13 19:50:12 +0000600 if (I->getOpcode() == Instruction::Shl)
Chris Lattner50e60c72004-11-15 05:54:07 +0000601 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000602 // The multiplier is really 1 << CST.
Zhou Sheng97b52c22007-03-29 01:57:21 +0000603 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000604 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Zhou Sheng97b52c22007-03-29 01:57:21 +0000605 CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
Chris Lattner50af16a2004-11-13 19:50:12 +0000606 return I->getOperand(0);
607 }
608 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000609 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000610}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000611
Chris Lattner574da9b2005-01-13 20:14:25 +0000612/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
613/// expression, return it.
614static User *dyn_castGetElementPtr(Value *V) {
615 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
616 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
617 if (CE->getOpcode() == Instruction::GetElementPtr)
618 return cast<User>(V);
619 return false;
620}
621
Dan Gohmaneee962e2008-04-10 18:43:06 +0000622/// getOpcode - If this is an Instruction or a ConstantExpr, return the
623/// opcode value. Otherwise return UserOp1.
Dan Gohmanb99e2e22008-05-29 19:53:46 +0000624static unsigned getOpcode(const Value *V) {
625 if (const Instruction *I = dyn_cast<Instruction>(V))
Dan Gohmaneee962e2008-04-10 18:43:06 +0000626 return I->getOpcode();
Dan Gohmanb99e2e22008-05-29 19:53:46 +0000627 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Dan Gohmaneee962e2008-04-10 18:43:06 +0000628 return CE->getOpcode();
629 // Use UserOp1 to mean there's no opcode.
630 return Instruction::UserOp1;
631}
632
Reid Spencer7177c3a2007-03-25 05:33:51 +0000633/// AddOne - Add one to a ConstantInt
Chris Lattnera96879a2004-09-29 17:40:11 +0000634static ConstantInt *AddOne(ConstantInt *C) {
Reid Spencer2149a9d2007-03-25 19:55:33 +0000635 APInt Val(C->getValue());
636 return ConstantInt::get(++Val);
Chris Lattner955f3312004-09-28 21:48:02 +0000637}
Reid Spencer7177c3a2007-03-25 05:33:51 +0000638/// SubOne - Subtract one from a ConstantInt
Chris Lattnera96879a2004-09-29 17:40:11 +0000639static ConstantInt *SubOne(ConstantInt *C) {
Reid Spencer2149a9d2007-03-25 19:55:33 +0000640 APInt Val(C->getValue());
641 return ConstantInt::get(--Val);
Reid Spencer7177c3a2007-03-25 05:33:51 +0000642}
643/// Add - Add two ConstantInts together
644static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
645 return ConstantInt::get(C1->getValue() + C2->getValue());
646}
647/// And - Bitwise AND two ConstantInts together
648static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
649 return ConstantInt::get(C1->getValue() & C2->getValue());
650}
651/// Subtract - Subtract one ConstantInt from another
652static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
653 return ConstantInt::get(C1->getValue() - C2->getValue());
654}
655/// Multiply - Multiply two ConstantInts together
656static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
657 return ConstantInt::get(C1->getValue() * C2->getValue());
Chris Lattner955f3312004-09-28 21:48:02 +0000658}
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000659/// MultiplyOverflows - True if the multiply can not be expressed in an int
660/// this size.
661static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
662 uint32_t W = C1->getBitWidth();
663 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
664 if (sign) {
665 LHSExt.sext(W * 2);
666 RHSExt.sext(W * 2);
667 } else {
668 LHSExt.zext(W * 2);
669 RHSExt.zext(W * 2);
670 }
671
672 APInt MulExt = LHSExt * RHSExt;
673
674 if (sign) {
675 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
676 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
677 return MulExt.slt(Min) || MulExt.sgt(Max);
678 } else
679 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
680}
Chris Lattner955f3312004-09-28 21:48:02 +0000681
Reid Spencere7816b52007-03-08 01:52:58 +0000682
Chris Lattner255d8912006-02-11 09:31:47 +0000683/// ShrinkDemandedConstant - Check to see if the specified operand of the
684/// specified instruction is a constant integer. If so, check to see if there
685/// are any bits set in the constant that are not demanded. If so, shrink the
686/// constant and return true.
687static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000688 APInt Demanded) {
689 assert(I && "No instruction?");
690 assert(OpNo < I->getNumOperands() && "Operand index too large");
691
692 // If the operand is not a constant integer, nothing to do.
693 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
694 if (!OpC) return false;
695
696 // If there are no bits set that aren't demanded, nothing to do.
697 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
698 if ((~Demanded & OpC->getValue()) == 0)
699 return false;
700
701 // This instruction is producing bits that are not demanded. Shrink the RHS.
702 Demanded &= OpC->getValue();
703 I->setOperand(OpNo, ConstantInt::get(Demanded));
704 return true;
705}
706
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000707// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
708// set of known zero and one bits, compute the maximum and minimum values that
709// could have the specified known zero and known one bits, returning them in
710// min/max.
Dan Gohman1c8491e2009-04-25 17:12:48 +0000711static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
Reid Spencer0460fb32007-03-22 20:36:03 +0000712 const APInt& KnownOne,
713 APInt& Min, APInt& Max) {
Dan Gohman1c8491e2009-04-25 17:12:48 +0000714 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
715 KnownZero.getBitWidth() == Min.getBitWidth() &&
716 KnownZero.getBitWidth() == Max.getBitWidth() &&
717 "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000718 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000719
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000720 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
721 // bit if it is unknown.
722 Min = KnownOne;
723 Max = KnownOne|UnknownBits;
724
Dan Gohman1c8491e2009-04-25 17:12:48 +0000725 if (UnknownBits.isNegative()) { // Sign bit is unknown
726 Min.set(Min.getBitWidth()-1);
727 Max.clear(Max.getBitWidth()-1);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000728 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000729}
730
731// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
732// a set of known zero and one bits, compute the maximum and minimum values that
733// could have the specified known zero and known one bits, returning them in
734// min/max.
Dan Gohman1c8491e2009-04-25 17:12:48 +0000735static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
Chris Lattnera9ff5eb2007-08-05 08:47:58 +0000736 const APInt &KnownOne,
737 APInt &Min, APInt &Max) {
Dan Gohman1c8491e2009-04-25 17:12:48 +0000738 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
739 KnownZero.getBitWidth() == Min.getBitWidth() &&
740 KnownZero.getBitWidth() == Max.getBitWidth() &&
Reid Spencer0460fb32007-03-22 20:36:03 +0000741 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000742 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000743
744 // The minimum value is when the unknown bits are all zeros.
745 Min = KnownOne;
746 // The maximum value is when the unknown bits are all ones.
747 Max = KnownOne|UnknownBits;
748}
Chris Lattner255d8912006-02-11 09:31:47 +0000749
Chris Lattner886ab6c2009-01-31 08:15:18 +0000750/// SimplifyDemandedInstructionBits - Inst is an integer instruction that
751/// SimplifyDemandedBits knows about. See if the instruction has any
752/// properties that allow us to simplify its operands.
753bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
754 unsigned BitWidth = cast<IntegerType>(Inst.getType())->getBitWidth();
755 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
756 APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
757
758 Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask,
759 KnownZero, KnownOne, 0);
760 if (V == 0) return false;
761 if (V == &Inst) return true;
762 ReplaceInstUsesWith(Inst, V);
763 return true;
764}
765
766/// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
767/// specified instruction operand if possible, updating it in place. It returns
768/// true if it made any change and false otherwise.
769bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask,
770 APInt &KnownZero, APInt &KnownOne,
771 unsigned Depth) {
772 Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
773 KnownZero, KnownOne, Depth);
774 if (NewVal == 0) return false;
775 U.set(NewVal);
776 return true;
777}
778
779
780/// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
781/// value based on the demanded bits. When this function is called, it is known
Reid Spencer8cb68342007-03-12 17:25:59 +0000782/// that only the bits set in DemandedMask of the result of V are ever used
783/// downstream. Consequently, depending on the mask and V, it may be possible
784/// to replace V with a constant or one of its operands. In such cases, this
785/// function does the replacement and returns true. In all other cases, it
786/// returns false after analyzing the expression and setting KnownOne and known
Chris Lattner886ab6c2009-01-31 08:15:18 +0000787/// to be one in the expression. KnownZero contains all the bits that are known
Reid Spencer8cb68342007-03-12 17:25:59 +0000788/// to be zero in the expression. These are provided to potentially allow the
789/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
790/// the expression. KnownOne and KnownZero always follow the invariant that
791/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
792/// the bits in KnownOne and KnownZero may only be accurate for those bits set
793/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
794/// and KnownOne must all be the same.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000795///
796/// This returns null if it did not change anything and it permits no
797/// simplification. This returns V itself if it did some simplification of V's
798/// operands based on the information about what bits are demanded. This returns
799/// some other non-null value if it found out that V is equal to another value
800/// in the context where the specified bits are demanded, but not for all users.
801Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
802 APInt &KnownZero, APInt &KnownOne,
803 unsigned Depth) {
Reid Spencer8cb68342007-03-12 17:25:59 +0000804 assert(V != 0 && "Null pointer of Value???");
805 assert(Depth <= 6 && "Limit Search Depth");
806 uint32_t BitWidth = DemandedMask.getBitWidth();
Dan Gohman1c8491e2009-04-25 17:12:48 +0000807 const Type *VTy = V->getType();
808 assert((TD || !isa<PointerType>(VTy)) &&
809 "SimplifyDemandedBits needs to know bit widths!");
810 assert((!TD || TD->getTypeSizeInBits(VTy) == BitWidth) &&
811 (!isa<IntegerType>(VTy) ||
812 VTy->getPrimitiveSizeInBits() == BitWidth) &&
813 KnownZero.getBitWidth() == BitWidth &&
Reid Spencer8cb68342007-03-12 17:25:59 +0000814 KnownOne.getBitWidth() == BitWidth &&
815 "Value *V, DemandedMask, KnownZero and KnownOne \
816 must have same BitWidth");
817 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
818 // We know all of the bits for a constant!
819 KnownOne = CI->getValue() & DemandedMask;
820 KnownZero = ~KnownOne & DemandedMask;
Chris Lattner886ab6c2009-01-31 08:15:18 +0000821 return 0;
Reid Spencer8cb68342007-03-12 17:25:59 +0000822 }
Dan Gohman1c8491e2009-04-25 17:12:48 +0000823 if (isa<ConstantPointerNull>(V)) {
824 // We know all of the bits for a constant!
825 KnownOne.clear();
826 KnownZero = DemandedMask;
827 return 0;
828 }
829
Chris Lattner08d2cc72009-01-31 07:26:06 +0000830 KnownZero.clear();
Zhou Sheng96704452007-03-14 03:21:24 +0000831 KnownOne.clear();
Chris Lattner886ab6c2009-01-31 08:15:18 +0000832 if (DemandedMask == 0) { // Not demanding any bits from V.
833 if (isa<UndefValue>(V))
834 return 0;
835 return UndefValue::get(VTy);
Reid Spencer8cb68342007-03-12 17:25:59 +0000836 }
837
Chris Lattner4598c942009-01-31 08:24:16 +0000838 if (Depth == 6) // Limit search depth.
839 return 0;
840
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000841 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
842 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
843
Dan Gohman1c8491e2009-04-25 17:12:48 +0000844 Instruction *I = dyn_cast<Instruction>(V);
845 if (!I) {
846 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
847 return 0; // Only analyze instructions.
848 }
849
Chris Lattner4598c942009-01-31 08:24:16 +0000850 // If there are multiple uses of this value and we aren't at the root, then
851 // we can't do any simplifications of the operands, because DemandedMask
852 // only reflects the bits demanded by *one* of the users.
853 if (Depth != 0 && !I->hasOneUse()) {
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000854 // Despite the fact that we can't simplify this instruction in all User's
855 // context, we can at least compute the knownzero/knownone bits, and we can
856 // do simplifications that apply to *just* the one user if we know that
857 // this instruction has a simpler value in that context.
858 if (I->getOpcode() == Instruction::And) {
859 // If either the LHS or the RHS are Zero, the result is zero.
860 ComputeMaskedBits(I->getOperand(1), DemandedMask,
861 RHSKnownZero, RHSKnownOne, Depth+1);
862 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
863 LHSKnownZero, LHSKnownOne, Depth+1);
864
865 // If all of the demanded bits are known 1 on one side, return the other.
866 // These bits cannot contribute to the result of the 'and' in this
867 // context.
868 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
869 (DemandedMask & ~LHSKnownZero))
870 return I->getOperand(0);
871 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
872 (DemandedMask & ~RHSKnownZero))
873 return I->getOperand(1);
874
875 // If all of the demanded bits in the inputs are known zeros, return zero.
876 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
877 return Constant::getNullValue(VTy);
878
879 } else if (I->getOpcode() == Instruction::Or) {
880 // We can simplify (X|Y) -> X or Y in the user's context if we know that
881 // only bits from X or Y are demanded.
882
883 // If either the LHS or the RHS are One, the result is One.
884 ComputeMaskedBits(I->getOperand(1), DemandedMask,
885 RHSKnownZero, RHSKnownOne, Depth+1);
886 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
887 LHSKnownZero, LHSKnownOne, Depth+1);
888
889 // If all of the demanded bits are known zero on one side, return the
890 // other. These bits cannot contribute to the result of the 'or' in this
891 // context.
892 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
893 (DemandedMask & ~LHSKnownOne))
894 return I->getOperand(0);
895 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
896 (DemandedMask & ~RHSKnownOne))
897 return I->getOperand(1);
898
899 // If all of the potentially set bits on one side are known to be set on
900 // the other side, just use the 'other' side.
901 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
902 (DemandedMask & (~RHSKnownZero)))
903 return I->getOperand(0);
904 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
905 (DemandedMask & (~LHSKnownZero)))
906 return I->getOperand(1);
907 }
908
Chris Lattner4598c942009-01-31 08:24:16 +0000909 // Compute the KnownZero/KnownOne bits to simplify things downstream.
910 ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
911 return 0;
912 }
913
914 // If this is the root being simplified, allow it to have multiple uses,
915 // just set the DemandedMask to all bits so that we can try to simplify the
916 // operands. This allows visitTruncInst (for example) to simplify the
917 // operand of a trunc without duplicating all the logic below.
918 if (Depth == 0 && !V->hasOneUse())
919 DemandedMask = APInt::getAllOnesValue(BitWidth);
920
Reid Spencer8cb68342007-03-12 17:25:59 +0000921 switch (I->getOpcode()) {
Dan Gohman23e8b712008-04-28 17:02:21 +0000922 default:
Chris Lattner886ab6c2009-01-31 08:15:18 +0000923 ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Dan Gohman23e8b712008-04-28 17:02:21 +0000924 break;
Reid Spencer8cb68342007-03-12 17:25:59 +0000925 case Instruction::And:
926 // If either the LHS or the RHS are Zero, the result is zero.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000927 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
928 RHSKnownZero, RHSKnownOne, Depth+1) ||
929 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
Reid Spencer8cb68342007-03-12 17:25:59 +0000930 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000931 return I;
932 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
933 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000934
935 // If all of the demanded bits are known 1 on one side, return the other.
936 // These bits cannot contribute to the result of the 'and'.
937 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
938 (DemandedMask & ~LHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000939 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000940 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
941 (DemandedMask & ~RHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000942 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000943
944 // If all of the demanded bits in the inputs are known zeros, return zero.
945 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +0000946 return Constant::getNullValue(VTy);
Reid Spencer8cb68342007-03-12 17:25:59 +0000947
948 // If the RHS is a constant, see if we can simplify it.
949 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000950 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +0000951
952 // Output known-1 bits are only known if set in both the LHS & RHS.
953 RHSKnownOne &= LHSKnownOne;
954 // Output known-0 are known to be clear if zero in either the LHS | RHS.
955 RHSKnownZero |= LHSKnownZero;
956 break;
957 case Instruction::Or:
958 // If either the LHS or the RHS are One, the result is One.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000959 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
960 RHSKnownZero, RHSKnownOne, Depth+1) ||
961 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne,
Reid Spencer8cb68342007-03-12 17:25:59 +0000962 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000963 return I;
964 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
965 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000966
967 // If all of the demanded bits are known zero on one side, return the other.
968 // These bits cannot contribute to the result of the 'or'.
969 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
970 (DemandedMask & ~LHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000971 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000972 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
973 (DemandedMask & ~RHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000974 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000975
976 // If all of the potentially set bits on one side are known to be set on
977 // the other side, just use the 'other' side.
978 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
979 (DemandedMask & (~RHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000980 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000981 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
982 (DemandedMask & (~LHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000983 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000984
985 // If the RHS is a constant, see if we can simplify it.
986 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000987 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +0000988
989 // Output known-0 bits are only known if clear in both the LHS & RHS.
990 RHSKnownZero &= LHSKnownZero;
991 // Output known-1 are known to be set if set in either the LHS | RHS.
992 RHSKnownOne |= LHSKnownOne;
993 break;
994 case Instruction::Xor: {
Chris Lattner886ab6c2009-01-31 08:15:18 +0000995 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
996 RHSKnownZero, RHSKnownOne, Depth+1) ||
997 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +0000998 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000999 return I;
1000 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1001 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001002
1003 // If all of the demanded bits are known zero on one side, return the other.
1004 // These bits cannot contribute to the result of the 'xor'.
1005 if ((DemandedMask & RHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +00001006 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001007 if ((DemandedMask & LHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +00001008 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001009
1010 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1011 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1012 (RHSKnownOne & LHSKnownOne);
1013 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1014 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1015 (RHSKnownOne & LHSKnownZero);
1016
1017 // If all of the demanded bits are known to be zero on one side or the
1018 // other, turn this into an *inclusive* or.
1019 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1020 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1021 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001022 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001023 I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001024 return InsertNewInstBefore(Or, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001025 }
1026
1027 // If all of the demanded bits on one side are known, and all of the set
1028 // bits on that side are also known to be set on the other side, turn this
1029 // into an AND, as we know the bits will be cleared.
1030 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1031 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1032 // all known
1033 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1034 Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
1035 Instruction *And =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001036 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
Chris Lattner886ab6c2009-01-31 08:15:18 +00001037 return InsertNewInstBefore(And, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001038 }
1039 }
1040
1041 // If the RHS is a constant, see if we can simplify it.
1042 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1043 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001044 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001045
1046 RHSKnownZero = KnownZeroOut;
1047 RHSKnownOne = KnownOneOut;
1048 break;
1049 }
1050 case Instruction::Select:
Chris Lattner886ab6c2009-01-31 08:15:18 +00001051 if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1052 RHSKnownZero, RHSKnownOne, Depth+1) ||
1053 SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001054 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001055 return I;
1056 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1057 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001058
1059 // If the operands are constants, see if we can simplify them.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001060 if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
1061 ShrinkDemandedConstant(I, 2, DemandedMask))
1062 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001063
1064 // Only known if known in both the LHS and RHS.
1065 RHSKnownOne &= LHSKnownOne;
1066 RHSKnownZero &= LHSKnownZero;
1067 break;
1068 case Instruction::Trunc: {
Chris Lattner886ab6c2009-01-31 08:15:18 +00001069 unsigned truncBf = I->getOperand(0)->getType()->getPrimitiveSizeInBits();
Zhou Sheng01542f32007-03-29 02:26:30 +00001070 DemandedMask.zext(truncBf);
1071 RHSKnownZero.zext(truncBf);
1072 RHSKnownOne.zext(truncBf);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001073 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +00001074 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001075 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001076 DemandedMask.trunc(BitWidth);
1077 RHSKnownZero.trunc(BitWidth);
1078 RHSKnownOne.trunc(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001079 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001080 break;
1081 }
1082 case Instruction::BitCast:
1083 if (!I->getOperand(0)->getType()->isInteger())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001084 return false; // vector->int or fp->int?
1085 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001086 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001087 return I;
1088 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001089 break;
1090 case Instruction::ZExt: {
1091 // Compute the bits in the result that are not present in the input.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001092 unsigned SrcBitWidth =I->getOperand(0)->getType()->getPrimitiveSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001093
Zhou Shengd48653a2007-03-29 04:45:55 +00001094 DemandedMask.trunc(SrcBitWidth);
1095 RHSKnownZero.trunc(SrcBitWidth);
1096 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001097 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +00001098 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001099 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001100 DemandedMask.zext(BitWidth);
1101 RHSKnownZero.zext(BitWidth);
1102 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001103 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001104 // The top bits are known to be zero.
Zhou Sheng01542f32007-03-29 02:26:30 +00001105 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001106 break;
1107 }
1108 case Instruction::SExt: {
1109 // Compute the bits in the result that are not present in the input.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001110 unsigned SrcBitWidth =I->getOperand(0)->getType()->getPrimitiveSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001111
Reid Spencer8cb68342007-03-12 17:25:59 +00001112 APInt InputDemandedBits = DemandedMask &
Zhou Sheng01542f32007-03-29 02:26:30 +00001113 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001114
Zhou Sheng01542f32007-03-29 02:26:30 +00001115 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
Reid Spencer8cb68342007-03-12 17:25:59 +00001116 // If any of the sign extended bits are demanded, we know that the sign
1117 // bit is demanded.
1118 if ((NewBits & DemandedMask) != 0)
Zhou Sheng4a1822a2007-04-02 13:45:30 +00001119 InputDemandedBits.set(SrcBitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001120
Zhou Shengd48653a2007-03-29 04:45:55 +00001121 InputDemandedBits.trunc(SrcBitWidth);
1122 RHSKnownZero.trunc(SrcBitWidth);
1123 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001124 if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
Zhou Sheng01542f32007-03-29 02:26:30 +00001125 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001126 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001127 InputDemandedBits.zext(BitWidth);
1128 RHSKnownZero.zext(BitWidth);
1129 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001130 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001131
1132 // If the sign bit of the input is known set or clear, then we know the
1133 // top bits of the result.
1134
1135 // If the input sign bit is known zero, or if the NewBits are not demanded
1136 // convert this into a zero extension.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001137 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001138 // Convert to ZExt cast
Chris Lattner886ab6c2009-01-31 08:15:18 +00001139 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1140 return InsertNewInstBefore(NewCast, *I);
Zhou Sheng01542f32007-03-29 02:26:30 +00001141 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
Reid Spencer8cb68342007-03-12 17:25:59 +00001142 RHSKnownOne |= NewBits;
Reid Spencer8cb68342007-03-12 17:25:59 +00001143 }
1144 break;
1145 }
1146 case Instruction::Add: {
1147 // Figure out what the input bits are. If the top bits of the and result
1148 // are not demanded, then the add doesn't demand them from its input
1149 // either.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001150 unsigned NLZ = DemandedMask.countLeadingZeros();
Reid Spencer8cb68342007-03-12 17:25:59 +00001151
1152 // If there is a constant on the RHS, there are a variety of xformations
1153 // we can do.
1154 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1155 // If null, this should be simplified elsewhere. Some of the xforms here
1156 // won't work if the RHS is zero.
1157 if (RHS->isZero())
1158 break;
1159
1160 // If the top bit of the output is demanded, demand everything from the
1161 // input. Otherwise, we demand all the input bits except NLZ top bits.
Zhou Sheng01542f32007-03-29 02:26:30 +00001162 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001163
1164 // Find information about known zero/one bits in the input.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001165 if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits,
Reid Spencer8cb68342007-03-12 17:25:59 +00001166 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001167 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001168
1169 // If the RHS of the add has bits set that can't affect the input, reduce
1170 // the constant.
1171 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001172 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001173
1174 // Avoid excess work.
1175 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1176 break;
1177
1178 // Turn it into OR if input bits are zero.
1179 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1180 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001181 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001182 I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001183 return InsertNewInstBefore(Or, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001184 }
1185
1186 // We can say something about the output known-zero and known-one bits,
1187 // depending on potential carries from the input constant and the
1188 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1189 // bits set and the RHS constant is 0x01001, then we know we have a known
1190 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1191
1192 // To compute this, we first compute the potential carry bits. These are
1193 // the bits which may be modified. I'm not aware of a better way to do
1194 // this scan.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001195 const APInt &RHSVal = RHS->getValue();
Zhou Shengb9cb95f2007-03-31 02:38:39 +00001196 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
Reid Spencer8cb68342007-03-12 17:25:59 +00001197
1198 // Now that we know which bits have carries, compute the known-1/0 sets.
1199
1200 // Bits are known one if they are known zero in one operand and one in the
1201 // other, and there is no input carry.
1202 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1203 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1204
1205 // Bits are known zero if they are known zero in both operands and there
1206 // is no input carry.
1207 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1208 } else {
1209 // If the high-bits of this ADD are not demanded, then it does not demand
1210 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001211 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001212 // Right fill the mask of bits for this ADD to demand the most
1213 // significant bit and all those below it.
Zhou Sheng01542f32007-03-29 02:26:30 +00001214 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001215 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1216 LHSKnownZero, LHSKnownOne, Depth+1) ||
1217 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001218 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001219 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001220 }
1221 }
1222 break;
1223 }
1224 case Instruction::Sub:
1225 // If the high-bits of this SUB are not demanded, then it does not demand
1226 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001227 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001228 // Right fill the mask of bits for this SUB to demand the most
1229 // significant bit and all those below it.
Zhou Sheng4351c642007-04-02 08:20:41 +00001230 uint32_t NLZ = DemandedMask.countLeadingZeros();
Zhou Sheng01542f32007-03-29 02:26:30 +00001231 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001232 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1233 LHSKnownZero, LHSKnownOne, Depth+1) ||
1234 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001235 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001236 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001237 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001238 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1239 // the known zeros and ones.
1240 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001241 break;
1242 case Instruction::Shl:
1243 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001244 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001245 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001246 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001247 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001248 return I;
1249 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001250 RHSKnownZero <<= ShiftAmt;
1251 RHSKnownOne <<= ShiftAmt;
1252 // low bits known zero.
Zhou Shengadc14952007-03-14 09:07:33 +00001253 if (ShiftAmt)
Zhou Shenge9e03f62007-03-28 15:02:20 +00001254 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
Reid Spencer8cb68342007-03-12 17:25:59 +00001255 }
1256 break;
1257 case Instruction::LShr:
1258 // For a logical shift right
1259 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001260 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001261
Reid Spencer8cb68342007-03-12 17:25:59 +00001262 // Unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001263 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001264 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001265 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001266 return I;
1267 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001268 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1269 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
Zhou Shengadc14952007-03-14 09:07:33 +00001270 if (ShiftAmt) {
1271 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001272 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Zhou Shengadc14952007-03-14 09:07:33 +00001273 RHSKnownZero |= HighBits; // high bits known zero.
1274 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001275 }
1276 break;
1277 case Instruction::AShr:
1278 // If this is an arithmetic shift right and only the low-bit is set, we can
1279 // always convert this into a logical shr, even if the shift amount is
1280 // variable. The low bit of the shift cannot be an input sign bit unless
1281 // the shift amount is >= the size of the datatype, which is undefined.
1282 if (DemandedMask == 1) {
1283 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001284 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001285 I->getOperand(0), I->getOperand(1), I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001286 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001287 }
Chris Lattner4241e4d2007-07-15 20:54:51 +00001288
1289 // If the sign bit is the only bit demanded by this ashr, then there is no
1290 // need to do it, the shift doesn't change the high bit.
1291 if (DemandedMask.isSignBit())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001292 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001293
1294 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00001295 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001296
Reid Spencer8cb68342007-03-12 17:25:59 +00001297 // Signed shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001298 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Lauro Ramos Venanciod0499af2007-06-06 17:08:48 +00001299 // If any of the "high bits" are demanded, we should set the sign bit as
1300 // demanded.
1301 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1302 DemandedMaskIn.set(BitWidth-1);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001303 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001304 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001305 return I;
1306 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001307 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001308 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Reid Spencer8cb68342007-03-12 17:25:59 +00001309 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1310 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1311
1312 // Handle the sign bits.
1313 APInt SignBit(APInt::getSignBit(BitWidth));
1314 // Adjust to where it is now in the mask.
1315 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1316
1317 // If the input sign bit is known to be zero, or if none of the top bits
1318 // are demanded, turn this into an unsigned shift right.
Zhou Shengcc419402008-06-06 08:32:05 +00001319 if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] ||
Reid Spencer8cb68342007-03-12 17:25:59 +00001320 (HighBits & ~DemandedMask) == HighBits) {
1321 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001322 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001323 I->getOperand(0), SA, I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001324 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001325 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1326 RHSKnownOne |= HighBits;
1327 }
1328 }
1329 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001330 case Instruction::SRem:
1331 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Nick Lewycky8e394322008-11-02 02:41:50 +00001332 APInt RA = Rem->getValue().abs();
1333 if (RA.isPowerOf2()) {
Nick Lewycky3ac9e102008-07-12 05:04:38 +00001334 if (DemandedMask.ule(RA)) // srem won't affect demanded bits
Chris Lattner886ab6c2009-01-31 08:15:18 +00001335 return I->getOperand(0);
Nick Lewycky3ac9e102008-07-12 05:04:38 +00001336
Nick Lewycky8e394322008-11-02 02:41:50 +00001337 APInt LowBits = RA - 1;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001338 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001339 if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001340 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001341 return I;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001342
1343 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1344 LHSKnownZero |= ~LowBits;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001345
1346 KnownZero |= LHSKnownZero & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001347
Chris Lattner886ab6c2009-01-31 08:15:18 +00001348 assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001349 }
1350 }
1351 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001352 case Instruction::URem: {
Dan Gohman23e8b712008-04-28 17:02:21 +00001353 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1354 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001355 if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1356 KnownZero2, KnownOne2, Depth+1) ||
1357 SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
Dan Gohmane85b7582008-05-01 19:13:24 +00001358 KnownZero2, KnownOne2, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001359 return I;
Dan Gohmane85b7582008-05-01 19:13:24 +00001360
Chris Lattner455e9ab2009-01-21 18:09:24 +00001361 unsigned Leaders = KnownZero2.countLeadingOnes();
Dan Gohman23e8b712008-04-28 17:02:21 +00001362 Leaders = std::max(Leaders,
1363 KnownZero2.countLeadingOnes());
1364 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001365 break;
Reid Spencer8cb68342007-03-12 17:25:59 +00001366 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00001367 case Instruction::Call:
1368 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1369 switch (II->getIntrinsicID()) {
1370 default: break;
1371 case Intrinsic::bswap: {
1372 // If the only bits demanded come from one byte of the bswap result,
1373 // just shift the input byte into position to eliminate the bswap.
1374 unsigned NLZ = DemandedMask.countLeadingZeros();
1375 unsigned NTZ = DemandedMask.countTrailingZeros();
1376
1377 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
1378 // we need all the bits down to bit 8. Likewise, round NLZ. If we
1379 // have 14 leading zeros, round to 8.
1380 NLZ &= ~7;
1381 NTZ &= ~7;
1382 // If we need exactly one byte, we can do this transformation.
1383 if (BitWidth-NLZ-NTZ == 8) {
1384 unsigned ResultBit = NTZ;
1385 unsigned InputBit = BitWidth-NTZ-8;
1386
1387 // Replace this with either a left or right shift to get the byte into
1388 // the right place.
1389 Instruction *NewVal;
1390 if (InputBit > ResultBit)
1391 NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
1392 ConstantInt::get(I->getType(), InputBit-ResultBit));
1393 else
1394 NewVal = BinaryOperator::CreateShl(I->getOperand(1),
1395 ConstantInt::get(I->getType(), ResultBit-InputBit));
1396 NewVal->takeName(I);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001397 return InsertNewInstBefore(NewVal, *I);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001398 }
1399
1400 // TODO: Could compute known zero/one bits based on the input.
1401 break;
1402 }
1403 }
1404 }
Chris Lattner6c3bfba2008-06-18 18:11:55 +00001405 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001406 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001407 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001408
1409 // If the client is only demanding bits that we know, return the known
1410 // constant.
Dan Gohman1c8491e2009-04-25 17:12:48 +00001411 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1412 Constant *C = ConstantInt::get(RHSKnownOne);
1413 if (isa<PointerType>(V->getType()))
1414 C = ConstantExpr::getIntToPtr(C, V->getType());
1415 return C;
1416 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001417 return false;
1418}
1419
Chris Lattner867b99f2006-10-05 06:55:50 +00001420
Mon P Wangaeb06d22008-11-10 04:46:22 +00001421/// SimplifyDemandedVectorElts - The specified value produces a vector with
Evan Cheng388df622009-02-03 10:05:09 +00001422/// any number of elements. DemandedElts contains the set of elements that are
Chris Lattner867b99f2006-10-05 06:55:50 +00001423/// actually used by the caller. This method analyzes which elements of the
1424/// operand are undef and returns that information in UndefElts.
1425///
1426/// If the information about demanded elements can be used to simplify the
1427/// operation, the operation is simplified, then the resultant value is
1428/// returned. This returns null if no change was made.
Evan Cheng388df622009-02-03 10:05:09 +00001429Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1430 APInt& UndefElts,
Chris Lattner867b99f2006-10-05 06:55:50 +00001431 unsigned Depth) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001432 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001433 APInt EltMask(APInt::getAllOnesValue(VWidth));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001434 assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
Chris Lattner867b99f2006-10-05 06:55:50 +00001435
1436 if (isa<UndefValue>(V)) {
1437 // If the entire vector is undefined, just return this info.
1438 UndefElts = EltMask;
1439 return 0;
1440 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1441 UndefElts = EltMask;
1442 return UndefValue::get(V->getType());
1443 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001444
Chris Lattner867b99f2006-10-05 06:55:50 +00001445 UndefElts = 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001446 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1447 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner867b99f2006-10-05 06:55:50 +00001448 Constant *Undef = UndefValue::get(EltTy);
1449
1450 std::vector<Constant*> Elts;
1451 for (unsigned i = 0; i != VWidth; ++i)
Evan Cheng388df622009-02-03 10:05:09 +00001452 if (!DemandedElts[i]) { // If not demanded, set to undef.
Chris Lattner867b99f2006-10-05 06:55:50 +00001453 Elts.push_back(Undef);
Evan Cheng388df622009-02-03 10:05:09 +00001454 UndefElts.set(i);
Chris Lattner867b99f2006-10-05 06:55:50 +00001455 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1456 Elts.push_back(Undef);
Evan Cheng388df622009-02-03 10:05:09 +00001457 UndefElts.set(i);
Chris Lattner867b99f2006-10-05 06:55:50 +00001458 } else { // Otherwise, defined.
1459 Elts.push_back(CP->getOperand(i));
1460 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001461
Chris Lattner867b99f2006-10-05 06:55:50 +00001462 // If we changed the constant, return it.
Reid Spencer9d6565a2007-02-15 02:26:10 +00001463 Constant *NewCP = ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001464 return NewCP != CP ? NewCP : 0;
1465 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001466 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner867b99f2006-10-05 06:55:50 +00001467 // set to undef.
Mon P Wange0b436a2008-11-06 22:52:21 +00001468
1469 // Check if this is identity. If so, return 0 since we are not simplifying
1470 // anything.
1471 if (DemandedElts == ((1ULL << VWidth) -1))
1472 return 0;
1473
Reid Spencer9d6565a2007-02-15 02:26:10 +00001474 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner867b99f2006-10-05 06:55:50 +00001475 Constant *Zero = Constant::getNullValue(EltTy);
1476 Constant *Undef = UndefValue::get(EltTy);
1477 std::vector<Constant*> Elts;
Evan Cheng388df622009-02-03 10:05:09 +00001478 for (unsigned i = 0; i != VWidth; ++i) {
1479 Constant *Elt = DemandedElts[i] ? Zero : Undef;
1480 Elts.push_back(Elt);
1481 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001482 UndefElts = DemandedElts ^ EltMask;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001483 return ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001484 }
1485
Dan Gohman488fbfc2008-09-09 18:11:14 +00001486 // Limit search depth.
1487 if (Depth == 10)
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001488 return 0;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001489
1490 // If multiple users are using the root value, procede with
1491 // simplification conservatively assuming that all elements
1492 // are needed.
1493 if (!V->hasOneUse()) {
1494 // Quit if we find multiple users of a non-root value though.
1495 // They'll be handled when it's their turn to be visited by
1496 // the main instcombine process.
1497 if (Depth != 0)
Chris Lattner867b99f2006-10-05 06:55:50 +00001498 // TODO: Just compute the UndefElts information recursively.
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001499 return 0;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001500
1501 // Conservatively assume that all elements are needed.
1502 DemandedElts = EltMask;
Chris Lattner867b99f2006-10-05 06:55:50 +00001503 }
1504
1505 Instruction *I = dyn_cast<Instruction>(V);
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001506 if (!I) return 0; // Only analyze instructions.
Chris Lattner867b99f2006-10-05 06:55:50 +00001507
1508 bool MadeChange = false;
Evan Cheng388df622009-02-03 10:05:09 +00001509 APInt UndefElts2(VWidth, 0);
Chris Lattner867b99f2006-10-05 06:55:50 +00001510 Value *TmpV;
1511 switch (I->getOpcode()) {
1512 default: break;
1513
1514 case Instruction::InsertElement: {
1515 // If this is a variable index, we don't know which element it overwrites.
1516 // demand exactly the same input as we produce.
Reid Spencerb83eb642006-10-20 07:07:24 +00001517 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner867b99f2006-10-05 06:55:50 +00001518 if (Idx == 0) {
1519 // Note that we can't propagate undef elt info, because we don't know
1520 // which elt is getting updated.
1521 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1522 UndefElts2, Depth+1);
1523 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1524 break;
1525 }
1526
1527 // If this is inserting an element that isn't demanded, remove this
1528 // insertelement.
Reid Spencerb83eb642006-10-20 07:07:24 +00001529 unsigned IdxNo = Idx->getZExtValue();
Evan Cheng388df622009-02-03 10:05:09 +00001530 if (IdxNo >= VWidth || !DemandedElts[IdxNo])
Chris Lattner867b99f2006-10-05 06:55:50 +00001531 return AddSoonDeadInstToWorklist(*I, 0);
1532
1533 // Otherwise, the element inserted overwrites whatever was there, so the
1534 // input demanded set is simpler than the output set.
Evan Cheng388df622009-02-03 10:05:09 +00001535 APInt DemandedElts2 = DemandedElts;
1536 DemandedElts2.clear(IdxNo);
1537 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
Chris Lattner867b99f2006-10-05 06:55:50 +00001538 UndefElts, Depth+1);
1539 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1540
1541 // The inserted element is defined.
Evan Cheng388df622009-02-03 10:05:09 +00001542 UndefElts.clear(IdxNo);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001543 break;
1544 }
1545 case Instruction::ShuffleVector: {
1546 ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001547 uint64_t LHSVWidth =
1548 cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001549 APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001550 for (unsigned i = 0; i < VWidth; i++) {
Evan Cheng388df622009-02-03 10:05:09 +00001551 if (DemandedElts[i]) {
Dan Gohman488fbfc2008-09-09 18:11:14 +00001552 unsigned MaskVal = Shuffle->getMaskValue(i);
1553 if (MaskVal != -1u) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00001554 assert(MaskVal < LHSVWidth * 2 &&
Dan Gohman488fbfc2008-09-09 18:11:14 +00001555 "shufflevector mask index out of range!");
Mon P Wangaeb06d22008-11-10 04:46:22 +00001556 if (MaskVal < LHSVWidth)
Evan Cheng388df622009-02-03 10:05:09 +00001557 LeftDemanded.set(MaskVal);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001558 else
Evan Cheng388df622009-02-03 10:05:09 +00001559 RightDemanded.set(MaskVal - LHSVWidth);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001560 }
1561 }
1562 }
1563
Nate Begeman7b254672009-02-11 22:36:25 +00001564 APInt UndefElts4(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001565 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
Nate Begeman7b254672009-02-11 22:36:25 +00001566 UndefElts4, Depth+1);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001567 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1568
Nate Begeman7b254672009-02-11 22:36:25 +00001569 APInt UndefElts3(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001570 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1571 UndefElts3, Depth+1);
1572 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1573
1574 bool NewUndefElts = false;
1575 for (unsigned i = 0; i < VWidth; i++) {
1576 unsigned MaskVal = Shuffle->getMaskValue(i);
Dan Gohmancb893092008-09-10 01:09:32 +00001577 if (MaskVal == -1u) {
Evan Cheng388df622009-02-03 10:05:09 +00001578 UndefElts.set(i);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001579 } else if (MaskVal < LHSVWidth) {
Nate Begeman7b254672009-02-11 22:36:25 +00001580 if (UndefElts4[MaskVal]) {
Evan Cheng388df622009-02-03 10:05:09 +00001581 NewUndefElts = true;
1582 UndefElts.set(i);
1583 }
Dan Gohman488fbfc2008-09-09 18:11:14 +00001584 } else {
Evan Cheng388df622009-02-03 10:05:09 +00001585 if (UndefElts3[MaskVal - LHSVWidth]) {
1586 NewUndefElts = true;
1587 UndefElts.set(i);
1588 }
Dan Gohman488fbfc2008-09-09 18:11:14 +00001589 }
1590 }
1591
1592 if (NewUndefElts) {
1593 // Add additional discovered undefs.
1594 std::vector<Constant*> Elts;
1595 for (unsigned i = 0; i < VWidth; ++i) {
Evan Cheng388df622009-02-03 10:05:09 +00001596 if (UndefElts[i])
Dan Gohman488fbfc2008-09-09 18:11:14 +00001597 Elts.push_back(UndefValue::get(Type::Int32Ty));
1598 else
1599 Elts.push_back(ConstantInt::get(Type::Int32Ty,
1600 Shuffle->getMaskValue(i)));
1601 }
1602 I->setOperand(2, ConstantVector::get(Elts));
1603 MadeChange = true;
1604 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001605 break;
1606 }
Chris Lattner69878332007-04-14 22:29:23 +00001607 case Instruction::BitCast: {
Dan Gohman07a96762007-07-16 14:29:03 +00001608 // Vector->vector casts only.
Chris Lattner69878332007-04-14 22:29:23 +00001609 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1610 if (!VTy) break;
1611 unsigned InVWidth = VTy->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001612 APInt InputDemandedElts(InVWidth, 0);
Chris Lattner69878332007-04-14 22:29:23 +00001613 unsigned Ratio;
1614
1615 if (VWidth == InVWidth) {
Dan Gohman07a96762007-07-16 14:29:03 +00001616 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
Chris Lattner69878332007-04-14 22:29:23 +00001617 // elements as are demanded of us.
1618 Ratio = 1;
1619 InputDemandedElts = DemandedElts;
1620 } else if (VWidth > InVWidth) {
1621 // Untested so far.
1622 break;
1623
1624 // If there are more elements in the result than there are in the source,
1625 // then an input element is live if any of the corresponding output
1626 // elements are live.
1627 Ratio = VWidth/InVWidth;
1628 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
Evan Cheng388df622009-02-03 10:05:09 +00001629 if (DemandedElts[OutIdx])
1630 InputDemandedElts.set(OutIdx/Ratio);
Chris Lattner69878332007-04-14 22:29:23 +00001631 }
1632 } else {
1633 // Untested so far.
1634 break;
1635
1636 // If there are more elements in the source than there are in the result,
1637 // then an input element is live if the corresponding output element is
1638 // live.
1639 Ratio = InVWidth/VWidth;
1640 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001641 if (DemandedElts[InIdx/Ratio])
1642 InputDemandedElts.set(InIdx);
Chris Lattner69878332007-04-14 22:29:23 +00001643 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001644
Chris Lattner69878332007-04-14 22:29:23 +00001645 // div/rem demand all inputs, because they don't want divide by zero.
1646 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1647 UndefElts2, Depth+1);
1648 if (TmpV) {
1649 I->setOperand(0, TmpV);
1650 MadeChange = true;
1651 }
1652
1653 UndefElts = UndefElts2;
1654 if (VWidth > InVWidth) {
1655 assert(0 && "Unimp");
1656 // If there are more elements in the result than there are in the source,
1657 // then an output element is undef if the corresponding input element is
1658 // undef.
1659 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001660 if (UndefElts2[OutIdx/Ratio])
1661 UndefElts.set(OutIdx);
Chris Lattner69878332007-04-14 22:29:23 +00001662 } else if (VWidth < InVWidth) {
1663 assert(0 && "Unimp");
1664 // If there are more elements in the source than there are in the result,
1665 // then a result element is undef if all of the corresponding input
1666 // elements are undef.
1667 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1668 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001669 if (!UndefElts2[InIdx]) // Not undef?
1670 UndefElts.clear(InIdx/Ratio); // Clear undef bit.
Chris Lattner69878332007-04-14 22:29:23 +00001671 }
1672 break;
1673 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001674 case Instruction::And:
1675 case Instruction::Or:
1676 case Instruction::Xor:
1677 case Instruction::Add:
1678 case Instruction::Sub:
1679 case Instruction::Mul:
1680 // div/rem demand all inputs, because they don't want divide by zero.
1681 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1682 UndefElts, Depth+1);
1683 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1684 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1685 UndefElts2, Depth+1);
1686 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1687
1688 // Output elements are undefined if both are undefined. Consider things
1689 // like undef&0. The result is known zero, not undef.
1690 UndefElts &= UndefElts2;
1691 break;
1692
1693 case Instruction::Call: {
1694 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1695 if (!II) break;
1696 switch (II->getIntrinsicID()) {
1697 default: break;
1698
1699 // Binary vector operations that work column-wise. A dest element is a
1700 // function of the corresponding input elements from the two inputs.
1701 case Intrinsic::x86_sse_sub_ss:
1702 case Intrinsic::x86_sse_mul_ss:
1703 case Intrinsic::x86_sse_min_ss:
1704 case Intrinsic::x86_sse_max_ss:
1705 case Intrinsic::x86_sse2_sub_sd:
1706 case Intrinsic::x86_sse2_mul_sd:
1707 case Intrinsic::x86_sse2_min_sd:
1708 case Intrinsic::x86_sse2_max_sd:
1709 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1710 UndefElts, Depth+1);
1711 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1712 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1713 UndefElts2, Depth+1);
1714 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1715
1716 // If only the low elt is demanded and this is a scalarizable intrinsic,
1717 // scalarize it now.
1718 if (DemandedElts == 1) {
1719 switch (II->getIntrinsicID()) {
1720 default: break;
1721 case Intrinsic::x86_sse_sub_ss:
1722 case Intrinsic::x86_sse_mul_ss:
1723 case Intrinsic::x86_sse2_sub_sd:
1724 case Intrinsic::x86_sse2_mul_sd:
1725 // TODO: Lower MIN/MAX/ABS/etc
1726 Value *LHS = II->getOperand(1);
1727 Value *RHS = II->getOperand(2);
1728 // Extract the element as scalars.
1729 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1730 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1731
1732 switch (II->getIntrinsicID()) {
1733 default: assert(0 && "Case stmts out of sync!");
1734 case Intrinsic::x86_sse_sub_ss:
1735 case Intrinsic::x86_sse2_sub_sd:
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001736 TmpV = InsertNewInstBefore(BinaryOperator::CreateSub(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001737 II->getName()), *II);
1738 break;
1739 case Intrinsic::x86_sse_mul_ss:
1740 case Intrinsic::x86_sse2_mul_sd:
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001741 TmpV = InsertNewInstBefore(BinaryOperator::CreateMul(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001742 II->getName()), *II);
1743 break;
1744 }
1745
1746 Instruction *New =
Gabor Greif051a9502008-04-06 20:25:17 +00001747 InsertElementInst::Create(UndefValue::get(II->getType()), TmpV, 0U,
1748 II->getName());
Chris Lattner867b99f2006-10-05 06:55:50 +00001749 InsertNewInstBefore(New, *II);
1750 AddSoonDeadInstToWorklist(*II, 0);
1751 return New;
1752 }
1753 }
1754
1755 // Output elements are undefined if both are undefined. Consider things
1756 // like undef&0. The result is known zero, not undef.
1757 UndefElts &= UndefElts2;
1758 break;
1759 }
1760 break;
1761 }
1762 }
1763 return MadeChange ? I : 0;
1764}
1765
Dan Gohman45b4e482008-05-19 22:14:15 +00001766
Chris Lattner564a7272003-08-13 19:01:45 +00001767/// AssociativeOpt - Perform an optimization on an associative operator. This
1768/// function is designed to check a chain of associative operators for a
1769/// potential to apply a certain optimization. Since the optimization may be
1770/// applicable if the expression was reassociated, this checks the chain, then
1771/// reassociates the expression as necessary to expose the optimization
1772/// opportunity. This makes use of a special Functor, which must define
1773/// 'shouldApply' and 'apply' methods.
1774///
1775template<typename Functor>
Dan Gohman76d402b2008-05-20 01:14:05 +00001776static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
Chris Lattner564a7272003-08-13 19:01:45 +00001777 unsigned Opcode = Root.getOpcode();
1778 Value *LHS = Root.getOperand(0);
1779
1780 // Quick check, see if the immediate LHS matches...
1781 if (F.shouldApply(LHS))
1782 return F.apply(Root);
1783
1784 // Otherwise, if the LHS is not of the same opcode as the root, return.
1785 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +00001786 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +00001787 // Should we apply this transform to the RHS?
1788 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1789
1790 // If not to the RHS, check to see if we should apply to the LHS...
1791 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1792 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1793 ShouldApply = true;
1794 }
1795
1796 // If the functor wants to apply the optimization to the RHS of LHSI,
1797 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1798 if (ShouldApply) {
Chris Lattner564a7272003-08-13 19:01:45 +00001799 // Now all of the instructions are in the current basic block, go ahead
1800 // and perform the reassociation.
1801 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1802
1803 // First move the selected RHS to the LHS of the root...
1804 Root.setOperand(0, LHSI->getOperand(1));
1805
1806 // Make what used to be the LHS of the root be the user of the root...
1807 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +00001808 if (&Root == TmpLHSI) {
Chris Lattner15a76c02004-04-05 02:10:19 +00001809 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1810 return 0;
1811 }
Chris Lattner65725312004-04-16 18:08:07 +00001812 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +00001813 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +00001814 BasicBlock::iterator ARI = &Root; ++ARI;
Dan Gohmand02d9172008-06-19 17:47:47 +00001815 TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root
Chris Lattner65725312004-04-16 18:08:07 +00001816 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +00001817
1818 // Now propagate the ExtraOperand down the chain of instructions until we
1819 // get to LHSI.
1820 while (TmpLHSI != LHSI) {
1821 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +00001822 // Move the instruction to immediately before the chain we are
1823 // constructing to avoid breaking dominance properties.
Dan Gohmand02d9172008-06-19 17:47:47 +00001824 NextLHSI->moveBefore(ARI);
Chris Lattner65725312004-04-16 18:08:07 +00001825 ARI = NextLHSI;
1826
Chris Lattner564a7272003-08-13 19:01:45 +00001827 Value *NextOp = NextLHSI->getOperand(1);
1828 NextLHSI->setOperand(1, ExtraOperand);
1829 TmpLHSI = NextLHSI;
1830 ExtraOperand = NextOp;
1831 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001832
Chris Lattner564a7272003-08-13 19:01:45 +00001833 // Now that the instructions are reassociated, have the functor perform
1834 // the transformation...
1835 return F.apply(Root);
1836 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001837
Chris Lattner564a7272003-08-13 19:01:45 +00001838 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1839 }
1840 return 0;
1841}
1842
Dan Gohman844731a2008-05-13 00:00:25 +00001843namespace {
Chris Lattner564a7272003-08-13 19:01:45 +00001844
Nick Lewycky02d639f2008-05-23 04:34:58 +00001845// AddRHS - Implements: X + X --> X << 1
Chris Lattner564a7272003-08-13 19:01:45 +00001846struct AddRHS {
1847 Value *RHS;
1848 AddRHS(Value *rhs) : RHS(rhs) {}
1849 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1850 Instruction *apply(BinaryOperator &Add) const {
Nick Lewycky02d639f2008-05-23 04:34:58 +00001851 return BinaryOperator::CreateShl(Add.getOperand(0),
1852 ConstantInt::get(Add.getType(), 1));
Chris Lattner564a7272003-08-13 19:01:45 +00001853 }
1854};
1855
1856// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1857// iff C1&C2 == 0
1858struct AddMaskingAnd {
1859 Constant *C2;
1860 AddMaskingAnd(Constant *c) : C2(c) {}
1861 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001862 ConstantInt *C1;
Misha Brukmanfd939082005-04-21 23:48:37 +00001863 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001864 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +00001865 }
1866 Instruction *apply(BinaryOperator &Add) const {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001867 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +00001868 }
1869};
1870
Dan Gohman844731a2008-05-13 00:00:25 +00001871}
1872
Chris Lattner6e7ba452005-01-01 16:22:27 +00001873static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +00001874 InstCombiner *IC) {
Reid Spencer3da59db2006-11-27 01:05:10 +00001875 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00001876 return IC->InsertCastBefore(CI->getOpcode(), SO, I.getType(), I);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001877 }
1878
Chris Lattner2eefe512004-04-09 19:05:30 +00001879 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +00001880 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1881 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +00001882
Chris Lattner2eefe512004-04-09 19:05:30 +00001883 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1884 if (ConstIsRHS)
Chris Lattner6e7ba452005-01-01 16:22:27 +00001885 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1886 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +00001887 }
1888
1889 Value *Op0 = SO, *Op1 = ConstOperand;
1890 if (!ConstIsRHS)
1891 std::swap(Op0, Op1);
1892 Instruction *New;
Chris Lattner6e7ba452005-01-01 16:22:27 +00001893 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001894 New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Reid Spencere4d87aa2006-12-23 06:05:41 +00001895 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001896 New = CmpInst::Create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
Reid Spencere4d87aa2006-12-23 06:05:41 +00001897 SO->getName()+".cmp");
Chris Lattner326c0f32004-04-10 19:15:56 +00001898 else {
Chris Lattner2eefe512004-04-09 19:05:30 +00001899 assert(0 && "Unknown binary instruction type!");
Chris Lattner326c0f32004-04-10 19:15:56 +00001900 abort();
1901 }
Chris Lattner6e7ba452005-01-01 16:22:27 +00001902 return IC->InsertNewInstBefore(New, I);
1903}
1904
1905// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1906// constant as the other operand, try to fold the binary operator into the
1907// select arguments. This also works for Cast instructions, which obviously do
1908// not have a second operand.
1909static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1910 InstCombiner *IC) {
1911 // Don't modify shared select instructions
1912 if (!SI->hasOneUse()) return 0;
1913 Value *TV = SI->getOperand(1);
1914 Value *FV = SI->getOperand(2);
1915
1916 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +00001917 // Bool selects with constant operands can be folded to logical ops.
Reid Spencer4fe16d62007-01-11 18:21:29 +00001918 if (SI->getType() == Type::Int1Ty) return 0;
Chris Lattner956db272005-04-21 05:43:13 +00001919
Chris Lattner6e7ba452005-01-01 16:22:27 +00001920 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1921 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1922
Gabor Greif051a9502008-04-06 20:25:17 +00001923 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1924 SelectFalseVal);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001925 }
1926 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +00001927}
1928
Chris Lattner4e998b22004-09-29 05:07:12 +00001929
1930/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1931/// node as operand #0, see if we can fold the instruction into the PHI (which
1932/// is only possible if all operands to the PHI are constants).
1933Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1934 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00001935 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001936 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner4e998b22004-09-29 05:07:12 +00001937
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001938 // Check to see if all of the operands of the PHI are constants. If there is
1939 // one non-constant value, remember the BB it is. If there is more than one
Chris Lattnerb3036682007-02-24 01:03:45 +00001940 // or if *it* is a PHI, bail out.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001941 BasicBlock *NonConstBB = 0;
1942 for (unsigned i = 0; i != NumPHIValues; ++i)
1943 if (!isa<Constant>(PN->getIncomingValue(i))) {
1944 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +00001945 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001946 NonConstBB = PN->getIncomingBlock(i);
1947
1948 // If the incoming non-constant value is in I's block, we have an infinite
1949 // loop.
1950 if (NonConstBB == I.getParent())
1951 return 0;
1952 }
1953
1954 // If there is exactly one non-constant value, we can insert a copy of the
1955 // operation in that block. However, if this is a critical edge, we would be
1956 // inserting the computation one some other paths (e.g. inside a loop). Only
1957 // do this if the pred block is unconditionally branching into the phi block.
1958 if (NonConstBB) {
1959 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1960 if (!BI || !BI->isUnconditional()) return 0;
1961 }
Chris Lattner4e998b22004-09-29 05:07:12 +00001962
1963 // Okay, we can do the transformation: create the new PHI node.
Gabor Greif051a9502008-04-06 20:25:17 +00001964 PHINode *NewPN = PHINode::Create(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +00001965 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner4e998b22004-09-29 05:07:12 +00001966 InsertNewInstBefore(NewPN, *PN);
Chris Lattner6934a042007-02-11 01:23:03 +00001967 NewPN->takeName(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +00001968
1969 // Next, add all of the operands to the PHI.
1970 if (I.getNumOperands() == 2) {
1971 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +00001972 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00001973 Value *InV = 0;
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001974 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001975 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1976 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1977 else
1978 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001979 } else {
1980 assert(PN->getIncomingBlock(i) == NonConstBB);
1981 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001982 InV = BinaryOperator::Create(BO->getOpcode(),
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001983 PN->getIncomingValue(i), C, "phitmp",
1984 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +00001985 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001986 InV = CmpInst::Create(CI->getOpcode(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00001987 CI->getPredicate(),
1988 PN->getIncomingValue(i), C, "phitmp",
1989 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001990 else
1991 assert(0 && "Unknown binop!");
1992
Chris Lattnerdbab3862007-03-02 21:28:56 +00001993 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001994 }
1995 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00001996 }
Reid Spencer3da59db2006-11-27 01:05:10 +00001997 } else {
1998 CastInst *CI = cast<CastInst>(&I);
1999 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +00002000 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002001 Value *InV;
2002 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00002003 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002004 } else {
2005 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002006 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Reid Spencer3da59db2006-11-27 01:05:10 +00002007 I.getType(), "phitmp",
2008 NonConstBB->getTerminator());
Chris Lattnerdbab3862007-03-02 21:28:56 +00002009 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002010 }
2011 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002012 }
2013 }
2014 return ReplaceInstUsesWith(I, NewPN);
2015}
2016
Chris Lattner2454a2e2008-01-29 06:52:45 +00002017
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002018/// WillNotOverflowSignedAdd - Return true if we can prove that:
2019/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
2020/// This basically requires proving that the add in the original type would not
2021/// overflow to change the sign bit or have a carry out.
2022bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2023 // There are different heuristics we can use for this. Here are some simple
2024 // ones.
2025
2026 // Add has the property that adding any two 2's complement numbers can only
2027 // have one carry bit which can change a sign. As such, if LHS and RHS each
2028 // have at least two sign bits, we know that the addition of the two values will
2029 // sign extend fine.
2030 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2031 return true;
2032
2033
2034 // If one of the operands only has one non-zero bit, and if the other operand
2035 // has a known-zero bit in a more significant place than it (not including the
2036 // sign bit) the ripple may go up to and fill the zero, but won't change the
2037 // sign. For example, (X & ~4) + 1.
2038
2039 // TODO: Implement.
2040
2041 return false;
2042}
2043
Chris Lattner2454a2e2008-01-29 06:52:45 +00002044
Chris Lattner7e708292002-06-25 16:13:24 +00002045Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002046 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002047 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002048
Chris Lattner66331a42004-04-10 22:01:55 +00002049 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattnere87597f2004-10-16 18:11:37 +00002050 // X + undef -> undef
2051 if (isa<UndefValue>(RHS))
2052 return ReplaceInstUsesWith(I, RHS);
2053
Chris Lattner66331a42004-04-10 22:01:55 +00002054 // X + 0 --> X
Chris Lattner9919e3d2006-12-02 00:13:08 +00002055 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
Chris Lattner5e678e02005-10-17 17:56:38 +00002056 if (RHSC->isNullValue())
2057 return ReplaceInstUsesWith(I, LHS);
Chris Lattner8532cf62005-10-17 20:18:38 +00002058 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00002059 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
2060 (I.getType())->getValueAPF()))
Chris Lattner8532cf62005-10-17 20:18:38 +00002061 return ReplaceInstUsesWith(I, LHS);
Chris Lattner5e678e02005-10-17 17:56:38 +00002062 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002063
Chris Lattner66331a42004-04-10 22:01:55 +00002064 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002065 // X + (signbit) --> X ^ signbit
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002066 const APInt& Val = CI->getValue();
Zhou Sheng4351c642007-04-02 08:20:41 +00002067 uint32_t BitWidth = Val.getBitWidth();
Reid Spencer2ec619a2007-03-23 21:24:59 +00002068 if (Val == APInt::getSignBit(BitWidth))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002069 return BinaryOperator::CreateXor(LHS, RHS);
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002070
2071 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2072 // (X & 254)+1 -> (X&254)|1
Chris Lattner886ab6c2009-01-31 08:15:18 +00002073 if (!isa<VectorType>(I.getType()) && SimplifyDemandedInstructionBits(I))
2074 return &I;
Dan Gohman1975d032008-10-30 20:40:10 +00002075
2076 // zext(i1) - 1 -> select i1, 0, -1
2077 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
2078 if (CI->isAllOnesValue() &&
2079 ZI->getOperand(0)->getType() == Type::Int1Ty)
2080 return SelectInst::Create(ZI->getOperand(0),
2081 Constant::getNullValue(I.getType()),
2082 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattner66331a42004-04-10 22:01:55 +00002083 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002084
2085 if (isa<PHINode>(LHS))
2086 if (Instruction *NV = FoldOpIntoPhi(I))
2087 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +00002088
Chris Lattner4f637d42006-01-06 17:59:59 +00002089 ConstantInt *XorRHS = 0;
2090 Value *XorLHS = 0;
Chris Lattnerc5eff442007-01-30 22:32:46 +00002091 if (isa<ConstantInt>(RHSC) &&
2092 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002093 uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002094 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner5931c542005-09-24 23:43:33 +00002095
Zhou Sheng4351c642007-04-02 08:20:41 +00002096 uint32_t Size = TySizeBits / 2;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002097 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2098 APInt CFF80Val(-C0080Val);
Chris Lattner5931c542005-09-24 23:43:33 +00002099 do {
2100 if (TySizeBits > Size) {
Chris Lattner5931c542005-09-24 23:43:33 +00002101 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2102 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002103 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2104 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner5931c542005-09-24 23:43:33 +00002105 // This is a sign extend if the top bits are known zero.
Zhou Sheng290bec52007-03-29 08:15:12 +00002106 if (!MaskedValueIsZero(XorLHS,
2107 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner5931c542005-09-24 23:43:33 +00002108 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002109 break;
Chris Lattner5931c542005-09-24 23:43:33 +00002110 }
2111 }
2112 Size >>= 1;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002113 C0080Val = APIntOps::lshr(C0080Val, Size);
2114 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2115 } while (Size >= 1);
Chris Lattner5931c542005-09-24 23:43:33 +00002116
Reid Spencer35c38852007-03-28 01:36:16 +00002117 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattner0c7a9a02008-05-19 20:25:04 +00002118 // with funny bit widths then this switch statement should be removed. It
2119 // is just here to get the size of the "middle" type back up to something
2120 // that the back ends can handle.
Reid Spencer35c38852007-03-28 01:36:16 +00002121 const Type *MiddleType = 0;
2122 switch (Size) {
2123 default: break;
2124 case 32: MiddleType = Type::Int32Ty; break;
2125 case 16: MiddleType = Type::Int16Ty; break;
2126 case 8: MiddleType = Type::Int8Ty; break;
2127 }
2128 if (MiddleType) {
Reid Spencerd977d862006-12-12 23:36:14 +00002129 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
Chris Lattner5931c542005-09-24 23:43:33 +00002130 InsertNewInstBefore(NewTrunc, I);
Reid Spencer35c38852007-03-28 01:36:16 +00002131 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner5931c542005-09-24 23:43:33 +00002132 }
2133 }
Chris Lattner66331a42004-04-10 22:01:55 +00002134 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002135
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002136 if (I.getType() == Type::Int1Ty)
2137 return BinaryOperator::CreateXor(LHS, RHS);
2138
Nick Lewycky7d26bd82008-05-23 04:39:38 +00002139 // X + X --> X << 1
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002140 if (I.getType()->isInteger()) {
Chris Lattner564a7272003-08-13 19:01:45 +00002141 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +00002142
2143 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2144 if (RHSI->getOpcode() == Instruction::Sub)
2145 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2146 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2147 }
2148 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2149 if (LHSI->getOpcode() == Instruction::Sub)
2150 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2151 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2152 }
Robert Bocchino71698282004-07-27 21:02:21 +00002153 }
Chris Lattnere92d2f42003-08-13 04:18:28 +00002154
Chris Lattner5c4afb92002-05-08 22:46:53 +00002155 // -A + B --> B - A
Chris Lattnerdd12f962008-02-17 21:03:36 +00002156 // -A + -B --> -(A + B)
2157 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattnere10c0b92008-02-18 17:50:16 +00002158 if (LHS->getType()->isIntOrIntVector()) {
2159 if (Value *RHSV = dyn_castNegVal(RHS)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002160 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
Chris Lattnere10c0b92008-02-18 17:50:16 +00002161 InsertNewInstBefore(NewAdd, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002162 return BinaryOperator::CreateNeg(NewAdd);
Chris Lattnere10c0b92008-02-18 17:50:16 +00002163 }
Chris Lattnerdd12f962008-02-17 21:03:36 +00002164 }
2165
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002166 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattnerdd12f962008-02-17 21:03:36 +00002167 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002168
2169 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +00002170 if (!isa<Constant>(RHS))
2171 if (Value *V = dyn_castNegVal(RHS))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002172 return BinaryOperator::CreateSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002173
Misha Brukmanfd939082005-04-21 23:48:37 +00002174
Chris Lattner50af16a2004-11-13 19:50:12 +00002175 ConstantInt *C2;
2176 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2177 if (X == RHS) // X*C + X --> X * (C+1)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002178 return BinaryOperator::CreateMul(RHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002179
2180 // X*C1 + X*C2 --> X * (C1+C2)
2181 ConstantInt *C1;
2182 if (X == dyn_castFoldableMul(RHS, C1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002183 return BinaryOperator::CreateMul(X, Add(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002184 }
2185
2186 // X + X*C --> X * (C+1)
Chris Lattner50af16a2004-11-13 19:50:12 +00002187 if (dyn_castFoldableMul(RHS, C2) == LHS)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002188 return BinaryOperator::CreateMul(LHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002189
Chris Lattnere617c9e2007-01-05 02:17:46 +00002190 // X + ~X --> -1 since ~X = -X-1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00002191 if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2192 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere617c9e2007-01-05 02:17:46 +00002193
Chris Lattnerad3448c2003-02-18 19:57:07 +00002194
Chris Lattner564a7272003-08-13 19:01:45 +00002195 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002196 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnere617c9e2007-01-05 02:17:46 +00002197 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2198 return R;
Chris Lattner5e0d7182008-05-19 20:01:56 +00002199
2200 // A+B --> A|B iff A and B have no bits set in common.
2201 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2202 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2203 APInt LHSKnownOne(IT->getBitWidth(), 0);
2204 APInt LHSKnownZero(IT->getBitWidth(), 0);
2205 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2206 if (LHSKnownZero != 0) {
2207 APInt RHSKnownOne(IT->getBitWidth(), 0);
2208 APInt RHSKnownZero(IT->getBitWidth(), 0);
2209 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2210
2211 // No bits in common -> bitwise or.
Chris Lattner9d60ba92008-05-19 20:03:53 +00002212 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattner5e0d7182008-05-19 20:01:56 +00002213 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattner5e0d7182008-05-19 20:01:56 +00002214 }
2215 }
Chris Lattnerc8802d22003-03-11 00:12:48 +00002216
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002217 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky0c2c3f62008-02-03 08:19:11 +00002218 if (I.getType()->isIntOrIntVector()) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002219 Value *W, *X, *Y, *Z;
2220 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2221 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2222 if (W != Y) {
2223 if (W == Z) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002224 std::swap(Y, Z);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002225 } else if (Y == X) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002226 std::swap(W, X);
2227 } else if (X == Z) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002228 std::swap(Y, Z);
2229 std::swap(W, X);
2230 }
2231 }
2232
2233 if (W == Y) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002234 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002235 LHS->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002236 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002237 }
2238 }
2239 }
2240
Chris Lattner6b032052003-10-02 15:11:26 +00002241 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002242 Value *X = 0;
Reid Spencer7177c3a2007-03-25 05:33:51 +00002243 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002244 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002245
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002246 // (X & FF00) + xx00 -> (X+xx00) & FF00
2247 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002248 Constant *Anded = And(CRHS, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002249 if (Anded == CRHS) {
2250 // See if all bits from the first bit set in the Add RHS up are included
2251 // in the mask. First, get the rightmost bit.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002252 const APInt& AddRHSV = CRHS->getValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002253
2254 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002255 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002256
2257 // See if the and mask includes all of these bits.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002258 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanfd939082005-04-21 23:48:37 +00002259
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002260 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2261 // Okay, the xform is safe. Insert the new add pronto.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002262 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002263 LHS->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002264 return BinaryOperator::CreateAnd(NewAdd, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002265 }
2266 }
2267 }
2268
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002269 // Try to fold constant add into select arguments.
2270 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002271 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002272 return R;
Chris Lattner6b032052003-10-02 15:11:26 +00002273 }
2274
Reid Spencer1628cec2006-10-26 06:15:43 +00002275 // add (cast *A to intptrtype) B ->
Chris Lattner42790482007-12-20 01:56:58 +00002276 // cast (GEP (cast *A to sbyte*) B) --> intptrtype
Andrew Lenharth16d79552006-09-19 18:24:51 +00002277 {
Reid Spencer3da59db2006-11-27 01:05:10 +00002278 CastInst *CI = dyn_cast<CastInst>(LHS);
2279 Value *Other = RHS;
Andrew Lenharth16d79552006-09-19 18:24:51 +00002280 if (!CI) {
2281 CI = dyn_cast<CastInst>(RHS);
2282 Other = LHS;
2283 }
Andrew Lenharth45633262006-09-20 15:37:57 +00002284 if (CI && CI->getType()->isSized() &&
Reid Spencerabaa8ca2007-01-08 16:32:00 +00002285 (CI->getType()->getPrimitiveSizeInBits() ==
2286 TD->getIntPtrType()->getPrimitiveSizeInBits())
Andrew Lenharth45633262006-09-20 15:37:57 +00002287 && isa<PointerType>(CI->getOperand(0)->getType())) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00002288 unsigned AS =
2289 cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +00002290 Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2291 PointerType::get(Type::Int8Ty, AS), I);
Gabor Greif051a9502008-04-06 20:25:17 +00002292 I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
Reid Spencer3da59db2006-11-27 01:05:10 +00002293 return new PtrToIntInst(I2, CI->getType());
Andrew Lenharth16d79552006-09-19 18:24:51 +00002294 }
2295 }
Christopher Lamb30f017a2007-12-18 09:34:41 +00002296
Chris Lattner42790482007-12-20 01:56:58 +00002297 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb30f017a2007-12-18 09:34:41 +00002298 {
2299 SelectInst *SI = dyn_cast<SelectInst>(LHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002300 Value *A = RHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002301 if (!SI) {
2302 SI = dyn_cast<SelectInst>(RHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002303 A = LHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002304 }
Chris Lattner42790482007-12-20 01:56:58 +00002305 if (SI && SI->hasOneUse()) {
Christopher Lamb30f017a2007-12-18 09:34:41 +00002306 Value *TV = SI->getTrueValue();
2307 Value *FV = SI->getFalseValue();
Chris Lattner6046fb72008-11-16 04:46:19 +00002308 Value *N;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002309
2310 // Can we fold the add into the argument of the select?
2311 // We check both true and false select arguments for a matching subtract.
Chris Lattner6046fb72008-11-16 04:46:19 +00002312 if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Specific(A))))
2313 // Fold the add into the true select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002314 return SelectInst::Create(SI->getCondition(), N, A);
Chris Lattner6046fb72008-11-16 04:46:19 +00002315 if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Specific(A))))
2316 // Fold the add into the false select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002317 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb30f017a2007-12-18 09:34:41 +00002318 }
2319 }
Chris Lattner2454a2e2008-01-29 06:52:45 +00002320
2321 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2322 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2323 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2324 return ReplaceInstUsesWith(I, LHS);
Andrew Lenharth16d79552006-09-19 18:24:51 +00002325
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002326 // Check for (add (sext x), y), see if we can merge this into an
2327 // integer add followed by a sext.
2328 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2329 // (add (sext x), cst) --> (sext (add x, cst'))
2330 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2331 Constant *CI =
2332 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
2333 if (LHSConv->hasOneUse() &&
2334 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
2335 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2336 // Insert the new, smaller add.
2337 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2338 CI, "addconv");
2339 InsertNewInstBefore(NewAdd, I);
2340 return new SExtInst(NewAdd, I.getType());
2341 }
2342 }
2343
2344 // (add (sext x), (sext y)) --> (sext (add int x, y))
2345 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2346 // Only do this if x/y have the same type, if at last one of them has a
2347 // single use (so we don't increase the number of sexts), and if the
2348 // integer add will not overflow.
2349 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2350 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2351 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2352 RHSConv->getOperand(0))) {
2353 // Insert the new integer add.
2354 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2355 RHSConv->getOperand(0),
2356 "addconv");
2357 InsertNewInstBefore(NewAdd, I);
2358 return new SExtInst(NewAdd, I.getType());
2359 }
2360 }
2361 }
2362
2363 // Check for (add double (sitofp x), y), see if we can merge this into an
2364 // integer add followed by a promotion.
2365 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2366 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2367 // ... if the constant fits in the integer value. This is useful for things
2368 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2369 // requires a constant pool load, and generally allows the add to be better
2370 // instcombined.
2371 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2372 Constant *CI =
2373 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
2374 if (LHSConv->hasOneUse() &&
2375 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
2376 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2377 // Insert the new integer add.
2378 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2379 CI, "addconv");
2380 InsertNewInstBefore(NewAdd, I);
2381 return new SIToFPInst(NewAdd, I.getType());
2382 }
2383 }
2384
2385 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2386 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2387 // Only do this if x/y have the same type, if at last one of them has a
2388 // single use (so we don't increase the number of int->fp conversions),
2389 // and if the integer add will not overflow.
2390 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2391 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2392 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2393 RHSConv->getOperand(0))) {
2394 // Insert the new integer add.
2395 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2396 RHSConv->getOperand(0),
2397 "addconv");
2398 InsertNewInstBefore(NewAdd, I);
2399 return new SIToFPInst(NewAdd, I.getType());
2400 }
2401 }
2402 }
2403
Chris Lattner7e708292002-06-25 16:13:24 +00002404 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002405}
2406
Chris Lattner7e708292002-06-25 16:13:24 +00002407Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00002408 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002409
Chris Lattnerd137ab42008-07-17 06:07:20 +00002410 if (Op0 == Op1 && // sub X, X -> 0
2411 !I.getType()->isFPOrFPVector())
Chris Lattner233f7dc2002-08-12 21:17:25 +00002412 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002413
Chris Lattner233f7dc2002-08-12 21:17:25 +00002414 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattner8d969642003-03-10 23:06:50 +00002415 if (Value *V = dyn_castNegVal(Op1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002416 return BinaryOperator::CreateAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002417
Chris Lattnere87597f2004-10-16 18:11:37 +00002418 if (isa<UndefValue>(Op0))
2419 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2420 if (isa<UndefValue>(Op1))
2421 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2422
Chris Lattnerd65460f2003-11-05 01:06:05 +00002423 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2424 // Replace (-1 - A) with (~A)...
Chris Lattnera2881962003-02-18 19:28:33 +00002425 if (C->isAllOnesValue())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002426 return BinaryOperator::CreateNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +00002427
Chris Lattnerd65460f2003-11-05 01:06:05 +00002428 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002429 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002430 if (match(Op1, m_Not(m_Value(X))))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002431 return BinaryOperator::CreateAdd(X, AddOne(C));
Reid Spencer7177c3a2007-03-25 05:33:51 +00002432
Chris Lattner76b7a062007-01-15 07:02:54 +00002433 // -(X >>u 31) -> (X >>s 31)
2434 // -(X >>s 31) -> (X >>u 31)
Zhou Sheng302748d2007-03-30 17:20:39 +00002435 if (C->isZero()) {
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002436 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002437 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002438 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00002439 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002440 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerb83eb642006-10-20 07:07:24 +00002441 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002442 // Ok, the transformation is safe. Insert AShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002443 return BinaryOperator::Create(Instruction::AShr,
Reid Spencer832254e2007-02-02 02:16:23 +00002444 SI->getOperand(0), CU, SI->getName());
Chris Lattner9c290672004-03-12 23:53:13 +00002445 }
2446 }
Reid Spencer3822ff52006-11-08 06:47:33 +00002447 }
2448 else if (SI->getOpcode() == Instruction::AShr) {
2449 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2450 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002451 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencer3822ff52006-11-08 06:47:33 +00002452 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00002453 // Ok, the transformation is safe. Insert LShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002454 return BinaryOperator::CreateLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00002455 SI->getOperand(0), CU, SI->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00002456 }
2457 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002458 }
2459 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00002460 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002461
2462 // Try to fold constant sub into select arguments.
2463 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002464 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002465 return R;
Chris Lattnerd65460f2003-11-05 01:06:05 +00002466 }
2467
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002468 if (I.getType() == Type::Int1Ty)
2469 return BinaryOperator::CreateXor(Op0, Op1);
2470
Chris Lattner43d84d62005-04-07 16:15:25 +00002471 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2472 if (Op1I->getOpcode() == Instruction::Add &&
Chris Lattner9919e3d2006-12-02 00:13:08 +00002473 !Op0->getType()->isFPOrFPVector()) {
Chris Lattner08954a22005-04-07 16:28:01 +00002474 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002475 return BinaryOperator::CreateNeg(Op1I->getOperand(1), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002476 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002477 return BinaryOperator::CreateNeg(Op1I->getOperand(0), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002478 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2479 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2480 // C1-(X+C2) --> (C1-C2)-X
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002481 return BinaryOperator::CreateSub(Subtract(CI1, CI2),
Chris Lattner08954a22005-04-07 16:28:01 +00002482 Op1I->getOperand(0));
2483 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002484 }
2485
Chris Lattnerfd059242003-10-15 16:48:29 +00002486 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002487 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2488 // is not used by anyone else...
2489 //
Chris Lattner0517e722004-02-02 20:09:56 +00002490 if (Op1I->getOpcode() == Instruction::Sub &&
Chris Lattner9919e3d2006-12-02 00:13:08 +00002491 !Op1I->getType()->isFPOrFPVector()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002492 // Swap the two operands of the subexpr...
2493 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2494 Op1I->setOperand(0, IIOp1);
2495 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00002496
Chris Lattnera2881962003-02-18 19:28:33 +00002497 // Create the new top level add instruction...
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002498 return BinaryOperator::CreateAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00002499 }
2500
2501 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2502 //
2503 if (Op1I->getOpcode() == Instruction::And &&
2504 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2505 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2506
Chris Lattnerf523d062004-06-09 05:08:07 +00002507 Value *NewNot =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002508 InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
2509 return BinaryOperator::CreateAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00002510 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00002511
Reid Spencerac5209e2006-10-16 23:08:08 +00002512 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer1628cec2006-10-26 06:15:43 +00002513 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencerb83eb642006-10-20 07:07:24 +00002514 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Zhou Sheng843f07672007-04-19 05:39:12 +00002515 if (CSI->isZero())
Chris Lattner91ccc152004-10-06 15:08:25 +00002516 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002517 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Chris Lattner91ccc152004-10-06 15:08:25 +00002518 ConstantExpr::getNeg(DivRHS));
2519
Chris Lattnerad3448c2003-02-18 19:57:07 +00002520 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002521 ConstantInt *C2 = 0;
Chris Lattner50af16a2004-11-13 19:50:12 +00002522 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002523 Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002524 return BinaryOperator::CreateMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00002525 }
Chris Lattner40371712002-05-09 01:29:19 +00002526 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002527 }
Chris Lattnera2881962003-02-18 19:28:33 +00002528
Chris Lattner9919e3d2006-12-02 00:13:08 +00002529 if (!Op0->getType()->isFPOrFPVector())
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002530 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner7edc8c22005-04-07 17:14:51 +00002531 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00002532 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2533 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2534 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2535 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner7edc8c22005-04-07 17:14:51 +00002536 } else if (Op0I->getOpcode() == Instruction::Sub) {
2537 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002538 return BinaryOperator::CreateNeg(Op0I->getOperand(1), I.getName());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00002539 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002540 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002541
Chris Lattner50af16a2004-11-13 19:50:12 +00002542 ConstantInt *C1;
2543 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002544 if (X == Op1) // X*C - X --> X * (C-1)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002545 return BinaryOperator::CreateMul(Op1, SubOne(C1));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002546
Chris Lattner50af16a2004-11-13 19:50:12 +00002547 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2548 if (X == dyn_castFoldableMul(Op1, C2))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002549 return BinaryOperator::CreateMul(X, Subtract(C1, C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002550 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002551 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002552}
2553
Chris Lattnera0141b92007-07-15 20:42:37 +00002554/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2555/// comparison only checks the sign bit. If it only checks the sign bit, set
2556/// TrueIfSigned if the result of the comparison is true when the input value is
2557/// signed.
2558static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2559 bool &TrueIfSigned) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002560 switch (pred) {
Chris Lattnera0141b92007-07-15 20:42:37 +00002561 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2562 TrueIfSigned = true;
2563 return RHS->isZero();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002564 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2565 TrueIfSigned = true;
2566 return RHS->isAllOnesValue();
Chris Lattnera0141b92007-07-15 20:42:37 +00002567 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2568 TrueIfSigned = false;
2569 return RHS->isAllOnesValue();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002570 case ICmpInst::ICMP_UGT:
2571 // True if LHS u> RHS and RHS == high-bit-mask - 1
2572 TrueIfSigned = true;
2573 return RHS->getValue() ==
2574 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2575 case ICmpInst::ICMP_UGE:
2576 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2577 TrueIfSigned = true;
Chris Lattner833f25d2008-06-02 01:29:46 +00002578 return RHS->getValue().isSignBit();
Chris Lattnera0141b92007-07-15 20:42:37 +00002579 default:
2580 return false;
Chris Lattner4cb170c2004-02-23 06:38:22 +00002581 }
Chris Lattner4cb170c2004-02-23 06:38:22 +00002582}
2583
Chris Lattner7e708292002-06-25 16:13:24 +00002584Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002585 bool Changed = SimplifyCommutative(I);
Chris Lattnera2881962003-02-18 19:28:33 +00002586 Value *Op0 = I.getOperand(0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002587
Chris Lattnere87597f2004-10-16 18:11:37 +00002588 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2589 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2590
Chris Lattner233f7dc2002-08-12 21:17:25 +00002591 // Simplify mul instructions with a constant RHS...
Chris Lattnera2881962003-02-18 19:28:33 +00002592 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2593 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00002594
2595 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer832254e2007-02-02 02:16:23 +00002596 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnere92d2f42003-08-13 04:18:28 +00002597 if (SI->getOpcode() == Instruction::Shl)
2598 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002599 return BinaryOperator::CreateMul(SI->getOperand(0),
Chris Lattner48595f12004-06-10 02:07:29 +00002600 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00002601
Zhou Sheng843f07672007-04-19 05:39:12 +00002602 if (CI->isZero())
Chris Lattner515c97c2003-09-11 22:24:54 +00002603 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2604 if (CI->equalsInt(1)) // X * 1 == X
2605 return ReplaceInstUsesWith(I, Op0);
2606 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002607 return BinaryOperator::CreateNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00002608
Zhou Sheng97b52c22007-03-29 01:57:21 +00002609 const APInt& Val = cast<ConstantInt>(CI)->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002610 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002611 return BinaryOperator::CreateShl(Op0,
Reid Spencerbca0e382007-03-23 20:05:17 +00002612 ConstantInt::get(Op0->getType(), Val.logBase2()));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00002613 }
Robert Bocchino71698282004-07-27 21:02:21 +00002614 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattnera2881962003-02-18 19:28:33 +00002615 if (Op1F->isNullValue())
2616 return ReplaceInstUsesWith(I, Op1);
Chris Lattner6c1ce212002-04-29 22:24:47 +00002617
Chris Lattnera2881962003-02-18 19:28:33 +00002618 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2619 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
Chris Lattnerb8cd4d32008-08-11 22:06:05 +00002620 if (Op1F->isExactlyValue(1.0))
2621 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2622 } else if (isa<VectorType>(Op1->getType())) {
2623 if (isa<ConstantAggregateZero>(Op1))
2624 return ReplaceInstUsesWith(I, Op1);
Nick Lewycky895f0852008-11-27 20:21:08 +00002625
2626 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2627 if (Op1V->isAllOnesValue()) // X * -1 == 0 - X
2628 return BinaryOperator::CreateNeg(Op0, I.getName());
2629
2630 // As above, vector X*splat(1.0) -> X in all defined cases.
2631 if (Constant *Splat = Op1V->getSplatValue()) {
2632 if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2633 if (F->isExactlyValue(1.0))
2634 return ReplaceInstUsesWith(I, Op0);
2635 if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2636 if (CI->equalsInt(1))
2637 return ReplaceInstUsesWith(I, Op0);
2638 }
2639 }
Chris Lattnera2881962003-02-18 19:28:33 +00002640 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002641
2642 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2643 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattner47c99092008-05-18 04:11:26 +00002644 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002645 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002646 Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002647 Op1, "tmp");
2648 InsertNewInstBefore(Add, I);
2649 Value *C1C2 = ConstantExpr::getMul(Op1,
2650 cast<Constant>(Op0I->getOperand(1)));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002651 return BinaryOperator::CreateAdd(Add, C1C2);
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002652
2653 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002654
2655 // Try to fold constant mul into select arguments.
2656 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002657 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002658 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002659
2660 if (isa<PHINode>(Op0))
2661 if (Instruction *NV = FoldOpIntoPhi(I))
2662 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002663 }
2664
Chris Lattnera4f445b2003-03-10 23:23:04 +00002665 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2666 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002667 return BinaryOperator::CreateMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00002668
Nick Lewycky0c730792008-11-21 07:33:58 +00002669 // (X / Y) * Y = X - (X % Y)
2670 // (X / Y) * -Y = (X % Y) - X
2671 {
2672 Value *Op1 = I.getOperand(1);
2673 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2674 if (!BO ||
2675 (BO->getOpcode() != Instruction::UDiv &&
2676 BO->getOpcode() != Instruction::SDiv)) {
2677 Op1 = Op0;
2678 BO = dyn_cast<BinaryOperator>(I.getOperand(1));
2679 }
2680 Value *Neg = dyn_castNegVal(Op1);
2681 if (BO && BO->hasOneUse() &&
2682 (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) &&
2683 (BO->getOpcode() == Instruction::UDiv ||
2684 BO->getOpcode() == Instruction::SDiv)) {
2685 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2686
2687 Instruction *Rem;
2688 if (BO->getOpcode() == Instruction::UDiv)
2689 Rem = BinaryOperator::CreateURem(Op0BO, Op1BO);
2690 else
2691 Rem = BinaryOperator::CreateSRem(Op0BO, Op1BO);
2692
2693 InsertNewInstBefore(Rem, I);
2694 Rem->takeName(BO);
2695
2696 if (Op1BO == Op1)
2697 return BinaryOperator::CreateSub(Op0BO, Rem);
2698 else
2699 return BinaryOperator::CreateSub(Rem, Op0BO);
2700 }
2701 }
2702
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002703 if (I.getType() == Type::Int1Ty)
2704 return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2705
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002706 // If one of the operands of the multiply is a cast from a boolean value, then
2707 // we know the bool is either zero or one, so this is a 'masking' multiply.
2708 // See if we can simplify things based on how the boolean was originally
2709 // formed.
2710 CastInst *BoolCast = 0;
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002711 if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002712 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002713 BoolCast = CI;
2714 if (!BoolCast)
Reid Spencerc55b2432006-12-13 18:21:21 +00002715 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002716 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002717 BoolCast = CI;
2718 if (BoolCast) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002719 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002720 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2721 const Type *SCOpTy = SCIOp0->getType();
Chris Lattnera0141b92007-07-15 20:42:37 +00002722 bool TIS = false;
2723
Reid Spencere4d87aa2006-12-23 06:05:41 +00002724 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattner4cb170c2004-02-23 06:38:22 +00002725 // multiply into a shift/and combination.
2726 if (isa<ConstantInt>(SCIOp1) &&
Chris Lattnera0141b92007-07-15 20:42:37 +00002727 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2728 TIS) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002729 // Shift the X value right to turn it into "all signbits".
Reid Spencer832254e2007-02-02 02:16:23 +00002730 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
Chris Lattner484d3cf2005-04-24 06:59:08 +00002731 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattner4cb170c2004-02-23 06:38:22 +00002732 Value *V =
Reid Spencer832254e2007-02-02 02:16:23 +00002733 InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002734 BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
Chris Lattner4cb170c2004-02-23 06:38:22 +00002735 BoolCast->getOperand(0)->getName()+
2736 ".mask"), I);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002737
2738 // If the multiply type is not the same as the source type, sign extend
2739 // or truncate to the multiply type.
Reid Spencer17212df2006-12-12 09:18:51 +00002740 if (I.getType() != V->getType()) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002741 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2742 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +00002743 Instruction::CastOps opcode =
2744 (SrcBits == DstBits ? Instruction::BitCast :
2745 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2746 V = InsertCastBefore(opcode, V, I.getType(), I);
2747 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002748
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002749 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002750 return BinaryOperator::CreateAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002751 }
2752 }
2753 }
2754
Chris Lattner7e708292002-06-25 16:13:24 +00002755 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002756}
2757
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002758/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2759/// instruction.
2760bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2761 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2762
2763 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2764 int NonNullOperand = -1;
2765 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2766 if (ST->isNullValue())
2767 NonNullOperand = 2;
2768 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2769 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2770 if (ST->isNullValue())
2771 NonNullOperand = 1;
2772
2773 if (NonNullOperand == -1)
2774 return false;
2775
2776 Value *SelectCond = SI->getOperand(0);
2777
2778 // Change the div/rem to use 'Y' instead of the select.
2779 I.setOperand(1, SI->getOperand(NonNullOperand));
2780
2781 // Okay, we know we replace the operand of the div/rem with 'Y' with no
2782 // problem. However, the select, or the condition of the select may have
2783 // multiple uses. Based on our knowledge that the operand must be non-zero,
2784 // propagate the known value for the select into other uses of it, and
2785 // propagate a known value of the condition into its other users.
2786
2787 // If the select and condition only have a single use, don't bother with this,
2788 // early exit.
2789 if (SI->use_empty() && SelectCond->hasOneUse())
2790 return true;
2791
2792 // Scan the current block backward, looking for other uses of SI.
2793 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2794
2795 while (BBI != BBFront) {
2796 --BBI;
2797 // If we found a call to a function, we can't assume it will return, so
2798 // information from below it cannot be propagated above it.
2799 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2800 break;
2801
2802 // Replace uses of the select or its condition with the known values.
2803 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2804 I != E; ++I) {
2805 if (*I == SI) {
2806 *I = SI->getOperand(NonNullOperand);
2807 AddToWorkList(BBI);
2808 } else if (*I == SelectCond) {
2809 *I = NonNullOperand == 1 ? ConstantInt::getTrue() :
2810 ConstantInt::getFalse();
2811 AddToWorkList(BBI);
2812 }
2813 }
2814
2815 // If we past the instruction, quit looking for it.
2816 if (&*BBI == SI)
2817 SI = 0;
2818 if (&*BBI == SelectCond)
2819 SelectCond = 0;
2820
2821 // If we ran out of things to eliminate, break out of the loop.
2822 if (SelectCond == 0 && SI == 0)
2823 break;
2824
2825 }
2826 return true;
2827}
2828
2829
Reid Spencer1628cec2006-10-26 06:15:43 +00002830/// This function implements the transforms on div instructions that work
2831/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2832/// used by the visitors to those instructions.
2833/// @brief Transforms common to all three div instructions
Reid Spencer3da59db2006-11-27 01:05:10 +00002834Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002835 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00002836
Chris Lattner50b2ca42008-02-19 06:12:18 +00002837 // undef / X -> 0 for integer.
2838 // undef / X -> undef for FP (the undef could be a snan).
2839 if (isa<UndefValue>(Op0)) {
2840 if (Op0->getType()->isFPOrFPVector())
2841 return ReplaceInstUsesWith(I, Op0);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002842 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00002843 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002844
2845 // X / undef -> undef
Chris Lattner857e8cd2004-12-12 21:48:58 +00002846 if (isa<UndefValue>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00002847 return ReplaceInstUsesWith(I, Op1);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002848
Reid Spencer1628cec2006-10-26 06:15:43 +00002849 return 0;
2850}
Misha Brukmanfd939082005-04-21 23:48:37 +00002851
Reid Spencer1628cec2006-10-26 06:15:43 +00002852/// This function implements the transforms common to both integer division
2853/// instructions (udiv and sdiv). It is called by the visitors to those integer
2854/// division instructions.
2855/// @brief Common integer divide transforms
Reid Spencer3da59db2006-11-27 01:05:10 +00002856Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002857 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2858
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00002859 // (sdiv X, X) --> 1 (udiv X, X) --> 1
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002860 if (Op0 == Op1) {
2861 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
2862 ConstantInt *CI = ConstantInt::get(Ty->getElementType(), 1);
2863 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
2864 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
2865 }
2866
2867 ConstantInt *CI = ConstantInt::get(I.getType(), 1);
2868 return ReplaceInstUsesWith(I, CI);
2869 }
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00002870
Reid Spencer1628cec2006-10-26 06:15:43 +00002871 if (Instruction *Common = commonDivTransforms(I))
2872 return Common;
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002873
2874 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2875 // This does not apply for fdiv.
2876 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2877 return &I;
Reid Spencer1628cec2006-10-26 06:15:43 +00002878
2879 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2880 // div X, 1 == X
2881 if (RHS->equalsInt(1))
2882 return ReplaceInstUsesWith(I, Op0);
2883
2884 // (X / C1) / C2 -> X / (C1*C2)
2885 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2886 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2887 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00002888 if (MultiplyOverflows(RHS, LHSRHS, I.getOpcode()==Instruction::SDiv))
2889 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2890 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002891 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00002892 Multiply(RHS, LHSRHS));
Chris Lattnerbf70b832005-04-08 04:03:26 +00002893 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002894
Reid Spencerbca0e382007-03-23 20:05:17 +00002895 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer1628cec2006-10-26 06:15:43 +00002896 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2897 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2898 return R;
2899 if (isa<PHINode>(Op0))
2900 if (Instruction *NV = FoldOpIntoPhi(I))
2901 return NV;
2902 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002903 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002904
Chris Lattnera2881962003-02-18 19:28:33 +00002905 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00002906 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00002907 if (LHS->equalsInt(0))
2908 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2909
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002910 // It can't be division by zero, hence it must be division by one.
2911 if (I.getType() == Type::Int1Ty)
2912 return ReplaceInstUsesWith(I, Op0);
2913
Nick Lewycky895f0852008-11-27 20:21:08 +00002914 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2915 if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
2916 // div X, 1 == X
2917 if (X->isOne())
2918 return ReplaceInstUsesWith(I, Op0);
2919 }
2920
Reid Spencer1628cec2006-10-26 06:15:43 +00002921 return 0;
2922}
2923
2924Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2925 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2926
2927 // Handle the integer div common cases
2928 if (Instruction *Common = commonIDivTransforms(I))
2929 return Common;
2930
Reid Spencer1628cec2006-10-26 06:15:43 +00002931 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky8ca52482008-11-27 22:41:10 +00002932 // X udiv C^2 -> X >> C
2933 // Check to see if this is an unsigned division with an exact power of 2,
2934 // if so, convert to a right shift.
Reid Spencer6eb0d992007-03-26 23:58:26 +00002935 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002936 return BinaryOperator::CreateLShr(Op0,
Zhou Sheng0fc50952007-03-25 05:01:29 +00002937 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Nick Lewycky8ca52482008-11-27 22:41:10 +00002938
2939 // X udiv C, where C >= signbit
2940 if (C->getValue().isNegative()) {
2941 Value *IC = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_ULT, Op0, C),
2942 I);
2943 return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
2944 ConstantInt::get(I.getType(), 1));
2945 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002946 }
2947
2948 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer832254e2007-02-02 02:16:23 +00002949 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002950 if (RHSI->getOpcode() == Instruction::Shl &&
2951 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002952 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002953 if (C1.isPowerOf2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002954 Value *N = RHSI->getOperand(1);
Reid Spencer3da59db2006-11-27 01:05:10 +00002955 const Type *NTy = N->getType();
Reid Spencer2ec619a2007-03-23 21:24:59 +00002956 if (uint32_t C2 = C1.logBase2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002957 Constant *C2V = ConstantInt::get(NTy, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002958 N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002959 }
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002960 return BinaryOperator::CreateLShr(Op0, N);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002961 }
2962 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00002963 }
2964
Reid Spencer1628cec2006-10-26 06:15:43 +00002965 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2966 // where C1&C2 are powers of two.
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002967 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00002968 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002969 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002970 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002971 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002972 // Compute the shift amounts
Reid Spencerbca0e382007-03-23 20:05:17 +00002973 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002974 // Construct the "on true" case of the select
2975 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002976 Instruction *TSI = BinaryOperator::CreateLShr(
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002977 Op0, TC, SI->getName()+".t");
2978 TSI = InsertNewInstBefore(TSI, I);
2979
2980 // Construct the "on false" case of the select
2981 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002982 Instruction *FSI = BinaryOperator::CreateLShr(
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002983 Op0, FC, SI->getName()+".f");
2984 FSI = InsertNewInstBefore(FSI, I);
Reid Spencer1628cec2006-10-26 06:15:43 +00002985
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002986 // construct the select instruction and return it.
Gabor Greif051a9502008-04-06 20:25:17 +00002987 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00002988 }
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002989 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002990 return 0;
2991}
2992
Reid Spencer1628cec2006-10-26 06:15:43 +00002993Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2994 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2995
2996 // Handle the integer div common cases
2997 if (Instruction *Common = commonIDivTransforms(I))
2998 return Common;
2999
3000 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3001 // sdiv X, -1 == -X
3002 if (RHS->isAllOnesValue())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003003 return BinaryOperator::CreateNeg(Op0);
Reid Spencer1628cec2006-10-26 06:15:43 +00003004 }
3005
3006 // If the sign bits of both operands are zero (i.e. we can prove they are
3007 // unsigned inputs), turn this into a udiv.
Chris Lattner42a75512007-01-15 02:27:26 +00003008 if (I.getType()->isInteger()) {
Reid Spencerbca0e382007-03-23 20:05:17 +00003009 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Reid Spencer1628cec2006-10-26 06:15:43 +00003010 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Dan Gohmancff55092007-11-05 23:16:33 +00003011 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003012 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00003013 }
3014 }
3015
3016 return 0;
3017}
3018
3019Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3020 return commonDivTransforms(I);
3021}
Chris Lattner3f5b8772002-05-06 16:14:14 +00003022
Reid Spencer0a783f72006-11-02 01:53:59 +00003023/// This function implements the transforms on rem instructions that work
3024/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3025/// is used by the visitors to those instructions.
3026/// @brief Transforms common to all three rem instructions
3027Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00003028 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer0a783f72006-11-02 01:53:59 +00003029
Chris Lattner50b2ca42008-02-19 06:12:18 +00003030 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3031 if (I.getType()->isFPOrFPVector())
3032 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003033 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00003034 }
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003035 if (isa<UndefValue>(Op1))
3036 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer0a783f72006-11-02 01:53:59 +00003037
3038 // Handle cases involving: rem X, (select Cond, Y, Z)
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003039 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3040 return &I;
Chris Lattner5b73c082004-07-06 07:01:22 +00003041
Reid Spencer0a783f72006-11-02 01:53:59 +00003042 return 0;
3043}
3044
3045/// This function implements the transforms common to both integer remainder
3046/// instructions (urem and srem). It is called by the visitors to those integer
3047/// remainder instructions.
3048/// @brief Common integer remainder transforms
3049Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3050 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3051
3052 if (Instruction *common = commonRemTransforms(I))
3053 return common;
3054
Dale Johannesened6af242009-01-21 00:35:19 +00003055 // 0 % X == 0 for integer, we don't need to preserve faults!
3056 if (Constant *LHS = dyn_cast<Constant>(Op0))
3057 if (LHS->isNullValue())
3058 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3059
Chris Lattner857e8cd2004-12-12 21:48:58 +00003060 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003061 // X % 0 == undef, we don't need to preserve faults!
3062 if (RHS->equalsInt(0))
3063 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3064
Chris Lattnera2881962003-02-18 19:28:33 +00003065 if (RHS->equalsInt(1)) // X % 1 == 0
3066 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3067
Chris Lattner97943922006-02-28 05:49:21 +00003068 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3069 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3070 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3071 return R;
3072 } else if (isa<PHINode>(Op0I)) {
3073 if (Instruction *NV = FoldOpIntoPhi(I))
3074 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00003075 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003076
3077 // See if we can fold away this rem instruction.
Chris Lattner886ab6c2009-01-31 08:15:18 +00003078 if (SimplifyDemandedInstructionBits(I))
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003079 return &I;
Chris Lattner97943922006-02-28 05:49:21 +00003080 }
Chris Lattnera2881962003-02-18 19:28:33 +00003081 }
3082
Reid Spencer0a783f72006-11-02 01:53:59 +00003083 return 0;
3084}
3085
3086Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3087 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3088
3089 if (Instruction *common = commonIRemTransforms(I))
3090 return common;
3091
3092 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3093 // X urem C^2 -> X and C
3094 // Check to see if this is an unsigned remainder with an exact power of 2,
3095 // if so, convert to a bitwise and.
3096 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencerbca0e382007-03-23 20:05:17 +00003097 if (C->getValue().isPowerOf2())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003098 return BinaryOperator::CreateAnd(Op0, SubOne(C));
Reid Spencer0a783f72006-11-02 01:53:59 +00003099 }
3100
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003101 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003102 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3103 if (RHSI->getOpcode() == Instruction::Shl &&
3104 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng0fc50952007-03-25 05:01:29 +00003105 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003106 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003107 Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003108 "tmp"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003109 return BinaryOperator::CreateAnd(Op0, Add);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003110 }
3111 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003112 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003113
Reid Spencer0a783f72006-11-02 01:53:59 +00003114 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3115 // where C1&C2 are powers of two.
3116 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3117 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3118 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3119 // STO == 0 and SFO == 0 handled above.
Reid Spencerbca0e382007-03-23 20:05:17 +00003120 if ((STO->getValue().isPowerOf2()) &&
3121 (SFO->getValue().isPowerOf2())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003122 Value *TrueAnd = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003123 BinaryOperator::CreateAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
Reid Spencer0a783f72006-11-02 01:53:59 +00003124 Value *FalseAnd = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003125 BinaryOperator::CreateAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
Gabor Greif051a9502008-04-06 20:25:17 +00003126 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Reid Spencer0a783f72006-11-02 01:53:59 +00003127 }
3128 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003129 }
3130
Chris Lattner3f5b8772002-05-06 16:14:14 +00003131 return 0;
3132}
3133
Reid Spencer0a783f72006-11-02 01:53:59 +00003134Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3135 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3136
Dan Gohmancff55092007-11-05 23:16:33 +00003137 // Handle the integer rem common cases
Reid Spencer0a783f72006-11-02 01:53:59 +00003138 if (Instruction *common = commonIRemTransforms(I))
3139 return common;
3140
3141 if (Value *RHSNeg = dyn_castNegVal(Op1))
Nick Lewycky23c04302008-09-03 06:24:21 +00003142 if (!isa<Constant>(RHSNeg) ||
3143 (isa<ConstantInt>(RHSNeg) &&
3144 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003145 // X % -Y -> X % Y
3146 AddUsesToWorkList(I);
3147 I.setOperand(1, RHSNeg);
3148 return &I;
3149 }
Nick Lewyckya06cf822008-09-30 06:08:34 +00003150
Dan Gohmancff55092007-11-05 23:16:33 +00003151 // If the sign bits of both operands are zero (i.e. we can prove they are
Reid Spencer0a783f72006-11-02 01:53:59 +00003152 // unsigned inputs), turn this into a urem.
Dan Gohmancff55092007-11-05 23:16:33 +00003153 if (I.getType()->isInteger()) {
3154 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3155 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3156 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003157 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmancff55092007-11-05 23:16:33 +00003158 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003159 }
3160
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003161 // If it's a constant vector, flip any negative values positive.
Nick Lewycky9dce8732008-12-20 16:48:00 +00003162 if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3163 unsigned VWidth = RHSV->getNumOperands();
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003164
Nick Lewycky9dce8732008-12-20 16:48:00 +00003165 bool hasNegative = false;
3166 for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3167 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3168 if (RHS->getValue().isNegative())
3169 hasNegative = true;
3170
3171 if (hasNegative) {
3172 std::vector<Constant *> Elts(VWidth);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003173 for (unsigned i = 0; i != VWidth; ++i) {
3174 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3175 if (RHS->getValue().isNegative())
3176 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
3177 else
3178 Elts[i] = RHS;
3179 }
3180 }
3181
3182 Constant *NewRHSV = ConstantVector::get(Elts);
3183 if (NewRHSV != RHSV) {
Nick Lewycky19c28922008-12-18 06:42:28 +00003184 AddUsesToWorkList(I);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003185 I.setOperand(1, NewRHSV);
3186 return &I;
3187 }
3188 }
3189 }
3190
Reid Spencer0a783f72006-11-02 01:53:59 +00003191 return 0;
3192}
3193
3194Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003195 return commonRemTransforms(I);
3196}
3197
Chris Lattner457dd822004-06-09 07:59:58 +00003198// isOneBitSet - Return true if there is exactly one bit set in the specified
3199// constant.
3200static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer5f6a8952007-03-20 00:16:52 +00003201 return CI->getValue().isPowerOf2();
Chris Lattner457dd822004-06-09 07:59:58 +00003202}
3203
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003204// isHighOnes - Return true if the constant is of the form 1+0+.
3205// This is the same as lowones(~X).
3206static bool isHighOnes(const ConstantInt *CI) {
Zhou Sheng2cde46c2007-03-20 12:49:06 +00003207 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003208}
3209
Reid Spencere4d87aa2006-12-23 06:05:41 +00003210/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003211/// are carefully arranged to allow folding of expressions such as:
3212///
3213/// (A < B) | (A > B) --> (A != B)
3214///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003215/// Note that this is only valid if the first and second predicates have the
3216/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003217///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003218/// Three bits are used to represent the condition, as follows:
3219/// 0 A > B
3220/// 1 A == B
3221/// 2 A < B
3222///
3223/// <=> Value Definition
3224/// 000 0 Always false
3225/// 001 1 A > B
3226/// 010 2 A == B
3227/// 011 3 A >= B
3228/// 100 4 A < B
3229/// 101 5 A != B
3230/// 110 6 A <= B
3231/// 111 7 Always true
3232///
3233static unsigned getICmpCode(const ICmpInst *ICI) {
3234 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003235 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00003236 case ICmpInst::ICMP_UGT: return 1; // 001
3237 case ICmpInst::ICMP_SGT: return 1; // 001
3238 case ICmpInst::ICMP_EQ: return 2; // 010
3239 case ICmpInst::ICMP_UGE: return 3; // 011
3240 case ICmpInst::ICMP_SGE: return 3; // 011
3241 case ICmpInst::ICMP_ULT: return 4; // 100
3242 case ICmpInst::ICMP_SLT: return 4; // 100
3243 case ICmpInst::ICMP_NE: return 5; // 101
3244 case ICmpInst::ICMP_ULE: return 6; // 110
3245 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003246 // True -> 7
3247 default:
Reid Spencere4d87aa2006-12-23 06:05:41 +00003248 assert(0 && "Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003249 return 0;
3250 }
3251}
3252
Evan Cheng8db90722008-10-14 17:15:11 +00003253/// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3254/// predicate into a three bit mask. It also returns whether it is an ordered
3255/// predicate by reference.
3256static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3257 isOrdered = false;
3258 switch (CC) {
3259 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
3260 case FCmpInst::FCMP_UNO: return 0; // 000
Evan Cheng4990b252008-10-14 18:13:38 +00003261 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
3262 case FCmpInst::FCMP_UGT: return 1; // 001
3263 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
3264 case FCmpInst::FCMP_UEQ: return 2; // 010
Evan Cheng8db90722008-10-14 17:15:11 +00003265 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
3266 case FCmpInst::FCMP_UGE: return 3; // 011
3267 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
3268 case FCmpInst::FCMP_ULT: return 4; // 100
Evan Cheng4990b252008-10-14 18:13:38 +00003269 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
3270 case FCmpInst::FCMP_UNE: return 5; // 101
Evan Cheng8db90722008-10-14 17:15:11 +00003271 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
3272 case FCmpInst::FCMP_ULE: return 6; // 110
Evan Cheng40300622008-10-14 18:44:08 +00003273 // True -> 7
Evan Cheng8db90722008-10-14 17:15:11 +00003274 default:
3275 // Not expecting FCMP_FALSE and FCMP_TRUE;
3276 assert(0 && "Unexpected FCmp predicate!");
3277 return 0;
3278 }
3279}
3280
Reid Spencere4d87aa2006-12-23 06:05:41 +00003281/// getICmpValue - This is the complement of getICmpCode, which turns an
3282/// opcode and two operands into either a constant true or false, or a brand
Dan Gohman5d066ff2007-09-17 17:31:57 +00003283/// new ICmp instruction. The sign is passed in to determine which kind
Evan Cheng8db90722008-10-14 17:15:11 +00003284/// of predicate to use in the new icmp instruction.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003285static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3286 switch (code) {
3287 default: assert(0 && "Illegal ICmp code!");
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003288 case 0: return ConstantInt::getFalse();
Reid Spencere4d87aa2006-12-23 06:05:41 +00003289 case 1:
3290 if (sign)
3291 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3292 else
3293 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3294 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
3295 case 3:
3296 if (sign)
3297 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3298 else
3299 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3300 case 4:
3301 if (sign)
3302 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3303 else
3304 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3305 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
3306 case 6:
3307 if (sign)
3308 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3309 else
3310 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003311 case 7: return ConstantInt::getTrue();
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003312 }
3313}
3314
Evan Cheng8db90722008-10-14 17:15:11 +00003315/// getFCmpValue - This is the complement of getFCmpCode, which turns an
3316/// opcode and two operands into either a FCmp instruction. isordered is passed
3317/// in to determine which kind of predicate to use in the new fcmp instruction.
3318static Value *getFCmpValue(bool isordered, unsigned code,
3319 Value *LHS, Value *RHS) {
3320 switch (code) {
Evan Cheng4990b252008-10-14 18:13:38 +00003321 default: assert(0 && "Illegal FCmp code!");
Evan Cheng8db90722008-10-14 17:15:11 +00003322 case 0:
3323 if (isordered)
3324 return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
3325 else
3326 return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
3327 case 1:
3328 if (isordered)
Evan Cheng8db90722008-10-14 17:15:11 +00003329 return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
3330 else
3331 return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003332 case 2:
3333 if (isordered)
3334 return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
3335 else
3336 return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003337 case 3:
3338 if (isordered)
3339 return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
3340 else
3341 return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
3342 case 4:
3343 if (isordered)
3344 return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
3345 else
3346 return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
3347 case 5:
3348 if (isordered)
Evan Cheng4990b252008-10-14 18:13:38 +00003349 return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
3350 else
3351 return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
3352 case 6:
3353 if (isordered)
Evan Cheng8db90722008-10-14 17:15:11 +00003354 return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
3355 else
3356 return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
Evan Cheng40300622008-10-14 18:44:08 +00003357 case 7: return ConstantInt::getTrue();
Evan Cheng8db90722008-10-14 17:15:11 +00003358 }
3359}
3360
Chris Lattnerb9553d62008-11-16 04:55:20 +00003361/// PredicatesFoldable - Return true if both predicates match sign or if at
3362/// least one of them is an equality comparison (which is signless).
Reid Spencere4d87aa2006-12-23 06:05:41 +00003363static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3364 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
Chris Lattnerb9553d62008-11-16 04:55:20 +00003365 (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3366 (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003367}
3368
3369namespace {
3370// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3371struct FoldICmpLogical {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003372 InstCombiner &IC;
3373 Value *LHS, *RHS;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003374 ICmpInst::Predicate pred;
3375 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3376 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3377 pred(ICI->getPredicate()) {}
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003378 bool shouldApply(Value *V) const {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003379 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3380 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003381 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3382 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003383 return false;
3384 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003385 Instruction *apply(Instruction &Log) const {
3386 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3387 if (ICI->getOperand(0) != LHS) {
3388 assert(ICI->getOperand(1) == LHS);
3389 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003390 }
3391
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003392 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003393 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003394 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003395 unsigned Code;
3396 switch (Log.getOpcode()) {
3397 case Instruction::And: Code = LHSCode & RHSCode; break;
3398 case Instruction::Or: Code = LHSCode | RHSCode; break;
3399 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner021c1902003-09-22 20:33:34 +00003400 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003401 }
3402
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003403 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3404 ICmpInst::isSignedPredicate(ICI->getPredicate());
3405
3406 Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003407 if (Instruction *I = dyn_cast<Instruction>(RV))
3408 return I;
3409 // Otherwise, it's a constant boolean value...
3410 return IC.ReplaceInstUsesWith(Log, RV);
3411 }
3412};
Chris Lattnerd23b5ba2006-11-15 04:53:24 +00003413} // end anonymous namespace
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003414
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003415// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3416// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +00003417// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003418Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003419 ConstantInt *OpRHS,
3420 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003421 BinaryOperator &TheAnd) {
3422 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00003423 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +00003424 if (!Op->isShift())
Reid Spencer7177c3a2007-03-25 05:33:51 +00003425 Together = And(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00003426
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003427 switch (Op->getOpcode()) {
3428 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003429 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003430 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003431 Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003432 InsertNewInstBefore(And, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003433 And->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003434 return BinaryOperator::CreateXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003435 }
3436 break;
3437 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003438 if (Together == AndRHS) // (X | C) & C --> C
3439 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003440
Chris Lattner6e7ba452005-01-01 16:22:27 +00003441 if (Op->hasOneUse() && Together != OpRHS) {
3442 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003443 Instruction *Or = BinaryOperator::CreateOr(X, Together);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003444 InsertNewInstBefore(Or, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003445 Or->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003446 return BinaryOperator::CreateAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003447 }
3448 break;
3449 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00003450 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003451 // Adding a one to a single bit bit-field should be turned into an XOR
3452 // of the bit. First thing to check is to see if this AND is with a
3453 // single bit constant.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003454 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003455
3456 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00003457 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003458 // Ok, at this point, we know that we are masking the result of the
3459 // ADD down to exactly one bit. If the constant we are adding has
3460 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003461 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00003462
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003463 // Check to see if any bits below the one bit set in AndRHSV are set.
3464 if ((AddRHS & (AndRHSV-1)) == 0) {
3465 // If not, the only thing that can effect the output of the AND is
3466 // the bit specified by AndRHSV. If that bit is set, the effect of
3467 // the XOR is to toggle the bit. If it is clear, then the ADD has
3468 // no effect.
3469 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3470 TheAnd.setOperand(0, X);
3471 return &TheAnd;
3472 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003473 // Pull the XOR out of the AND.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003474 Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003475 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003476 NewAnd->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003477 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003478 }
3479 }
3480 }
3481 }
3482 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00003483
3484 case Instruction::Shl: {
3485 // We know that the AND will not produce any of the bits shifted in, so if
3486 // the anded constant includes them, clear them now!
3487 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003488 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003489 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003490 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3491 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00003492
Zhou Sheng290bec52007-03-29 08:15:12 +00003493 if (CI->getValue() == ShlMask) {
3494 // Masking out bits that the shift already masks
Chris Lattner0c967662004-09-24 15:21:34 +00003495 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3496 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00003497 TheAnd.setOperand(1, CI);
3498 return &TheAnd;
3499 }
3500 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00003501 }
Reid Spencer3822ff52006-11-08 06:47:33 +00003502 case Instruction::LShr:
3503 {
Chris Lattner62a355c2003-09-19 19:05:02 +00003504 // We know that the AND will not produce any of the bits shifted in, so if
3505 // the anded constant includes them, clear them now! This only applies to
3506 // unsigned shifts, because a signed shr may bring in set bits!
3507 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003508 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003509 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003510 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3511 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00003512
Zhou Sheng290bec52007-03-29 08:15:12 +00003513 if (CI->getValue() == ShrMask) {
3514 // Masking out bits that the shift already masks.
Reid Spencer3822ff52006-11-08 06:47:33 +00003515 return ReplaceInstUsesWith(TheAnd, Op);
3516 } else if (CI != AndRHS) {
3517 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3518 return &TheAnd;
3519 }
3520 break;
3521 }
3522 case Instruction::AShr:
3523 // Signed shr.
3524 // See if this is shifting in some sign extension, then masking it out
3525 // with an and.
3526 if (Op->hasOneUse()) {
Zhou Sheng290bec52007-03-29 08:15:12 +00003527 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003528 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003529 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3530 Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
Reid Spencer7eb76382006-12-13 17:19:09 +00003531 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +00003532 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +00003533 // Make the argument unsigned.
3534 Value *ShVal = Op->getOperand(0);
Reid Spencer832254e2007-02-02 02:16:23 +00003535 ShVal = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003536 BinaryOperator::CreateLShr(ShVal, OpRHS,
Reid Spencer832254e2007-02-02 02:16:23 +00003537 Op->getName()), TheAnd);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003538 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00003539 }
Chris Lattner62a355c2003-09-19 19:05:02 +00003540 }
3541 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003542 }
3543 return 0;
3544}
3545
Chris Lattner8b170942002-08-09 23:47:40 +00003546
Chris Lattnera96879a2004-09-29 17:40:11 +00003547/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3548/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +00003549/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3550/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +00003551/// insert new instructions.
3552Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003553 bool isSigned, bool Inside,
3554 Instruction &IB) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003555 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +00003556 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +00003557 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003558
Chris Lattnera96879a2004-09-29 17:40:11 +00003559 if (Inside) {
3560 if (Lo == Hi) // Trivially false.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003561 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +00003562
Reid Spencere4d87aa2006-12-23 06:05:41 +00003563 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003564 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4e40032007-03-21 23:19:50 +00003565 ICmpInst::Predicate pred = (isSigned ?
Reid Spencere4d87aa2006-12-23 06:05:41 +00003566 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3567 return new ICmpInst(pred, V, Hi);
3568 }
3569
3570 // Emit V-Lo <u Hi-Lo
3571 Constant *NegLo = ConstantExpr::getNeg(Lo);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003572 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003573 InsertNewInstBefore(Add, IB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003574 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3575 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003576 }
3577
3578 if (Lo == Hi) // Trivially true.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003579 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +00003580
Reid Spencere4e40032007-03-21 23:19:50 +00003581 // V < Min || V >= Hi -> V > Hi-1
Chris Lattnera96879a2004-09-29 17:40:11 +00003582 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003583 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003584 ICmpInst::Predicate pred = (isSigned ?
3585 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3586 return new ICmpInst(pred, V, Hi);
3587 }
Reid Spencerb83eb642006-10-20 07:07:24 +00003588
Reid Spencere4e40032007-03-21 23:19:50 +00003589 // Emit V-Lo >u Hi-1-Lo
3590 // Note that Hi has already had one subtracted from it, above.
3591 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003592 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003593 InsertNewInstBefore(Add, IB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003594 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3595 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003596}
3597
Chris Lattner7203e152005-09-18 07:22:02 +00003598// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3599// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3600// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3601// not, since all 1s are not contiguous.
Zhou Sheng4351c642007-04-02 08:20:41 +00003602static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003603 const APInt& V = Val->getValue();
Reid Spencerf2442522007-03-24 00:42:08 +00003604 uint32_t BitWidth = Val->getType()->getBitWidth();
3605 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattner7203e152005-09-18 07:22:02 +00003606
3607 // look for the first zero bit after the run of ones
Reid Spencerf2442522007-03-24 00:42:08 +00003608 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattner7203e152005-09-18 07:22:02 +00003609 // look for the first non-zero bit
Reid Spencerf2442522007-03-24 00:42:08 +00003610 ME = V.getActiveBits();
Chris Lattner7203e152005-09-18 07:22:02 +00003611 return true;
3612}
3613
Chris Lattner7203e152005-09-18 07:22:02 +00003614/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3615/// where isSub determines whether the operator is a sub. If we can fold one of
3616/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00003617///
3618/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3619/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3620/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3621///
3622/// return (A +/- B).
3623///
3624Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003625 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +00003626 Instruction &I) {
3627 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3628 if (!LHSI || LHSI->getNumOperands() != 2 ||
3629 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3630
3631 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3632
3633 switch (LHSI->getOpcode()) {
3634 default: return 0;
3635 case Instruction::And:
Reid Spencer7177c3a2007-03-25 05:33:51 +00003636 if (And(N, Mask) == Mask) {
Chris Lattner7203e152005-09-18 07:22:02 +00003637 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Sheng00f436c2007-03-24 15:34:37 +00003638 if ((Mask->getValue().countLeadingZeros() +
3639 Mask->getValue().countPopulation()) ==
3640 Mask->getValue().getBitWidth())
Chris Lattner7203e152005-09-18 07:22:02 +00003641 break;
3642
3643 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3644 // part, we don't need any explicit masks to take them out of A. If that
3645 // is all N is, ignore it.
Zhou Sheng4351c642007-04-02 08:20:41 +00003646 uint32_t MB = 0, ME = 0;
Chris Lattner7203e152005-09-18 07:22:02 +00003647 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerb35ae032007-03-23 18:46:34 +00003648 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Sheng290bec52007-03-29 08:15:12 +00003649 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattner3bedbd92006-02-07 07:27:52 +00003650 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00003651 break;
3652 }
3653 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00003654 return 0;
3655 case Instruction::Or:
3656 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00003657 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Sheng00f436c2007-03-24 15:34:37 +00003658 if ((Mask->getValue().countLeadingZeros() +
3659 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Reid Spencer6eb0d992007-03-26 23:58:26 +00003660 && And(N, Mask)->isZero())
Chris Lattnerc8e77562005-09-18 04:24:45 +00003661 break;
3662 return 0;
3663 }
3664
3665 Instruction *New;
3666 if (isSub)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003667 New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00003668 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003669 New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00003670 return InsertNewInstBefore(New, I);
3671}
3672
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003673/// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3674Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3675 ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattnerea065fb2008-11-16 05:10:52 +00003676 Value *Val, *Val2;
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003677 ConstantInt *LHSCst, *RHSCst;
3678 ICmpInst::Predicate LHSCC, RHSCC;
3679
Chris Lattnerea065fb2008-11-16 05:10:52 +00003680 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003681 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) ||
Chris Lattnerea065fb2008-11-16 05:10:52 +00003682 !match(RHS, m_ICmp(RHSCC, m_Value(Val2), m_ConstantInt(RHSCst))))
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003683 return 0;
Chris Lattnerea065fb2008-11-16 05:10:52 +00003684
3685 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3686 // where C is a power of 2
3687 if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3688 LHSCst->getValue().isPowerOf2()) {
3689 Instruction *NewOr = BinaryOperator::CreateOr(Val, Val2);
3690 InsertNewInstBefore(NewOr, I);
3691 return new ICmpInst(LHSCC, NewOr, LHSCst);
3692 }
3693
3694 // From here on, we only handle:
3695 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3696 if (Val != Val2) return 0;
3697
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003698 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3699 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3700 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3701 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3702 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3703 return 0;
3704
3705 // We can't fold (ugt x, C) & (sgt x, C2).
3706 if (!PredicatesFoldable(LHSCC, RHSCC))
3707 return 0;
3708
3709 // Ensure that the larger constant is on the RHS.
Chris Lattneraa3e1572008-11-16 05:14:43 +00003710 bool ShouldSwap;
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003711 if (ICmpInst::isSignedPredicate(LHSCC) ||
3712 (ICmpInst::isEquality(LHSCC) &&
3713 ICmpInst::isSignedPredicate(RHSCC)))
Chris Lattneraa3e1572008-11-16 05:14:43 +00003714 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003715 else
Chris Lattneraa3e1572008-11-16 05:14:43 +00003716 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3717
3718 if (ShouldSwap) {
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003719 std::swap(LHS, RHS);
3720 std::swap(LHSCst, RHSCst);
3721 std::swap(LHSCC, RHSCC);
3722 }
3723
3724 // At this point, we know we have have two icmp instructions
3725 // comparing a value against two constants and and'ing the result
3726 // together. Because of the above check, we know that we only have
3727 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3728 // (from the FoldICmpLogical check above), that the two constants
3729 // are not equal and that the larger constant is on the RHS
3730 assert(LHSCst != RHSCst && "Compares not folded above?");
3731
3732 switch (LHSCC) {
3733 default: assert(0 && "Unknown integer condition code!");
3734 case ICmpInst::ICMP_EQ:
3735 switch (RHSCC) {
3736 default: assert(0 && "Unknown integer condition code!");
3737 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3738 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3739 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
3740 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3741 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3742 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3743 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
3744 return ReplaceInstUsesWith(I, LHS);
3745 }
3746 case ICmpInst::ICMP_NE:
3747 switch (RHSCC) {
3748 default: assert(0 && "Unknown integer condition code!");
3749 case ICmpInst::ICMP_ULT:
3750 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3751 return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
3752 break; // (X != 13 & X u< 15) -> no change
3753 case ICmpInst::ICMP_SLT:
3754 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3755 return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
3756 break; // (X != 13 & X s< 15) -> no change
3757 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3758 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3759 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
3760 return ReplaceInstUsesWith(I, RHS);
3761 case ICmpInst::ICMP_NE:
3762 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3763 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3764 Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
3765 Val->getName()+".off");
3766 InsertNewInstBefore(Add, I);
3767 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3768 ConstantInt::get(Add->getType(), 1));
3769 }
3770 break; // (X != 13 & X != 15) -> no change
3771 }
3772 break;
3773 case ICmpInst::ICMP_ULT:
3774 switch (RHSCC) {
3775 default: assert(0 && "Unknown integer condition code!");
3776 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3777 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
3778 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3779 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3780 break;
3781 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3782 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
3783 return ReplaceInstUsesWith(I, LHS);
3784 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3785 break;
3786 }
3787 break;
3788 case ICmpInst::ICMP_SLT:
3789 switch (RHSCC) {
3790 default: assert(0 && "Unknown integer condition code!");
3791 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3792 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
3793 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3794 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3795 break;
3796 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3797 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
3798 return ReplaceInstUsesWith(I, LHS);
3799 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3800 break;
3801 }
3802 break;
3803 case ICmpInst::ICMP_UGT:
3804 switch (RHSCC) {
3805 default: assert(0 && "Unknown integer condition code!");
3806 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
3807 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3808 return ReplaceInstUsesWith(I, RHS);
3809 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3810 break;
3811 case ICmpInst::ICMP_NE:
3812 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3813 return new ICmpInst(LHSCC, Val, RHSCst);
3814 break; // (X u> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00003815 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003816 return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, false, true, I);
3817 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3818 break;
3819 }
3820 break;
3821 case ICmpInst::ICMP_SGT:
3822 switch (RHSCC) {
3823 default: assert(0 && "Unknown integer condition code!");
3824 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
3825 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3826 return ReplaceInstUsesWith(I, RHS);
3827 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3828 break;
3829 case ICmpInst::ICMP_NE:
3830 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3831 return new ICmpInst(LHSCC, Val, RHSCst);
3832 break; // (X s> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00003833 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003834 return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, true, true, I);
3835 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3836 break;
3837 }
3838 break;
3839 }
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003840
3841 return 0;
3842}
3843
3844
Chris Lattner7e708292002-06-25 16:13:24 +00003845Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003846 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00003847 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003848
Chris Lattnere87597f2004-10-16 18:11:37 +00003849 if (isa<UndefValue>(Op1)) // X & undef -> 0
3850 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3851
Chris Lattner6e7ba452005-01-01 16:22:27 +00003852 // and X, X = X
3853 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00003854 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003855
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003856 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00003857 // purpose is to compute bits we don't care about.
Reid Spencer9d6565a2007-02-15 02:26:10 +00003858 if (!isa<VectorType>(I.getType())) {
Chris Lattner886ab6c2009-01-31 08:15:18 +00003859 if (SimplifyDemandedInstructionBits(I))
Reid Spencer6eb0d992007-03-26 23:58:26 +00003860 return &I;
Chris Lattner696ee0a2007-01-18 22:16:33 +00003861 } else {
Reid Spencer9d6565a2007-02-15 02:26:10 +00003862 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
Chris Lattner041a6c92007-06-15 05:26:55 +00003863 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
Chris Lattner696ee0a2007-01-18 22:16:33 +00003864 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner041a6c92007-06-15 05:26:55 +00003865 } else if (isa<ConstantAggregateZero>(Op1)) {
3866 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
Chris Lattner696ee0a2007-01-18 22:16:33 +00003867 }
3868 }
Chris Lattner9ca96412006-02-08 03:25:32 +00003869
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003870 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003871 const APInt& AndRHSMask = AndRHS->getValue();
3872 APInt NotAndRHS(~AndRHSMask);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003873
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003874 // Optimize a variety of ((val OP C1) & C2) combinations...
Reid Spencer832254e2007-02-02 02:16:23 +00003875 if (isa<BinaryOperator>(Op0)) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003876 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003877 Value *Op0LHS = Op0I->getOperand(0);
3878 Value *Op0RHS = Op0I->getOperand(1);
3879 switch (Op0I->getOpcode()) {
3880 case Instruction::Xor:
3881 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00003882 // If the mask is only needed on one incoming arm, push it up.
3883 if (Op0I->hasOneUse()) {
3884 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3885 // Not masking anything out for the LHS, move to RHS.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003886 Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
Chris Lattnerad1e3022005-01-23 20:26:55 +00003887 Op0RHS->getName()+".masked");
3888 InsertNewInstBefore(NewRHS, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003889 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00003890 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003891 }
Chris Lattner3bedbd92006-02-07 07:27:52 +00003892 if (!isa<Constant>(Op0RHS) &&
Chris Lattnerad1e3022005-01-23 20:26:55 +00003893 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3894 // Not masking anything out for the RHS, move to LHS.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003895 Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
Chris Lattnerad1e3022005-01-23 20:26:55 +00003896 Op0LHS->getName()+".masked");
3897 InsertNewInstBefore(NewLHS, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003898 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00003899 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3900 }
3901 }
3902
Chris Lattner6e7ba452005-01-01 16:22:27 +00003903 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00003904 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00003905 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3906 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3907 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3908 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003909 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattner7203e152005-09-18 07:22:02 +00003910 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003911 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00003912 break;
3913
3914 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00003915 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3916 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3917 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3918 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003919 return BinaryOperator::CreateAnd(V, AndRHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00003920
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00003921 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
3922 // has 1's for all bits that the subtraction with A might affect.
3923 if (Op0I->hasOneUse()) {
3924 uint32_t BitWidth = AndRHSMask.getBitWidth();
3925 uint32_t Zeros = AndRHSMask.countLeadingZeros();
3926 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
3927
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00003928 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00003929 if (!(A && A->isZero()) && // avoid infinite recursion.
3930 MaskedValueIsZero(Op0LHS, Mask)) {
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00003931 Instruction *NewNeg = BinaryOperator::CreateNeg(Op0RHS);
3932 InsertNewInstBefore(NewNeg, I);
3933 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
3934 }
3935 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00003936 break;
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00003937
3938 case Instruction::Shl:
3939 case Instruction::LShr:
3940 // (1 << x) & 1 --> zext(x == 0)
3941 // (1 >> x) & 1 --> zext(x == 0)
Nick Lewyckyd8ad4922008-07-09 07:35:26 +00003942 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00003943 Instruction *NewICmp = new ICmpInst(ICmpInst::ICMP_EQ, Op0RHS,
3944 Constant::getNullValue(I.getType()));
3945 InsertNewInstBefore(NewICmp, I);
3946 return new ZExtInst(NewICmp, I.getType());
3947 }
3948 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00003949 }
3950
Chris Lattner58403262003-07-23 19:25:52 +00003951 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003952 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003953 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00003954 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00003955 // If this is an integer truncation or change from signed-to-unsigned, and
3956 // if the source is an and/or with immediate, transform it. This
3957 // frequently occurs for bitfield accesses.
3958 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00003959 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00003960 CastOp->getNumOperands() == 2)
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003961 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
Chris Lattner2b83af22005-08-07 07:03:10 +00003962 if (CastOp->getOpcode() == Instruction::And) {
3963 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00003964 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
3965 // This will fold the two constants together, which may allow
3966 // other simplifications.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003967 Instruction *NewCast = CastInst::CreateTruncOrBitCast(
Reid Spencerd977d862006-12-12 23:36:14 +00003968 CastOp->getOperand(0), I.getType(),
3969 CastOp->getName()+".shrunk");
Chris Lattner2b83af22005-08-07 07:03:10 +00003970 NewCast = InsertNewInstBefore(NewCast, I);
Reid Spencer3da59db2006-11-27 01:05:10 +00003971 // trunc_or_bitcast(C1)&C2
Reid Spencerd977d862006-12-12 23:36:14 +00003972 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00003973 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003974 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner2b83af22005-08-07 07:03:10 +00003975 } else if (CastOp->getOpcode() == Instruction::Or) {
3976 // Change: and (cast (or X, C1) to T), C2
3977 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattnerbb4e7b22006-12-12 19:11:20 +00003978 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Chris Lattner2b83af22005-08-07 07:03:10 +00003979 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3980 return ReplaceInstUsesWith(I, AndRHS);
3981 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003982 }
Chris Lattner2b83af22005-08-07 07:03:10 +00003983 }
Chris Lattner06782f82003-07-23 19:36:21 +00003984 }
Chris Lattner2eefe512004-04-09 19:05:30 +00003985
3986 // Try to fold constant and into select arguments.
3987 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003988 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00003989 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00003990 if (isa<PHINode>(Op0))
3991 if (Instruction *NV = FoldOpIntoPhi(I))
3992 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00003993 }
3994
Chris Lattner8d969642003-03-10 23:06:50 +00003995 Value *Op0NotVal = dyn_castNotVal(Op0);
3996 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00003997
Chris Lattner5b62aa72004-06-18 06:07:51 +00003998 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3999 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4000
Misha Brukmancb6267b2004-07-30 12:50:08 +00004001 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00004002 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004003 Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
Chris Lattner48595f12004-06-10 02:07:29 +00004004 I.getName()+".demorgan");
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00004005 InsertNewInstBefore(Or, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004006 return BinaryOperator::CreateNot(Or);
Chris Lattnera2881962003-02-18 19:28:33 +00004007 }
Chris Lattner2082ad92006-02-13 23:07:23 +00004008
4009 {
Chris Lattner003b6202007-06-15 05:58:24 +00004010 Value *A = 0, *B = 0, *C = 0, *D = 0;
4011 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00004012 if (A == Op1 || B == Op1) // (A | ?) & A --> A
4013 return ReplaceInstUsesWith(I, Op1);
Chris Lattner003b6202007-06-15 05:58:24 +00004014
4015 // (A|B) & ~(A&B) -> A^B
4016 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
4017 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004018 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004019 }
4020 }
4021
4022 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00004023 if (A == Op0 || B == Op0) // A & (A | ?) --> A
4024 return ReplaceInstUsesWith(I, Op0);
Chris Lattner003b6202007-06-15 05:58:24 +00004025
4026 // ~(A&B) & (A|B) -> A^B
4027 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
4028 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004029 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004030 }
4031 }
Chris Lattner64daab52006-04-01 08:03:55 +00004032
4033 if (Op0->hasOneUse() &&
4034 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
4035 if (A == Op1) { // (A^B)&A -> A&(A^B)
4036 I.swapOperands(); // Simplify below
4037 std::swap(Op0, Op1);
4038 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
4039 cast<BinaryOperator>(Op0)->swapOperands();
4040 I.swapOperands(); // Simplify below
4041 std::swap(Op0, Op1);
4042 }
4043 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004044
Chris Lattner64daab52006-04-01 08:03:55 +00004045 if (Op1->hasOneUse() &&
4046 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
4047 if (B == Op0) { // B&(A^B) -> B&(B^A)
4048 cast<BinaryOperator>(Op1)->swapOperands();
4049 std::swap(A, B);
4050 }
4051 if (A == Op0) { // A&(A^B) -> A & ~B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004052 Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
Chris Lattner64daab52006-04-01 08:03:55 +00004053 InsertNewInstBefore(NotB, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004054 return BinaryOperator::CreateAnd(A, NotB);
Chris Lattner64daab52006-04-01 08:03:55 +00004055 }
4056 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004057
4058 // (A&((~A)|B)) -> A&B
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00004059 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
4060 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
4061 return BinaryOperator::CreateAnd(A, Op1);
4062 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
4063 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
4064 return BinaryOperator::CreateAnd(A, Op0);
Chris Lattner2082ad92006-02-13 23:07:23 +00004065 }
4066
Reid Spencere4d87aa2006-12-23 06:05:41 +00004067 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4068 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
4069 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004070 return R;
4071
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004072 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4073 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4074 return Res;
Chris Lattner955f3312004-09-28 21:48:02 +00004075 }
4076
Chris Lattner6fc205f2006-05-05 06:39:07 +00004077 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004078 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4079 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4080 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4081 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00004082 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004083 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004084 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4085 I.getType(), TD) &&
4086 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4087 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004088 Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004089 Op1C->getOperand(0),
4090 I.getName());
4091 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004092 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004093 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004094 }
Chris Lattnere511b742006-11-14 07:46:50 +00004095
4096 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004097 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4098 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4099 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004100 SI0->getOperand(1) == SI1->getOperand(1) &&
4101 (SI0->hasOneUse() || SI1->hasOneUse())) {
4102 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004103 InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
Chris Lattnere511b742006-11-14 07:46:50 +00004104 SI1->getOperand(0),
4105 SI0->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004106 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004107 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004108 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004109 }
4110
Evan Cheng8db90722008-10-14 17:15:11 +00004111 // If and'ing two fcmp, try combine them into one.
Chris Lattner99c65742007-10-24 05:38:08 +00004112 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4113 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4114 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
Evan Cheng8db90722008-10-14 17:15:11 +00004115 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
4116 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
Chris Lattner99c65742007-10-24 05:38:08 +00004117 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4118 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4119 // If either of the constants are nans, then the whole thing returns
4120 // false.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00004121 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner99c65742007-10-24 05:38:08 +00004122 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4123 return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
4124 RHS->getOperand(0));
4125 }
Evan Cheng8db90722008-10-14 17:15:11 +00004126 } else {
4127 Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4128 FCmpInst::Predicate Op0CC, Op1CC;
4129 if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS), m_Value(Op0RHS))) &&
4130 match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS), m_Value(Op1RHS)))) {
Evan Cheng4990b252008-10-14 18:13:38 +00004131 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4132 // Swap RHS operands to match LHS.
4133 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4134 std::swap(Op1LHS, Op1RHS);
4135 }
Evan Cheng8db90722008-10-14 17:15:11 +00004136 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4137 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4138 if (Op0CC == Op1CC)
4139 return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
4140 else if (Op0CC == FCmpInst::FCMP_FALSE ||
4141 Op1CC == FCmpInst::FCMP_FALSE)
4142 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4143 else if (Op0CC == FCmpInst::FCMP_TRUE)
4144 return ReplaceInstUsesWith(I, Op1);
4145 else if (Op1CC == FCmpInst::FCMP_TRUE)
4146 return ReplaceInstUsesWith(I, Op0);
4147 bool Op0Ordered;
4148 bool Op1Ordered;
4149 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4150 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4151 if (Op1Pred == 0) {
4152 std::swap(Op0, Op1);
4153 std::swap(Op0Pred, Op1Pred);
4154 std::swap(Op0Ordered, Op1Ordered);
4155 }
4156 if (Op0Pred == 0) {
4157 // uno && ueq -> uno && (uno || eq) -> ueq
4158 // ord && olt -> ord && (ord && lt) -> olt
4159 if (Op0Ordered == Op1Ordered)
4160 return ReplaceInstUsesWith(I, Op1);
4161 // uno && oeq -> uno && (ord && eq) -> false
4162 // uno && ord -> false
4163 if (!Op0Ordered)
4164 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4165 // ord && ueq -> ord && (uno || eq) -> oeq
4166 return cast<Instruction>(getFCmpValue(true, Op1Pred,
4167 Op0LHS, Op0RHS));
4168 }
4169 }
4170 }
4171 }
Chris Lattner99c65742007-10-24 05:38:08 +00004172 }
4173 }
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004174
Chris Lattner7e708292002-06-25 16:13:24 +00004175 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004176}
4177
Chris Lattner8c34cd22008-10-05 02:13:19 +00004178/// CollectBSwapParts - Analyze the specified subexpression and see if it is
4179/// capable of providing pieces of a bswap. The subexpression provides pieces
4180/// of a bswap if it is proven that each of the non-zero bytes in the output of
4181/// the expression came from the corresponding "byte swapped" byte in some other
4182/// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
4183/// we know that the expression deposits the low byte of %X into the high byte
4184/// of the bswap result and that all other bytes are zero. This expression is
4185/// accepted, the high byte of ByteValues is set to X to indicate a correct
4186/// match.
4187///
4188/// This function returns true if the match was unsuccessful and false if so.
4189/// On entry to the function the "OverallLeftShift" is a signed integer value
4190/// indicating the number of bytes that the subexpression is later shifted. For
4191/// example, if the expression is later right shifted by 16 bits, the
4192/// OverallLeftShift value would be -2 on entry. This is used to specify which
4193/// byte of ByteValues is actually being set.
4194///
4195/// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4196/// byte is masked to zero by a user. For example, in (X & 255), X will be
4197/// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
4198/// this function to working on up to 32-byte (256 bit) values. ByteMask is
4199/// always in the local (OverallLeftShift) coordinate space.
4200///
4201static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4202 SmallVector<Value*, 8> &ByteValues) {
4203 if (Instruction *I = dyn_cast<Instruction>(V)) {
4204 // If this is an or instruction, it may be an inner node of the bswap.
4205 if (I->getOpcode() == Instruction::Or) {
4206 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4207 ByteValues) ||
4208 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4209 ByteValues);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004210 }
Chris Lattner8c34cd22008-10-05 02:13:19 +00004211
4212 // If this is a logical shift by a constant multiple of 8, recurse with
4213 // OverallLeftShift and ByteMask adjusted.
4214 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4215 unsigned ShAmt =
4216 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4217 // Ensure the shift amount is defined and of a byte value.
4218 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4219 return true;
4220
4221 unsigned ByteShift = ShAmt >> 3;
4222 if (I->getOpcode() == Instruction::Shl) {
4223 // X << 2 -> collect(X, +2)
4224 OverallLeftShift += ByteShift;
4225 ByteMask >>= ByteShift;
4226 } else {
4227 // X >>u 2 -> collect(X, -2)
4228 OverallLeftShift -= ByteShift;
4229 ByteMask <<= ByteShift;
Chris Lattnerde17ddc2008-10-08 06:42:28 +00004230 ByteMask &= (~0U >> (32-ByteValues.size()));
Chris Lattner8c34cd22008-10-05 02:13:19 +00004231 }
4232
4233 if (OverallLeftShift >= (int)ByteValues.size()) return true;
4234 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4235
4236 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4237 ByteValues);
4238 }
4239
4240 // If this is a logical 'and' with a mask that clears bytes, clear the
4241 // corresponding bytes in ByteMask.
4242 if (I->getOpcode() == Instruction::And &&
4243 isa<ConstantInt>(I->getOperand(1))) {
4244 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4245 unsigned NumBytes = ByteValues.size();
4246 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4247 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4248
4249 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4250 // If this byte is masked out by a later operation, we don't care what
4251 // the and mask is.
4252 if ((ByteMask & (1 << i)) == 0)
4253 continue;
4254
4255 // If the AndMask is all zeros for this byte, clear the bit.
4256 APInt MaskB = AndMask & Byte;
4257 if (MaskB == 0) {
4258 ByteMask &= ~(1U << i);
4259 continue;
4260 }
4261
4262 // If the AndMask is not all ones for this byte, it's not a bytezap.
4263 if (MaskB != Byte)
4264 return true;
4265
4266 // Otherwise, this byte is kept.
4267 }
4268
4269 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4270 ByteValues);
4271 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004272 }
4273
Chris Lattner8c34cd22008-10-05 02:13:19 +00004274 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
4275 // the input value to the bswap. Some observations: 1) if more than one byte
4276 // is demanded from this input, then it could not be successfully assembled
4277 // into a byteswap. At least one of the two bytes would not be aligned with
4278 // their ultimate destination.
4279 if (!isPowerOf2_32(ByteMask)) return true;
4280 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004281
Chris Lattner8c34cd22008-10-05 02:13:19 +00004282 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4283 // is demanded, it needs to go into byte 0 of the result. This means that the
4284 // byte needs to be shifted until it lands in the right byte bucket. The
4285 // shift amount depends on the position: if the byte is coming from the high
4286 // part of the value (e.g. byte 3) then it must be shifted right. If from the
4287 // low part, it must be shifted left.
4288 unsigned DestByteNo = InputByteNo + OverallLeftShift;
4289 if (InputByteNo < ByteValues.size()/2) {
4290 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4291 return true;
4292 } else {
4293 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4294 return true;
4295 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004296
4297 // If the destination byte value is already defined, the values are or'd
4298 // together, which isn't a bswap (unless it's an or of the same bits).
Chris Lattner8c34cd22008-10-05 02:13:19 +00004299 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
Chris Lattnerafe91a52006-06-15 19:07:26 +00004300 return true;
Chris Lattner8c34cd22008-10-05 02:13:19 +00004301 ByteValues[DestByteNo] = V;
Chris Lattnerafe91a52006-06-15 19:07:26 +00004302 return false;
4303}
4304
4305/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4306/// If so, insert the new bswap intrinsic and return it.
4307Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattner55fc8c42007-04-01 20:57:36 +00004308 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
Chris Lattner8c34cd22008-10-05 02:13:19 +00004309 if (!ITy || ITy->getBitWidth() % 16 ||
4310 // ByteMask only allows up to 32-byte values.
4311 ITy->getBitWidth() > 32*8)
Chris Lattner55fc8c42007-04-01 20:57:36 +00004312 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004313
4314 /// ByteValues - For each byte of the result, we keep track of which value
4315 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00004316 SmallVector<Value*, 8> ByteValues;
Chris Lattner55fc8c42007-04-01 20:57:36 +00004317 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004318
4319 // Try to find all the pieces corresponding to the bswap.
Chris Lattner8c34cd22008-10-05 02:13:19 +00004320 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4321 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
Chris Lattnerafe91a52006-06-15 19:07:26 +00004322 return 0;
4323
4324 // Check to see if all of the bytes come from the same value.
4325 Value *V = ByteValues[0];
4326 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4327
4328 // Check to make sure that all of the bytes come from the same value.
4329 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4330 if (ByteValues[i] != V)
4331 return 0;
Chandler Carruth69940402007-08-04 01:51:18 +00004332 const Type *Tys[] = { ITy };
Chris Lattnerafe91a52006-06-15 19:07:26 +00004333 Module *M = I.getParent()->getParent()->getParent();
Chandler Carruth69940402007-08-04 01:51:18 +00004334 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greif051a9502008-04-06 20:25:17 +00004335 return CallInst::Create(F, V);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004336}
4337
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004338/// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
4339/// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4340/// we can simplify this expression to "cond ? C : D or B".
4341static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
4342 Value *C, Value *D) {
Chris Lattnera6a474d2008-11-16 04:26:55 +00004343 // If A is not a select of -1/0, this cannot match.
Chris Lattner6046fb72008-11-16 04:46:19 +00004344 Value *Cond = 0;
Chris Lattner159c35b2009-01-05 23:53:12 +00004345 if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004346 return 0;
4347
Chris Lattnera6a474d2008-11-16 04:26:55 +00004348 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
Chris Lattner159c35b2009-01-05 23:53:12 +00004349 if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004350 return SelectInst::Create(Cond, C, B);
Chris Lattner159c35b2009-01-05 23:53:12 +00004351 if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004352 return SelectInst::Create(Cond, C, B);
4353 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
Chris Lattner159c35b2009-01-05 23:53:12 +00004354 if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004355 return SelectInst::Create(Cond, C, D);
Chris Lattner159c35b2009-01-05 23:53:12 +00004356 if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004357 return SelectInst::Create(Cond, C, D);
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004358 return 0;
4359}
Chris Lattnerafe91a52006-06-15 19:07:26 +00004360
Chris Lattner69d4ced2008-11-16 05:20:07 +00004361/// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4362Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4363 ICmpInst *LHS, ICmpInst *RHS) {
4364 Value *Val, *Val2;
4365 ConstantInt *LHSCst, *RHSCst;
4366 ICmpInst::Predicate LHSCC, RHSCC;
4367
4368 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
4369 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) ||
4370 !match(RHS, m_ICmp(RHSCC, m_Value(Val2), m_ConstantInt(RHSCst))))
4371 return 0;
4372
4373 // From here on, we only handle:
4374 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4375 if (Val != Val2) return 0;
4376
4377 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4378 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4379 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4380 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4381 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4382 return 0;
4383
4384 // We can't fold (ugt x, C) | (sgt x, C2).
4385 if (!PredicatesFoldable(LHSCC, RHSCC))
4386 return 0;
4387
4388 // Ensure that the larger constant is on the RHS.
4389 bool ShouldSwap;
4390 if (ICmpInst::isSignedPredicate(LHSCC) ||
4391 (ICmpInst::isEquality(LHSCC) &&
4392 ICmpInst::isSignedPredicate(RHSCC)))
4393 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4394 else
4395 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4396
4397 if (ShouldSwap) {
4398 std::swap(LHS, RHS);
4399 std::swap(LHSCst, RHSCst);
4400 std::swap(LHSCC, RHSCC);
4401 }
4402
4403 // At this point, we know we have have two icmp instructions
4404 // comparing a value against two constants and or'ing the result
4405 // together. Because of the above check, we know that we only have
4406 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4407 // FoldICmpLogical check above), that the two constants are not
4408 // equal.
4409 assert(LHSCst != RHSCst && "Compares not folded above?");
4410
4411 switch (LHSCC) {
4412 default: assert(0 && "Unknown integer condition code!");
4413 case ICmpInst::ICMP_EQ:
4414 switch (RHSCC) {
4415 default: assert(0 && "Unknown integer condition code!");
4416 case ICmpInst::ICMP_EQ:
4417 if (LHSCst == SubOne(RHSCst)) { // (X == 13 | X == 14) -> X-13 <u 2
4418 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4419 Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
4420 Val->getName()+".off");
4421 InsertNewInstBefore(Add, I);
4422 AddCST = Subtract(AddOne(RHSCst), LHSCst);
4423 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4424 }
4425 break; // (X == 13 | X == 15) -> no change
4426 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4427 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4428 break;
4429 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4430 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4431 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4432 return ReplaceInstUsesWith(I, RHS);
4433 }
4434 break;
4435 case ICmpInst::ICMP_NE:
4436 switch (RHSCC) {
4437 default: assert(0 && "Unknown integer condition code!");
4438 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4439 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4440 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4441 return ReplaceInstUsesWith(I, LHS);
4442 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4443 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4444 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
4445 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4446 }
4447 break;
4448 case ICmpInst::ICMP_ULT:
4449 switch (RHSCC) {
4450 default: assert(0 && "Unknown integer condition code!");
4451 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4452 break;
4453 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
4454 // If RHSCst is [us]MAXINT, it is always false. Not handling
4455 // this can cause overflow.
4456 if (RHSCst->isMaxValue(false))
4457 return ReplaceInstUsesWith(I, LHS);
4458 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), false, false, I);
4459 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4460 break;
4461 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4462 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4463 return ReplaceInstUsesWith(I, RHS);
4464 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4465 break;
4466 }
4467 break;
4468 case ICmpInst::ICMP_SLT:
4469 switch (RHSCC) {
4470 default: assert(0 && "Unknown integer condition code!");
4471 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4472 break;
4473 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
4474 // If RHSCst is [us]MAXINT, it is always false. Not handling
4475 // this can cause overflow.
4476 if (RHSCst->isMaxValue(true))
4477 return ReplaceInstUsesWith(I, LHS);
4478 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), true, false, I);
4479 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4480 break;
4481 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4482 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4483 return ReplaceInstUsesWith(I, RHS);
4484 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4485 break;
4486 }
4487 break;
4488 case ICmpInst::ICMP_UGT:
4489 switch (RHSCC) {
4490 default: assert(0 && "Unknown integer condition code!");
4491 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4492 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4493 return ReplaceInstUsesWith(I, LHS);
4494 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4495 break;
4496 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4497 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
4498 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4499 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4500 break;
4501 }
4502 break;
4503 case ICmpInst::ICMP_SGT:
4504 switch (RHSCC) {
4505 default: assert(0 && "Unknown integer condition code!");
4506 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4507 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4508 return ReplaceInstUsesWith(I, LHS);
4509 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4510 break;
4511 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4512 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
4513 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4514 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4515 break;
4516 }
4517 break;
4518 }
4519 return 0;
4520}
4521
Bill Wendlinga698a472008-12-01 08:23:25 +00004522/// FoldOrWithConstants - This helper function folds:
4523///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004524/// ((A | B) & C1) | (B & C2)
Bill Wendlinga698a472008-12-01 08:23:25 +00004525///
4526/// into:
4527///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004528/// (A & C1) | B
Bill Wendlingd54d8602008-12-01 08:32:40 +00004529///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004530/// when the XOR of the two constants is "all ones" (-1).
Bill Wendlingd54d8602008-12-01 08:32:40 +00004531Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +00004532 Value *A, Value *B, Value *C) {
Bill Wendlingdda74e02008-12-02 05:06:43 +00004533 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4534 if (!CI1) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00004535
Bill Wendling286a0542008-12-02 06:24:20 +00004536 Value *V1 = 0;
4537 ConstantInt *CI2 = 0;
4538 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00004539
Bill Wendling29976b92008-12-02 06:18:11 +00004540 APInt Xor = CI1->getValue() ^ CI2->getValue();
4541 if (!Xor.isAllOnesValue()) return 0;
4542
Bill Wendling286a0542008-12-02 06:24:20 +00004543 if (V1 == A || V1 == B) {
Bill Wendling29976b92008-12-02 06:18:11 +00004544 Instruction *NewOp =
Bill Wendlingd16c6e92008-12-02 06:22:04 +00004545 InsertNewInstBefore(BinaryOperator::CreateAnd((V1 == A) ? B : A, CI1), I);
4546 return BinaryOperator::CreateOr(NewOp, V1);
Bill Wendlinga698a472008-12-01 08:23:25 +00004547 }
4548
4549 return 0;
4550}
4551
Chris Lattner7e708292002-06-25 16:13:24 +00004552Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004553 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004554 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004555
Chris Lattner42593e62007-03-24 23:56:43 +00004556 if (isa<UndefValue>(Op1)) // X | undef -> -1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004557 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004558
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004559 // or X, X = X
4560 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00004561 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004562
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004563 // See if we can simplify any instructions used by the instruction whose sole
4564 // purpose is to compute bits we don't care about.
Chris Lattner42593e62007-03-24 23:56:43 +00004565 if (!isa<VectorType>(I.getType())) {
Chris Lattner886ab6c2009-01-31 08:15:18 +00004566 if (SimplifyDemandedInstructionBits(I))
Chris Lattner42593e62007-03-24 23:56:43 +00004567 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00004568 } else if (isa<ConstantAggregateZero>(Op1)) {
4569 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4570 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4571 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4572 return ReplaceInstUsesWith(I, I.getOperand(1));
Chris Lattner42593e62007-03-24 23:56:43 +00004573 }
Chris Lattner041a6c92007-06-15 05:26:55 +00004574
4575
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004576
Chris Lattner3f5b8772002-05-06 16:14:14 +00004577 // or X, -1 == -1
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004578 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00004579 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004580 // (X & C1) | C2 --> (X | C2) & (C1|C2)
4581 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004582 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004583 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00004584 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004585 return BinaryOperator::CreateAnd(Or,
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004586 ConstantInt::get(RHS->getValue() | C1->getValue()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004587 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004588
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004589 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4590 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004591 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004592 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00004593 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004594 return BinaryOperator::CreateXor(Or,
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004595 ConstantInt::get(C1->getValue() & ~RHS->getValue()));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004596 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004597
4598 // Try to fold constant and into select arguments.
4599 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004600 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004601 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004602 if (isa<PHINode>(Op0))
4603 if (Instruction *NV = FoldOpIntoPhi(I))
4604 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004605 }
4606
Chris Lattner4f637d42006-01-06 17:59:59 +00004607 Value *A = 0, *B = 0;
4608 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004609
4610 if (match(Op0, m_And(m_Value(A), m_Value(B))))
4611 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4612 return ReplaceInstUsesWith(I, Op1);
4613 if (match(Op1, m_And(m_Value(A), m_Value(B))))
4614 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4615 return ReplaceInstUsesWith(I, Op0);
4616
Chris Lattner6423d4c2006-07-10 20:25:24 +00004617 // (A | B) | C and A | (B | C) -> bswap if possible.
4618 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004619 if (match(Op0, m_Or(m_Value(), m_Value())) ||
Chris Lattner6423d4c2006-07-10 20:25:24 +00004620 match(Op1, m_Or(m_Value(), m_Value())) ||
4621 (match(Op0, m_Shift(m_Value(), m_Value())) &&
4622 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00004623 if (Instruction *BSwap = MatchBSwap(I))
4624 return BSwap;
4625 }
4626
Chris Lattner6e4c6492005-05-09 04:58:36 +00004627 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4628 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004629 MaskedValueIsZero(Op1, C1->getValue())) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004630 Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00004631 InsertNewInstBefore(NOr, I);
4632 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004633 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004634 }
4635
4636 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4637 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004638 MaskedValueIsZero(Op0, C1->getValue())) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004639 Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
Chris Lattner6934a042007-02-11 01:23:03 +00004640 InsertNewInstBefore(NOr, I);
4641 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004642 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004643 }
4644
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004645 // (A & C)|(B & D)
Chris Lattner2384d7b2007-06-19 05:43:49 +00004646 Value *C = 0, *D = 0;
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004647 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4648 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004649 Value *V1 = 0, *V2 = 0, *V3 = 0;
4650 C1 = dyn_cast<ConstantInt>(C);
4651 C2 = dyn_cast<ConstantInt>(D);
4652 if (C1 && C2) { // (A & C1)|(B & C2)
4653 // If we have: ((V + N) & C1) | (V & C2)
4654 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4655 // replace with V+N.
4656 if (C1->getValue() == ~C2->getValue()) {
4657 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4658 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4659 // Add commutes, try both ways.
4660 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4661 return ReplaceInstUsesWith(I, A);
4662 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4663 return ReplaceInstUsesWith(I, A);
4664 }
4665 // Or commutes, try both ways.
4666 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4667 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4668 // Add commutes, try both ways.
4669 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4670 return ReplaceInstUsesWith(I, B);
4671 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4672 return ReplaceInstUsesWith(I, B);
4673 }
4674 }
Chris Lattner044e5332007-04-08 08:01:49 +00004675 V1 = 0; V2 = 0; V3 = 0;
Chris Lattner6cae0e02007-04-08 07:55:22 +00004676 }
4677
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004678 // Check to see if we have any common things being and'ed. If so, find the
4679 // terms for V1 & (V2|V3).
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004680 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4681 if (A == B) // (A & C)|(A & D) == A & (C|D)
4682 V1 = A, V2 = C, V3 = D;
4683 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4684 V1 = A, V2 = B, V3 = C;
4685 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4686 V1 = C, V2 = A, V3 = D;
4687 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4688 V1 = C, V2 = A, V3 = B;
4689
4690 if (V1) {
4691 Value *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004692 InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4693 return BinaryOperator::CreateAnd(V1, Or);
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00004694 }
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004695 }
Dan Gohmanb493b272008-10-28 22:38:57 +00004696
Dan Gohman1975d032008-10-30 20:40:10 +00004697 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004698 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D))
4699 return Match;
4700 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C))
4701 return Match;
4702 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D))
4703 return Match;
4704 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C))
4705 return Match;
Bill Wendlingb01865c2008-11-30 13:52:49 +00004706
Bill Wendlingb01865c2008-11-30 13:52:49 +00004707 // ((A&~B)|(~A&B)) -> A^B
Bill Wendling03aae5f2008-12-01 08:09:47 +00004708 if ((match(C, m_Not(m_Specific(D))) &&
4709 match(B, m_Not(m_Specific(A)))))
4710 return BinaryOperator::CreateXor(A, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004711 // ((~B&A)|(~A&B)) -> A^B
Bill Wendling03aae5f2008-12-01 08:09:47 +00004712 if ((match(A, m_Not(m_Specific(D))) &&
4713 match(B, m_Not(m_Specific(C)))))
4714 return BinaryOperator::CreateXor(C, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004715 // ((A&~B)|(B&~A)) -> A^B
Bill Wendling03aae5f2008-12-01 08:09:47 +00004716 if ((match(C, m_Not(m_Specific(B))) &&
4717 match(D, m_Not(m_Specific(A)))))
4718 return BinaryOperator::CreateXor(A, B);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004719 // ((~B&A)|(B&~A)) -> A^B
Bill Wendling03aae5f2008-12-01 08:09:47 +00004720 if ((match(A, m_Not(m_Specific(B))) &&
4721 match(D, m_Not(m_Specific(C)))))
4722 return BinaryOperator::CreateXor(C, B);
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004723 }
Chris Lattnere511b742006-11-14 07:46:50 +00004724
4725 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004726 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4727 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4728 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004729 SI0->getOperand(1) == SI1->getOperand(1) &&
4730 (SI0->hasOneUse() || SI1->hasOneUse())) {
4731 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004732 InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
Chris Lattnere511b742006-11-14 07:46:50 +00004733 SI1->getOperand(0),
4734 SI0->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004735 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004736 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004737 }
4738 }
Chris Lattner67ca7682003-08-12 19:11:07 +00004739
Bill Wendlingb3833d12008-12-01 01:07:11 +00004740 // ((A|B)&1)|(B&-2) -> (A&1) | B
4741 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4742 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00004743 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00004744 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00004745 }
4746 // (B&-2)|((A|B)&1) -> (A&1) | B
4747 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4748 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00004749 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00004750 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00004751 }
4752
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004753 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
4754 if (A == Op1) // ~A | A == -1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004755 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004756 } else {
4757 A = 0;
4758 }
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004759 // Note, A is still live here!
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004760 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
4761 if (Op0 == B)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004762 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera27231a2003-03-10 23:13:59 +00004763
Misha Brukmancb6267b2004-07-30 12:50:08 +00004764 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004765 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004766 Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004767 I.getName()+".demorgan"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004768 return BinaryOperator::CreateNot(And);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004769 }
Chris Lattnera27231a2003-03-10 23:13:59 +00004770 }
Chris Lattnera2881962003-02-18 19:28:33 +00004771
Reid Spencere4d87aa2006-12-23 06:05:41 +00004772 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4773 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4774 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004775 return R;
4776
Chris Lattner69d4ced2008-11-16 05:20:07 +00004777 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4778 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4779 return Res;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004780 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004781
4782 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00004783 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00004784 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004785 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chengb98a10e2008-03-24 00:21:34 +00004786 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4787 !isa<ICmpInst>(Op1C->getOperand(0))) {
4788 const Type *SrcTy = Op0C->getOperand(0)->getType();
4789 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4790 // Only do this if the casts both really cause code to be
4791 // generated.
4792 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4793 I.getType(), TD) &&
4794 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4795 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004796 Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
Evan Chengb98a10e2008-03-24 00:21:34 +00004797 Op1C->getOperand(0),
4798 I.getName());
4799 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004800 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00004801 }
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004802 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004803 }
Chris Lattner99c65742007-10-24 05:38:08 +00004804 }
4805
4806
4807 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4808 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4809 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4810 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
Chris Lattner5ebd9362008-02-29 06:09:11 +00004811 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
Evan Cheng40300622008-10-14 18:44:08 +00004812 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
Chris Lattner99c65742007-10-24 05:38:08 +00004813 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4814 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4815 // If either of the constants are nans, then the whole thing returns
4816 // true.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00004817 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner99c65742007-10-24 05:38:08 +00004818 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4819
4820 // Otherwise, no need to compare the two constants, compare the
4821 // rest.
4822 return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4823 RHS->getOperand(0));
4824 }
Evan Cheng40300622008-10-14 18:44:08 +00004825 } else {
4826 Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4827 FCmpInst::Predicate Op0CC, Op1CC;
4828 if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS), m_Value(Op0RHS))) &&
4829 match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS), m_Value(Op1RHS)))) {
4830 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4831 // Swap RHS operands to match LHS.
4832 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4833 std::swap(Op1LHS, Op1RHS);
4834 }
4835 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4836 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4837 if (Op0CC == Op1CC)
4838 return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
4839 else if (Op0CC == FCmpInst::FCMP_TRUE ||
4840 Op1CC == FCmpInst::FCMP_TRUE)
4841 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4842 else if (Op0CC == FCmpInst::FCMP_FALSE)
4843 return ReplaceInstUsesWith(I, Op1);
4844 else if (Op1CC == FCmpInst::FCMP_FALSE)
4845 return ReplaceInstUsesWith(I, Op0);
4846 bool Op0Ordered;
4847 bool Op1Ordered;
4848 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4849 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4850 if (Op0Ordered == Op1Ordered) {
4851 // If both are ordered or unordered, return a new fcmp with
4852 // or'ed predicates.
4853 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4854 Op0LHS, Op0RHS);
4855 if (Instruction *I = dyn_cast<Instruction>(RV))
4856 return I;
4857 // Otherwise, it's a constant boolean value...
4858 return ReplaceInstUsesWith(I, RV);
4859 }
4860 }
4861 }
4862 }
Chris Lattner99c65742007-10-24 05:38:08 +00004863 }
4864 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004865
Chris Lattner7e708292002-06-25 16:13:24 +00004866 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004867}
4868
Dan Gohman844731a2008-05-13 00:00:25 +00004869namespace {
4870
Chris Lattnerc317d392004-02-16 01:20:27 +00004871// XorSelf - Implements: X ^ X --> 0
4872struct XorSelf {
4873 Value *RHS;
4874 XorSelf(Value *rhs) : RHS(rhs) {}
4875 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4876 Instruction *apply(BinaryOperator &Xor) const {
4877 return &Xor;
4878 }
4879};
Chris Lattner3f5b8772002-05-06 16:14:14 +00004880
Dan Gohman844731a2008-05-13 00:00:25 +00004881}
Chris Lattner3f5b8772002-05-06 16:14:14 +00004882
Chris Lattner7e708292002-06-25 16:13:24 +00004883Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004884 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004885 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004886
Evan Chengd34af782008-03-25 20:07:13 +00004887 if (isa<UndefValue>(Op1)) {
4888 if (isa<UndefValue>(Op0))
4889 // Handle undef ^ undef -> 0 special case. This is a common
4890 // idiom (misuse).
4891 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004892 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chengd34af782008-03-25 20:07:13 +00004893 }
Chris Lattnere87597f2004-10-16 18:11:37 +00004894
Chris Lattnerc317d392004-02-16 01:20:27 +00004895 // xor X, X = 0, even if X is nested in a sequence of Xor's.
4896 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00004897 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Chris Lattner233f7dc2002-08-12 21:17:25 +00004898 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00004899 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004900
4901 // See if we can simplify any instructions used by the instruction whose sole
4902 // purpose is to compute bits we don't care about.
Reid Spencera03d45f2007-03-22 22:19:58 +00004903 if (!isa<VectorType>(I.getType())) {
Chris Lattner886ab6c2009-01-31 08:15:18 +00004904 if (SimplifyDemandedInstructionBits(I))
Reid Spencera03d45f2007-03-22 22:19:58 +00004905 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00004906 } else if (isa<ConstantAggregateZero>(Op1)) {
4907 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Reid Spencera03d45f2007-03-22 22:19:58 +00004908 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00004909
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004910 // Is this a ~ operation?
4911 if (Value *NotOp = dyn_castNotVal(&I)) {
4912 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4913 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4914 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4915 if (Op0I->getOpcode() == Instruction::And ||
4916 Op0I->getOpcode() == Instruction::Or) {
4917 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4918 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4919 Instruction *NotY =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004920 BinaryOperator::CreateNot(Op0I->getOperand(1),
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004921 Op0I->getOperand(1)->getName()+".not");
4922 InsertNewInstBefore(NotY, I);
4923 if (Op0I->getOpcode() == Instruction::And)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004924 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004925 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004926 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004927 }
4928 }
4929 }
4930 }
4931
4932
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004933 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00004934 if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
Bill Wendling3479be92009-01-01 01:18:23 +00004935 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00004936 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00004937 return new ICmpInst(ICI->getInversePredicate(),
4938 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00004939
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00004940 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
4941 return new FCmpInst(FCI->getInversePredicate(),
4942 FCI->getOperand(0), FCI->getOperand(1));
4943 }
4944
Nick Lewycky517e1f52008-05-31 19:01:33 +00004945 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
4946 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4947 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
4948 if (CI->hasOneUse() && Op0C->hasOneUse()) {
4949 Instruction::CastOps Opcode = Op0C->getOpcode();
4950 if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
4951 if (RHS == ConstantExpr::getCast(Opcode, ConstantInt::getTrue(),
4952 Op0C->getDestTy())) {
4953 Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
4954 CI->getOpcode(), CI->getInversePredicate(),
4955 CI->getOperand(0), CI->getOperand(1)), I);
4956 NewCI->takeName(CI);
4957 return CastInst::Create(Opcode, NewCI, Op0C->getType());
4958 }
4959 }
4960 }
4961 }
4962 }
4963
Reid Spencere4d87aa2006-12-23 06:05:41 +00004964 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00004965 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00004966 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4967 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattner48595f12004-06-10 02:07:29 +00004968 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4969 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattner7c4049c2004-01-12 19:35:11 +00004970 ConstantInt::get(I.getType(), 1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004971 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00004972 }
Chris Lattner5c6e2db2007-04-02 05:36:22 +00004973
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004974 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004975 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00004976 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00004977 if (RHS->isAllOnesValue()) {
Chris Lattner48595f12004-06-10 02:07:29 +00004978 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004979 return BinaryOperator::CreateSub(
Chris Lattner48595f12004-06-10 02:07:29 +00004980 ConstantExpr::getSub(NegOp0CI,
Chris Lattner7c4049c2004-01-12 19:35:11 +00004981 ConstantInt::get(I.getType(), 1)),
Chris Lattner689d24b2003-11-04 23:37:10 +00004982 Op0I->getOperand(0));
Chris Lattneracf4e072007-04-02 05:42:22 +00004983 } else if (RHS->getValue().isSignBit()) {
Chris Lattner5c6e2db2007-04-02 05:36:22 +00004984 // (X + C) ^ signbit -> (X + C + signbit)
4985 Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004986 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Chris Lattnercd1d6d52007-04-02 05:48:58 +00004987
Chris Lattner7c4049c2004-01-12 19:35:11 +00004988 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00004989 } else if (Op0I->getOpcode() == Instruction::Or) {
4990 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencera03d45f2007-03-22 22:19:58 +00004991 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Chris Lattner02bd1b32006-02-26 19:57:54 +00004992 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4993 // Anything in both C1 and C2 is known to be zero, remove it from
4994 // NewRHS.
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004995 Constant *CommonBits = And(Op0CI, RHS);
Chris Lattner02bd1b32006-02-26 19:57:54 +00004996 NewRHS = ConstantExpr::getAnd(NewRHS,
4997 ConstantExpr::getNot(CommonBits));
Chris Lattnerdbab3862007-03-02 21:28:56 +00004998 AddToWorkList(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00004999 I.setOperand(0, Op0I->getOperand(0));
5000 I.setOperand(1, NewRHS);
5001 return &I;
5002 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00005003 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005004 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00005005 }
Chris Lattner2eefe512004-04-09 19:05:30 +00005006
5007 // Try to fold constant and into select arguments.
5008 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00005009 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00005010 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00005011 if (isa<PHINode>(Op0))
5012 if (Instruction *NV = FoldOpIntoPhi(I))
5013 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005014 }
5015
Chris Lattner8d969642003-03-10 23:06:50 +00005016 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005017 if (X == Op1)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005018 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005019
Chris Lattner8d969642003-03-10 23:06:50 +00005020 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005021 if (X == Op0)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005022 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005023
Chris Lattner318bf792007-03-18 22:51:34 +00005024
5025 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5026 if (Op1I) {
5027 Value *A, *B;
5028 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
5029 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005030 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00005031 I.swapOperands();
5032 std::swap(Op0, Op1);
Chris Lattner318bf792007-03-18 22:51:34 +00005033 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005034 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00005035 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00005036 }
Chris Lattnercb504b92008-11-16 05:38:51 +00005037 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
5038 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
5039 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
5040 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
Chris Lattner318bf792007-03-18 22:51:34 +00005041 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
Chris Lattner6abbdf92007-04-01 05:36:37 +00005042 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattner64daab52006-04-01 08:03:55 +00005043 Op1I->swapOperands();
Chris Lattner6abbdf92007-04-01 05:36:37 +00005044 std::swap(A, B);
5045 }
Chris Lattner318bf792007-03-18 22:51:34 +00005046 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattner64daab52006-04-01 08:03:55 +00005047 I.swapOperands(); // Simplified below.
5048 std::swap(Op0, Op1);
5049 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00005050 }
Chris Lattner318bf792007-03-18 22:51:34 +00005051 }
5052
5053 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5054 if (Op0I) {
5055 Value *A, *B;
5056 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
5057 if (A == Op1) // (B|A)^B == (A|B)^B
5058 std::swap(A, B);
5059 if (B == Op1) { // (A|B)^B == A & ~B
5060 Instruction *NotB =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005061 InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I);
5062 return BinaryOperator::CreateAnd(A, NotB);
Chris Lattnercb40a372003-03-10 18:24:17 +00005063 }
Chris Lattnercb504b92008-11-16 05:38:51 +00005064 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
5065 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
5066 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
5067 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
Chris Lattner318bf792007-03-18 22:51:34 +00005068 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
5069 if (A == Op1) // (A&B)^A -> (B&A)^A
5070 std::swap(A, B);
5071 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattnerae1ab392006-04-01 22:05:01 +00005072 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner318bf792007-03-18 22:51:34 +00005073 Instruction *N =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005074 InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I);
5075 return BinaryOperator::CreateAnd(N, Op1);
Chris Lattner64daab52006-04-01 08:03:55 +00005076 }
Chris Lattnercb40a372003-03-10 18:24:17 +00005077 }
Chris Lattner318bf792007-03-18 22:51:34 +00005078 }
5079
5080 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
5081 if (Op0I && Op1I && Op0I->isShift() &&
5082 Op0I->getOpcode() == Op1I->getOpcode() &&
5083 Op0I->getOperand(1) == Op1I->getOperand(1) &&
5084 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5085 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005086 InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
Chris Lattner318bf792007-03-18 22:51:34 +00005087 Op1I->getOperand(0),
5088 Op0I->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005089 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Chris Lattner318bf792007-03-18 22:51:34 +00005090 Op1I->getOperand(1));
5091 }
5092
5093 if (Op0I && Op1I) {
5094 Value *A, *B, *C, *D;
5095 // (A & B)^(A | B) -> A ^ B
5096 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5097 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
5098 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005099 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005100 }
5101 // (A | B)^(A & B) -> A ^ B
5102 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5103 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5104 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005105 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005106 }
5107
5108 // (A & B)^(C & D)
5109 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
5110 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5111 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5112 // (X & Y)^(X & Y) -> (Y^Z) & X
5113 Value *X = 0, *Y = 0, *Z = 0;
5114 if (A == C)
5115 X = A, Y = B, Z = D;
5116 else if (A == D)
5117 X = A, Y = B, Z = C;
5118 else if (B == C)
5119 X = B, Y = A, Z = D;
5120 else if (B == D)
5121 X = B, Y = A, Z = C;
5122
5123 if (X) {
5124 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005125 InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
5126 return BinaryOperator::CreateAnd(NewOp, X);
Chris Lattner318bf792007-03-18 22:51:34 +00005127 }
5128 }
5129 }
5130
Reid Spencere4d87aa2006-12-23 06:05:41 +00005131 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5132 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
5133 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00005134 return R;
5135
Chris Lattner6fc205f2006-05-05 06:39:07 +00005136 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00005137 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00005138 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005139 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5140 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00005141 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005142 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005143 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5144 I.getType(), TD) &&
5145 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5146 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005147 Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005148 Op1C->getOperand(0),
5149 I.getName());
5150 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005151 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005152 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00005153 }
Chris Lattner99c65742007-10-24 05:38:08 +00005154 }
Nick Lewycky517e1f52008-05-31 19:01:33 +00005155
Chris Lattner7e708292002-06-25 16:13:24 +00005156 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005157}
5158
Chris Lattnera96879a2004-09-29 17:40:11 +00005159/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
5160/// overflowed for this type.
5161static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
Reid Spencere4e40032007-03-21 23:19:50 +00005162 ConstantInt *In2, bool IsSigned = false) {
Zhou Sheng4a1822a2007-04-02 13:45:30 +00005163 Result = cast<ConstantInt>(Add(In1, In2));
Chris Lattnera96879a2004-09-29 17:40:11 +00005164
Reid Spencere4e40032007-03-21 23:19:50 +00005165 if (IsSigned)
5166 if (In2->getValue().isNegative())
5167 return Result->getValue().sgt(In1->getValue());
5168 else
5169 return Result->getValue().slt(In1->getValue());
5170 else
5171 return Result->getValue().ult(In1->getValue());
Chris Lattnera96879a2004-09-29 17:40:11 +00005172}
5173
Dan Gohman1df3fd62008-09-10 23:30:57 +00005174/// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5175/// overflowed for this type.
5176static bool SubWithOverflow(ConstantInt *&Result, ConstantInt *In1,
5177 ConstantInt *In2, bool IsSigned = false) {
Dan Gohmanbcb37fd2008-09-11 18:53:02 +00005178 Result = cast<ConstantInt>(Subtract(In1, In2));
Dan Gohman1df3fd62008-09-10 23:30:57 +00005179
5180 if (IsSigned)
5181 if (In2->getValue().isNegative())
5182 return Result->getValue().slt(In1->getValue());
5183 else
5184 return Result->getValue().sgt(In1->getValue());
5185 else
5186 return Result->getValue().ugt(In1->getValue());
5187}
5188
Chris Lattner574da9b2005-01-13 20:14:25 +00005189/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5190/// code necessary to compute the offset from the base pointer (without adding
5191/// in the base pointer). Return the result as a signed integer of intptr size.
5192static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
5193 TargetData &TD = IC.getTargetData();
5194 gep_type_iterator GTI = gep_type_begin(GEP);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005195 const Type *IntPtrTy = TD.getIntPtrType();
5196 Value *Result = Constant::getNullValue(IntPtrTy);
Chris Lattner574da9b2005-01-13 20:14:25 +00005197
5198 // Build a mask for high order bits.
Chris Lattner10c0d912008-04-22 02:53:33 +00005199 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Chris Lattnere62f0212007-04-28 04:52:43 +00005200 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Chris Lattner574da9b2005-01-13 20:14:25 +00005201
Gabor Greif177dd3f2008-06-12 21:37:33 +00005202 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5203 ++i, ++GTI) {
5204 Value *Op = *i;
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00005205 uint64_t Size = TD.getTypePaddedSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattnere62f0212007-04-28 04:52:43 +00005206 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5207 if (OpC->isZero()) continue;
5208
5209 // Handle a struct index, which adds its field offset to the pointer.
5210 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5211 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5212
5213 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
5214 Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
Chris Lattner9bc14642007-04-28 00:57:34 +00005215 else
Chris Lattnere62f0212007-04-28 04:52:43 +00005216 Result = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005217 BinaryOperator::CreateAdd(Result,
Chris Lattnere62f0212007-04-28 04:52:43 +00005218 ConstantInt::get(IntPtrTy, Size),
5219 GEP->getName()+".offs"), I);
5220 continue;
Chris Lattner9bc14642007-04-28 00:57:34 +00005221 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005222
5223 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5224 Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5225 Scale = ConstantExpr::getMul(OC, Scale);
5226 if (Constant *RC = dyn_cast<Constant>(Result))
5227 Result = ConstantExpr::getAdd(RC, Scale);
5228 else {
5229 // Emit an add instruction.
5230 Result = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005231 BinaryOperator::CreateAdd(Result, Scale,
Chris Lattnere62f0212007-04-28 04:52:43 +00005232 GEP->getName()+".offs"), I);
Chris Lattner9bc14642007-04-28 00:57:34 +00005233 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005234 continue;
Chris Lattner574da9b2005-01-13 20:14:25 +00005235 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005236 // Convert to correct type.
5237 if (Op->getType() != IntPtrTy) {
5238 if (Constant *OpC = dyn_cast<Constant>(Op))
Chris Lattner62ce3b32009-04-07 05:03:34 +00005239 Op = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true);
Chris Lattnere62f0212007-04-28 04:52:43 +00005240 else
Chris Lattner62ce3b32009-04-07 05:03:34 +00005241 Op = IC.InsertNewInstBefore(CastInst::CreateIntegerCast(Op, IntPtrTy,
5242 true,
5243 Op->getName()+".c"), I);
Chris Lattnere62f0212007-04-28 04:52:43 +00005244 }
5245 if (Size != 1) {
5246 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5247 if (Constant *OpC = dyn_cast<Constant>(Op))
5248 Op = ConstantExpr::getMul(OpC, Scale);
5249 else // We'll let instcombine(mul) convert this to a shl if possible.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005250 Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
Chris Lattnere62f0212007-04-28 04:52:43 +00005251 GEP->getName()+".idx"), I);
5252 }
5253
5254 // Emit an add instruction.
5255 if (isa<Constant>(Op) && isa<Constant>(Result))
5256 Result = ConstantExpr::getAdd(cast<Constant>(Op),
5257 cast<Constant>(Result));
5258 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005259 Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
Chris Lattnere62f0212007-04-28 04:52:43 +00005260 GEP->getName()+".offs"), I);
Chris Lattner574da9b2005-01-13 20:14:25 +00005261 }
5262 return Result;
5263}
5264
Chris Lattner10c0d912008-04-22 02:53:33 +00005265
5266/// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
5267/// the *offset* implied by GEP to zero. For example, if we have &A[i], we want
5268/// to return 'i' for "icmp ne i, 0". Note that, in general, indices can be
5269/// complex, and scales are involved. The above expression would also be legal
5270/// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32). This
5271/// later form is less amenable to optimization though, and we are allowed to
5272/// generate the first by knowing that pointer arithmetic doesn't overflow.
5273///
5274/// If we can't emit an optimized form for this expression, this returns null.
5275///
5276static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5277 InstCombiner &IC) {
Chris Lattner10c0d912008-04-22 02:53:33 +00005278 TargetData &TD = IC.getTargetData();
5279 gep_type_iterator GTI = gep_type_begin(GEP);
5280
5281 // Check to see if this gep only has a single variable index. If so, and if
5282 // any constant indices are a multiple of its scale, then we can compute this
5283 // in terms of the scale of the variable index. For example, if the GEP
5284 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5285 // because the expression will cross zero at the same point.
5286 unsigned i, e = GEP->getNumOperands();
5287 int64_t Offset = 0;
5288 for (i = 1; i != e; ++i, ++GTI) {
5289 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5290 // Compute the aggregate offset of constant indices.
5291 if (CI->isZero()) continue;
5292
5293 // Handle a struct index, which adds its field offset to the pointer.
5294 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5295 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5296 } else {
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00005297 uint64_t Size = TD.getTypePaddedSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005298 Offset += Size*CI->getSExtValue();
5299 }
5300 } else {
5301 // Found our variable index.
5302 break;
5303 }
5304 }
5305
5306 // If there are no variable indices, we must have a constant offset, just
5307 // evaluate it the general way.
5308 if (i == e) return 0;
5309
5310 Value *VariableIdx = GEP->getOperand(i);
5311 // Determine the scale factor of the variable element. For example, this is
5312 // 4 if the variable index is into an array of i32.
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00005313 uint64_t VariableScale = TD.getTypePaddedSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005314
5315 // Verify that there are no other variable indices. If so, emit the hard way.
5316 for (++i, ++GTI; i != e; ++i, ++GTI) {
5317 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5318 if (!CI) return 0;
5319
5320 // Compute the aggregate offset of constant indices.
5321 if (CI->isZero()) continue;
5322
5323 // Handle a struct index, which adds its field offset to the pointer.
5324 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5325 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5326 } else {
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00005327 uint64_t Size = TD.getTypePaddedSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005328 Offset += Size*CI->getSExtValue();
5329 }
5330 }
5331
5332 // Okay, we know we have a single variable index, which must be a
5333 // pointer/array/vector index. If there is no offset, life is simple, return
5334 // the index.
5335 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5336 if (Offset == 0) {
5337 // Cast to intptrty in case a truncation occurs. If an extension is needed,
5338 // we don't need to bother extending: the extension won't affect where the
5339 // computation crosses zero.
5340 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5341 VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
5342 VariableIdx->getNameStart(), &I);
5343 return VariableIdx;
5344 }
5345
5346 // Otherwise, there is an index. The computation we will do will be modulo
5347 // the pointer size, so get it.
5348 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5349
5350 Offset &= PtrSizeMask;
5351 VariableScale &= PtrSizeMask;
5352
5353 // To do this transformation, any constant index must be a multiple of the
5354 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
5355 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
5356 // multiple of the variable scale.
5357 int64_t NewOffs = Offset / (int64_t)VariableScale;
5358 if (Offset != NewOffs*(int64_t)VariableScale)
5359 return 0;
5360
5361 // Okay, we can do this evaluation. Start by converting the index to intptr.
5362 const Type *IntPtrTy = TD.getIntPtrType();
5363 if (VariableIdx->getType() != IntPtrTy)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005364 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
Chris Lattner10c0d912008-04-22 02:53:33 +00005365 true /*SExt*/,
5366 VariableIdx->getNameStart(), &I);
5367 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005368 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
Chris Lattner10c0d912008-04-22 02:53:33 +00005369}
5370
5371
Reid Spencere4d87aa2006-12-23 06:05:41 +00005372/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner574da9b2005-01-13 20:14:25 +00005373/// else. At this point we know that the GEP is on the LHS of the comparison.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005374Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
5375 ICmpInst::Predicate Cond,
5376 Instruction &I) {
Chris Lattner574da9b2005-01-13 20:14:25 +00005377 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattnere9d782b2005-01-13 22:25:21 +00005378
Chris Lattner10c0d912008-04-22 02:53:33 +00005379 // Look through bitcasts.
5380 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5381 RHS = BCI->getOperand(0);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005382
Chris Lattner574da9b2005-01-13 20:14:25 +00005383 Value *PtrBase = GEPLHS->getOperand(0);
5384 if (PtrBase == RHS) {
Chris Lattner7c95deb2008-02-05 04:45:32 +00005385 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattner10c0d912008-04-22 02:53:33 +00005386 // This transformation (ignoring the base and scales) is valid because we
5387 // know pointers can't overflow. See if we can output an optimized form.
5388 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5389
5390 // If not, synthesize the offset the hard way.
5391 if (Offset == 0)
5392 Offset = EmitGEPOffset(GEPLHS, I, *this);
Chris Lattner7c95deb2008-02-05 04:45:32 +00005393 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
5394 Constant::getNullValue(Offset->getType()));
Chris Lattner574da9b2005-01-13 20:14:25 +00005395 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00005396 // If the base pointers are different, but the indices are the same, just
5397 // compare the base pointer.
5398 if (PtrBase != GEPRHS->getOperand(0)) {
5399 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00005400 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00005401 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00005402 if (IndicesTheSame)
5403 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5404 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5405 IndicesTheSame = false;
5406 break;
5407 }
5408
5409 // If all indices are the same, just compare the base pointers.
5410 if (IndicesTheSame)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005411 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
5412 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera70b66d2005-04-25 20:17:30 +00005413
5414 // Otherwise, the base pointers are different and the indices are
5415 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00005416 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00005417 }
Chris Lattner574da9b2005-01-13 20:14:25 +00005418
Chris Lattnere9d782b2005-01-13 22:25:21 +00005419 // If one of the GEPs has all zero indices, recurse.
5420 bool AllZeros = true;
5421 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5422 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5423 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5424 AllZeros = false;
5425 break;
5426 }
5427 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005428 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5429 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005430
5431 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00005432 AllZeros = true;
5433 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5434 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5435 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5436 AllZeros = false;
5437 break;
5438 }
5439 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005440 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005441
Chris Lattner4401c9c2005-01-14 00:20:05 +00005442 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5443 // If the GEPs only differ by one index, compare it.
5444 unsigned NumDifferences = 0; // Keep track of # differences.
5445 unsigned DiffOperand = 0; // The operand that differs.
5446 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5447 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00005448 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5449 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005450 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00005451 NumDifferences = 2;
5452 break;
5453 } else {
5454 if (NumDifferences++) break;
5455 DiffOperand = i;
5456 }
5457 }
5458
5459 if (NumDifferences == 0) // SAME GEP?
5460 return ReplaceInstUsesWith(I, // No comparison is needed here.
Nick Lewycky455e1762007-09-06 02:40:25 +00005461 ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005462 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky455e1762007-09-06 02:40:25 +00005463
Chris Lattner4401c9c2005-01-14 00:20:05 +00005464 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005465 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5466 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005467 // Make sure we do a signed comparison here.
5468 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005469 }
5470 }
5471
Reid Spencere4d87aa2006-12-23 06:05:41 +00005472 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00005473 // the result to fold to a constant!
5474 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5475 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5476 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
5477 Value *L = EmitGEPOffset(GEPLHS, I, *this);
5478 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005479 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner574da9b2005-01-13 20:14:25 +00005480 }
5481 }
5482 return 0;
5483}
5484
Chris Lattnera5406232008-05-19 20:18:56 +00005485/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5486///
5487Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5488 Instruction *LHSI,
5489 Constant *RHSC) {
5490 if (!isa<ConstantFP>(RHSC)) return 0;
5491 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5492
5493 // Get the width of the mantissa. We don't want to hack on conversions that
5494 // might lose information from the integer, e.g. "i64 -> float"
Chris Lattner7be1c452008-05-19 21:17:23 +00005495 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Chris Lattnera5406232008-05-19 20:18:56 +00005496 if (MantissaWidth == -1) return 0; // Unknown.
5497
5498 // Check to see that the input is converted from an integer type that is small
5499 // enough that preserves all bits. TODO: check here for "known" sign bits.
5500 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5501 unsigned InputSize = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
5502
5503 // If this is a uitofp instruction, we need an extra bit to hold the sign.
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005504 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5505 if (LHSUnsigned)
Chris Lattnera5406232008-05-19 20:18:56 +00005506 ++InputSize;
5507
5508 // If the conversion would lose info, don't hack on this.
5509 if ((int)InputSize > MantissaWidth)
5510 return 0;
5511
5512 // Otherwise, we can potentially simplify the comparison. We know that it
5513 // will always come through as an integer value and we know the constant is
5514 // not a NAN (it would have been previously simplified).
5515 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5516
5517 ICmpInst::Predicate Pred;
5518 switch (I.getPredicate()) {
5519 default: assert(0 && "Unexpected predicate!");
5520 case FCmpInst::FCMP_UEQ:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005521 case FCmpInst::FCMP_OEQ:
5522 Pred = ICmpInst::ICMP_EQ;
5523 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005524 case FCmpInst::FCMP_UGT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005525 case FCmpInst::FCMP_OGT:
5526 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5527 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005528 case FCmpInst::FCMP_UGE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005529 case FCmpInst::FCMP_OGE:
5530 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5531 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005532 case FCmpInst::FCMP_ULT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005533 case FCmpInst::FCMP_OLT:
5534 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5535 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005536 case FCmpInst::FCMP_ULE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005537 case FCmpInst::FCMP_OLE:
5538 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5539 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005540 case FCmpInst::FCMP_UNE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005541 case FCmpInst::FCMP_ONE:
5542 Pred = ICmpInst::ICMP_NE;
5543 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005544 case FCmpInst::FCMP_ORD:
Eli Friedman8b019c82008-11-30 22:48:49 +00005545 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnera5406232008-05-19 20:18:56 +00005546 case FCmpInst::FCMP_UNO:
Eli Friedman8b019c82008-11-30 22:48:49 +00005547 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattnera5406232008-05-19 20:18:56 +00005548 }
5549
5550 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5551
5552 // Now we know that the APFloat is a normal number, zero or inf.
5553
Chris Lattner85162782008-05-20 03:50:52 +00005554 // See if the FP constant is too large for the integer. For example,
Chris Lattnera5406232008-05-19 20:18:56 +00005555 // comparing an i8 to 300.0.
5556 unsigned IntWidth = IntTy->getPrimitiveSizeInBits();
5557
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005558 if (!LHSUnsigned) {
5559 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5560 // and large values.
5561 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5562 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5563 APFloat::rmNearestTiesToEven);
5564 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5565 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
5566 Pred == ICmpInst::ICMP_SLE)
Eli Friedman8b019c82008-11-30 22:48:49 +00005567 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5568 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005569 }
5570 } else {
5571 // If the RHS value is > UnsignedMax, fold the comparison. This handles
5572 // +INF and large values.
5573 APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5574 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5575 APFloat::rmNearestTiesToEven);
5576 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
5577 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
5578 Pred == ICmpInst::ICMP_ULE)
Eli Friedman8b019c82008-11-30 22:48:49 +00005579 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5580 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005581 }
Chris Lattnera5406232008-05-19 20:18:56 +00005582 }
5583
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005584 if (!LHSUnsigned) {
5585 // See if the RHS value is < SignedMin.
5586 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5587 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5588 APFloat::rmNearestTiesToEven);
5589 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5590 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5591 Pred == ICmpInst::ICMP_SGE)
Eli Friedman8b019c82008-11-30 22:48:49 +00005592 return ReplaceInstUsesWith(I,ConstantInt::getTrue());
5593 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005594 }
Chris Lattnera5406232008-05-19 20:18:56 +00005595 }
5596
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005597 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5598 // [0, UMAX], but it may still be fractional. See if it is fractional by
5599 // casting the FP value to the integer value and back, checking for equality.
5600 // Don't do this for zero, because -0.0 is not fractional.
Chris Lattnera5406232008-05-19 20:18:56 +00005601 Constant *RHSInt = ConstantExpr::getFPToSI(RHSC, IntTy);
5602 if (!RHS.isZero() &&
5603 ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) != RHSC) {
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005604 // If we had a comparison against a fractional value, we have to adjust the
5605 // compare predicate and sometimes the value. RHSC is rounded towards zero
5606 // at this point.
Chris Lattnera5406232008-05-19 20:18:56 +00005607 switch (Pred) {
5608 default: assert(0 && "Unexpected integer comparison!");
5609 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
Eli Friedman8b019c82008-11-30 22:48:49 +00005610 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnera5406232008-05-19 20:18:56 +00005611 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
Eli Friedman8b019c82008-11-30 22:48:49 +00005612 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005613 case ICmpInst::ICMP_ULE:
5614 // (float)int <= 4.4 --> int <= 4
5615 // (float)int <= -4.4 --> false
5616 if (RHS.isNegative())
Eli Friedman8b019c82008-11-30 22:48:49 +00005617 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005618 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005619 case ICmpInst::ICMP_SLE:
5620 // (float)int <= 4.4 --> int <= 4
5621 // (float)int <= -4.4 --> int < -4
5622 if (RHS.isNegative())
5623 Pred = ICmpInst::ICMP_SLT;
5624 break;
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005625 case ICmpInst::ICMP_ULT:
5626 // (float)int < -4.4 --> false
5627 // (float)int < 4.4 --> int <= 4
5628 if (RHS.isNegative())
Eli Friedman8b019c82008-11-30 22:48:49 +00005629 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005630 Pred = ICmpInst::ICMP_ULE;
5631 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005632 case ICmpInst::ICMP_SLT:
5633 // (float)int < -4.4 --> int < -4
5634 // (float)int < 4.4 --> int <= 4
5635 if (!RHS.isNegative())
5636 Pred = ICmpInst::ICMP_SLE;
5637 break;
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005638 case ICmpInst::ICMP_UGT:
5639 // (float)int > 4.4 --> int > 4
5640 // (float)int > -4.4 --> true
5641 if (RHS.isNegative())
Eli Friedman8b019c82008-11-30 22:48:49 +00005642 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005643 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005644 case ICmpInst::ICMP_SGT:
5645 // (float)int > 4.4 --> int > 4
5646 // (float)int > -4.4 --> int >= -4
5647 if (RHS.isNegative())
5648 Pred = ICmpInst::ICMP_SGE;
5649 break;
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005650 case ICmpInst::ICMP_UGE:
5651 // (float)int >= -4.4 --> true
5652 // (float)int >= 4.4 --> int > 4
5653 if (!RHS.isNegative())
Eli Friedman8b019c82008-11-30 22:48:49 +00005654 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005655 Pred = ICmpInst::ICMP_UGT;
5656 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005657 case ICmpInst::ICMP_SGE:
5658 // (float)int >= -4.4 --> int >= -4
5659 // (float)int >= 4.4 --> int > 4
5660 if (!RHS.isNegative())
5661 Pred = ICmpInst::ICMP_SGT;
5662 break;
5663 }
5664 }
5665
5666 // Lower this FP comparison into an appropriate integer version of the
5667 // comparison.
5668 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
5669}
5670
Reid Spencere4d87aa2006-12-23 06:05:41 +00005671Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5672 bool Changed = SimplifyCompare(I);
Chris Lattner8b170942002-08-09 23:47:40 +00005673 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005674
Chris Lattner58e97462007-01-14 19:42:17 +00005675 // Fold trivial predicates.
5676 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
Eli Friedman8b019c82008-11-30 22:48:49 +00005677 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattner58e97462007-01-14 19:42:17 +00005678 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
Eli Friedman8b019c82008-11-30 22:48:49 +00005679 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner58e97462007-01-14 19:42:17 +00005680
5681 // Simplify 'fcmp pred X, X'
5682 if (Op0 == Op1) {
5683 switch (I.getPredicate()) {
5684 default: assert(0 && "Unknown predicate!");
5685 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5686 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5687 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
Eli Friedman8b019c82008-11-30 22:48:49 +00005688 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner58e97462007-01-14 19:42:17 +00005689 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5690 case FCmpInst::FCMP_OLT: // True if ordered and less than
5691 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
Eli Friedman8b019c82008-11-30 22:48:49 +00005692 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattner58e97462007-01-14 19:42:17 +00005693
5694 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5695 case FCmpInst::FCMP_ULT: // True if unordered or less than
5696 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5697 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5698 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5699 I.setPredicate(FCmpInst::FCMP_UNO);
5700 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5701 return &I;
5702
5703 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5704 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5705 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5706 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5707 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5708 I.setPredicate(FCmpInst::FCMP_ORD);
5709 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5710 return &I;
5711 }
5712 }
5713
Reid Spencere4d87aa2006-12-23 06:05:41 +00005714 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Reid Spencer4fe16d62007-01-11 18:21:29 +00005715 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Chris Lattnere87597f2004-10-16 18:11:37 +00005716
Reid Spencere4d87aa2006-12-23 06:05:41 +00005717 // Handle fcmp with constant RHS
5718 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
Chris Lattnera5406232008-05-19 20:18:56 +00005719 // If the constant is a nan, see if we can fold the comparison based on it.
5720 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5721 if (CFP->getValueAPF().isNaN()) {
5722 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
Eli Friedman8b019c82008-11-30 22:48:49 +00005723 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattner85162782008-05-20 03:50:52 +00005724 assert(FCmpInst::isUnordered(I.getPredicate()) &&
5725 "Comparison must be either ordered or unordered!");
5726 // True if unordered.
Eli Friedman8b019c82008-11-30 22:48:49 +00005727 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnera5406232008-05-19 20:18:56 +00005728 }
5729 }
5730
Reid Spencere4d87aa2006-12-23 06:05:41 +00005731 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5732 switch (LHSI->getOpcode()) {
5733 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00005734 // Only fold fcmp into the PHI if the phi and fcmp are in the same
5735 // block. If in the same block, we're encouraging jump threading. If
5736 // not, we are just pessimizing the code by making an i1 phi.
5737 if (LHSI->getParent() == I.getParent())
5738 if (Instruction *NV = FoldOpIntoPhi(I))
5739 return NV;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005740 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005741 case Instruction::SIToFP:
5742 case Instruction::UIToFP:
5743 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5744 return NV;
5745 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005746 case Instruction::Select:
5747 // If either operand of the select is a constant, we can fold the
5748 // comparison into the select arms, which will cause one to be
5749 // constant folded and the select turned into a bitwise or.
5750 Value *Op1 = 0, *Op2 = 0;
5751 if (LHSI->hasOneUse()) {
5752 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5753 // Fold the known value into the constant operand.
5754 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5755 // Insert a new FCmp of the other select operand.
5756 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5757 LHSI->getOperand(2), RHSC,
5758 I.getName()), I);
5759 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5760 // Fold the known value into the constant operand.
5761 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5762 // Insert a new FCmp of the other select operand.
5763 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5764 LHSI->getOperand(1), RHSC,
5765 I.getName()), I);
5766 }
5767 }
5768
5769 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00005770 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005771 break;
5772 }
5773 }
5774
5775 return Changed ? &I : 0;
5776}
5777
5778Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5779 bool Changed = SimplifyCompare(I);
5780 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5781 const Type *Ty = Op0->getType();
5782
5783 // icmp X, X
5784 if (Op0 == Op1)
Reid Spencer579dca12007-01-12 04:24:46 +00005785 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005786 I.isTrueWhenEqual()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00005787
5788 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Reid Spencer4fe16d62007-01-11 18:21:29 +00005789 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Christopher Lamb7a0678c2007-12-18 21:32:20 +00005790
Reid Spencere4d87aa2006-12-23 06:05:41 +00005791 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner711b3402004-11-14 07:33:16 +00005792 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanfd939082005-04-21 23:48:37 +00005793 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5794 isa<ConstantPointerNull>(Op0)) &&
5795 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner711b3402004-11-14 07:33:16 +00005796 isa<ConstantPointerNull>(Op1)))
Reid Spencer579dca12007-01-12 04:24:46 +00005797 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005798 !I.isTrueWhenEqual()));
Chris Lattner8b170942002-08-09 23:47:40 +00005799
Reid Spencere4d87aa2006-12-23 06:05:41 +00005800 // icmp's with boolean values can always be turned into bitwise operations
Reid Spencer4fe16d62007-01-11 18:21:29 +00005801 if (Ty == Type::Int1Ty) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005802 switch (I.getPredicate()) {
5803 default: assert(0 && "Invalid icmp instruction!");
Chris Lattner85b5eb02008-07-11 04:20:58 +00005804 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005805 Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner8b170942002-08-09 23:47:40 +00005806 InsertNewInstBefore(Xor, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005807 return BinaryOperator::CreateNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00005808 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00005809 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005810 return BinaryOperator::CreateXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00005811
Reid Spencere4d87aa2006-12-23 06:05:41 +00005812 case ICmpInst::ICMP_UGT:
Chris Lattner85b5eb02008-07-11 04:20:58 +00005813 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
Chris Lattner5dbef222004-08-11 00:50:51 +00005814 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00005815 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005816 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Chris Lattner5dbef222004-08-11 00:50:51 +00005817 InsertNewInstBefore(Not, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005818 return BinaryOperator::CreateAnd(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00005819 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00005820 case ICmpInst::ICMP_SGT:
5821 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
Chris Lattner5dbef222004-08-11 00:50:51 +00005822 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00005823 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
5824 Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
5825 InsertNewInstBefore(Not, I);
5826 return BinaryOperator::CreateAnd(Not, Op0);
5827 }
5828 case ICmpInst::ICMP_UGE:
5829 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
5830 // FALL THROUGH
5831 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005832 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Chris Lattner5dbef222004-08-11 00:50:51 +00005833 InsertNewInstBefore(Not, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005834 return BinaryOperator::CreateOr(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00005835 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00005836 case ICmpInst::ICMP_SGE:
5837 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
5838 // FALL THROUGH
5839 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
5840 Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
5841 InsertNewInstBefore(Not, I);
5842 return BinaryOperator::CreateOr(Not, Op0);
5843 }
Chris Lattner5dbef222004-08-11 00:50:51 +00005844 }
Chris Lattner8b170942002-08-09 23:47:40 +00005845 }
5846
Dan Gohman1c8491e2009-04-25 17:12:48 +00005847 unsigned BitWidth = 0;
5848 if (TD)
5849 BitWidth = TD->getTypeSizeInBits(Ty);
5850 else if (isa<IntegerType>(Ty))
5851 BitWidth = Ty->getPrimitiveSizeInBits();
5852
5853 bool isSignBit = false;
5854
Dan Gohman81b28ce2008-09-16 18:46:06 +00005855 // See if we are doing a comparison with a constant.
Chris Lattner8b170942002-08-09 23:47:40 +00005856 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky579214a2009-02-27 06:37:39 +00005857 Value *A = 0, *B = 0;
Christopher Lamb103e1a32007-12-20 07:21:11 +00005858
Chris Lattnerb6566012008-01-05 01:18:20 +00005859 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5860 if (I.isEquality() && CI->isNullValue() &&
5861 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
5862 // (icmp cond A B) if cond is equality
5863 return new ICmpInst(I.getPredicate(), A, B);
Owen Andersonf5783f82007-12-28 07:42:12 +00005864 }
Christopher Lamb103e1a32007-12-20 07:21:11 +00005865
Dan Gohman81b28ce2008-09-16 18:46:06 +00005866 // If we have an icmp le or icmp ge instruction, turn it into the
5867 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
5868 // them being folded in the code below.
Chris Lattner84dff672008-07-11 05:08:55 +00005869 switch (I.getPredicate()) {
5870 default: break;
5871 case ICmpInst::ICMP_ULE:
5872 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
5873 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5874 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5875 case ICmpInst::ICMP_SLE:
5876 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
5877 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5878 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5879 case ICmpInst::ICMP_UGE:
5880 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
5881 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5882 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5883 case ICmpInst::ICMP_SGE:
5884 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
5885 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5886 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
5887 }
5888
Chris Lattner183661e2008-07-11 05:40:05 +00005889 // If this comparison is a normal comparison, it demands all
Chris Lattner4241e4d2007-07-15 20:54:51 +00005890 // bits, if it is a sign bit comparison, it only demands the sign bit.
Chris Lattner4241e4d2007-07-15 20:54:51 +00005891 bool UnusedBit;
Dan Gohman1c8491e2009-04-25 17:12:48 +00005892 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5893 }
5894
5895 // See if we can fold the comparison based on range information we can get
5896 // by checking whether bits are known to be zero or one in the input.
5897 if (BitWidth != 0) {
5898 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
5899 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
5900
5901 if (SimplifyDemandedBits(I.getOperandUse(0),
Chris Lattner4241e4d2007-07-15 20:54:51 +00005902 isSignBit ? APInt::getSignBit(BitWidth)
5903 : APInt::getAllOnesValue(BitWidth),
Dan Gohman1c8491e2009-04-25 17:12:48 +00005904 Op0KnownZero, Op0KnownOne, 0))
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005905 return &I;
Dan Gohman1c8491e2009-04-25 17:12:48 +00005906 if (SimplifyDemandedBits(I.getOperandUse(1),
5907 APInt::getAllOnesValue(BitWidth),
5908 Op1KnownZero, Op1KnownOne, 0))
5909 return &I;
5910
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005911 // Given the known and unknown bits, compute a range that the LHS could be
Chris Lattner84dff672008-07-11 05:08:55 +00005912 // in. Compute the Min, Max and RHS values based on the known bits. For the
5913 // EQ and NE we use unsigned values.
Dan Gohman1c8491e2009-04-25 17:12:48 +00005914 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
5915 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
5916 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
5917 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
5918 Op0Min, Op0Max);
5919 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
5920 Op1Min, Op1Max);
5921 } else {
5922 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
5923 Op0Min, Op0Max);
5924 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
5925 Op1Min, Op1Max);
5926 }
5927
Chris Lattner183661e2008-07-11 05:40:05 +00005928 // If Min and Max are known to be the same, then SimplifyDemandedBits
5929 // figured out that the LHS is a constant. Just constant fold this now so
5930 // that code below can assume that Min != Max.
Dan Gohman1c8491e2009-04-25 17:12:48 +00005931 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
5932 return new ICmpInst(I.getPredicate(), ConstantInt::get(Op0Min), Op1);
5933 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
5934 return new ICmpInst(I.getPredicate(), Op0, ConstantInt::get(Op1Min));
5935
Chris Lattner183661e2008-07-11 05:40:05 +00005936 // Based on the range information we know about the LHS, see if we can
5937 // simplify this comparison. For example, (x&4) < 8 is always true.
Dan Gohman1c8491e2009-04-25 17:12:48 +00005938 switch (I.getPredicate()) {
Chris Lattner84dff672008-07-11 05:08:55 +00005939 default: assert(0 && "Unknown icmp opcode!");
5940 case ICmpInst::ICMP_EQ:
Dan Gohman1c8491e2009-04-25 17:12:48 +00005941 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Chris Lattner84dff672008-07-11 05:08:55 +00005942 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5943 break;
5944 case ICmpInst::ICMP_NE:
Dan Gohman1c8491e2009-04-25 17:12:48 +00005945 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Chris Lattner84dff672008-07-11 05:08:55 +00005946 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5947 break;
5948 case ICmpInst::ICMP_ULT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00005949 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
Chris Lattner84dff672008-07-11 05:08:55 +00005950 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00005951 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
Chris Lattner84dff672008-07-11 05:08:55 +00005952 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Dan Gohman1c8491e2009-04-25 17:12:48 +00005953 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
Chris Lattner183661e2008-07-11 05:40:05 +00005954 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00005955 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
5956 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
5957 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5958
5959 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
5960 if (CI->isMinValue(true))
5961 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
Chris Lattner183661e2008-07-11 05:40:05 +00005962 ConstantInt::getAllOnesValue(Op0->getType()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00005963 }
Chris Lattner84dff672008-07-11 05:08:55 +00005964 break;
5965 case ICmpInst::ICMP_UGT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00005966 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
Chris Lattner84dff672008-07-11 05:08:55 +00005967 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00005968 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
Chris Lattner84dff672008-07-11 05:08:55 +00005969 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Dan Gohman1c8491e2009-04-25 17:12:48 +00005970
5971 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
Chris Lattner183661e2008-07-11 05:40:05 +00005972 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00005973 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
5974 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C
5975 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5976
5977 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
5978 if (CI->isMaxValue(true))
5979 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
5980 ConstantInt::getNullValue(Op0->getType()));
5981 }
Chris Lattner84dff672008-07-11 05:08:55 +00005982 break;
5983 case ICmpInst::ICMP_SLT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00005984 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
Chris Lattner84dff672008-07-11 05:08:55 +00005985 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00005986 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
Chris Lattner84dff672008-07-11 05:08:55 +00005987 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Dan Gohman1c8491e2009-04-25 17:12:48 +00005988 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
Chris Lattner183661e2008-07-11 05:40:05 +00005989 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00005990 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
5991 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C
5992 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5993 }
Chris Lattner84dff672008-07-11 05:08:55 +00005994 break;
Dan Gohman1c8491e2009-04-25 17:12:48 +00005995 case ICmpInst::ICMP_SGT:
5996 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
Chris Lattner84dff672008-07-11 05:08:55 +00005997 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00005998 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
Chris Lattner84dff672008-07-11 05:08:55 +00005999 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006000
6001 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
Chris Lattner183661e2008-07-11 05:40:05 +00006002 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006003 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6004 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
6005 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
6006 }
6007 break;
6008 case ICmpInst::ICMP_SGE:
6009 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6010 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
6011 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
6012 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
6013 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
6014 break;
6015 case ICmpInst::ICMP_SLE:
6016 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6017 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
6018 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
6019 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
6020 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
6021 break;
6022 case ICmpInst::ICMP_UGE:
6023 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6024 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
6025 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
6026 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
6027 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
6028 break;
6029 case ICmpInst::ICMP_ULE:
6030 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6031 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
6032 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
6033 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
6034 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattner84dff672008-07-11 05:08:55 +00006035 break;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006036 }
Dan Gohman1c8491e2009-04-25 17:12:48 +00006037
6038 // Turn a signed comparison into an unsigned one if both operands
6039 // are known to have the same sign.
6040 if (I.isSignedPredicate() &&
6041 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6042 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
6043 return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
Dan Gohman81b28ce2008-09-16 18:46:06 +00006044 }
6045
6046 // Test if the ICmpInst instruction is used exclusively by a select as
6047 // part of a minimum or maximum operation. If so, refrain from doing
6048 // any other folding. This helps out other analyses which understand
6049 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6050 // and CodeGen. And in this case, at least one of the comparison
6051 // operands has at least one user besides the compare (the select),
6052 // which would often largely negate the benefit of folding anyway.
6053 if (I.hasOneUse())
6054 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6055 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6056 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6057 return 0;
6058
6059 // See if we are doing a comparison between a constant and an instruction that
6060 // can be folded into the comparison.
6061 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006062 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer1628cec2006-10-26 06:15:43 +00006063 // instruction, see if that instruction also has constants so that the
Reid Spencere4d87aa2006-12-23 06:05:41 +00006064 // instruction can be folded into the icmp
Chris Lattner3c6a0d42004-05-25 06:32:08 +00006065 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner01deb9d2007-04-03 17:43:25 +00006066 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6067 return Res;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006068 }
6069
Chris Lattner01deb9d2007-04-03 17:43:25 +00006070 // Handle icmp with constant (but not simple integer constant) RHS
Chris Lattner6970b662005-04-23 15:31:55 +00006071 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6072 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6073 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00006074 case Instruction::GetElementPtr:
6075 if (RHSC->isNullValue()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006076 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattner9fb25db2005-05-01 04:42:15 +00006077 bool isAllZeros = true;
6078 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6079 if (!isa<Constant>(LHSI->getOperand(i)) ||
6080 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6081 isAllZeros = false;
6082 break;
6083 }
6084 if (isAllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00006085 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Chris Lattner9fb25db2005-05-01 04:42:15 +00006086 Constant::getNullValue(LHSI->getOperand(0)->getType()));
6087 }
6088 break;
6089
Chris Lattner6970b662005-04-23 15:31:55 +00006090 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00006091 // Only fold icmp into the PHI if the phi and fcmp are in the same
6092 // block. If in the same block, we're encouraging jump threading. If
6093 // not, we are just pessimizing the code by making an i1 phi.
6094 if (LHSI->getParent() == I.getParent())
6095 if (Instruction *NV = FoldOpIntoPhi(I))
6096 return NV;
Chris Lattner6970b662005-04-23 15:31:55 +00006097 break;
Chris Lattner4802d902007-04-06 18:57:34 +00006098 case Instruction::Select: {
Chris Lattner6970b662005-04-23 15:31:55 +00006099 // If either operand of the select is a constant, we can fold the
6100 // comparison into the select arms, which will cause one to be
6101 // constant folded and the select turned into a bitwise or.
6102 Value *Op1 = 0, *Op2 = 0;
6103 if (LHSI->hasOneUse()) {
6104 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6105 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00006106 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6107 // Insert a new ICmp of the other select operand.
6108 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
6109 LHSI->getOperand(2), RHSC,
6110 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00006111 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6112 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00006113 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6114 // Insert a new ICmp of the other select operand.
6115 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
6116 LHSI->getOperand(1), RHSC,
6117 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00006118 }
6119 }
Jeff Cohen9d809302005-04-23 21:38:35 +00006120
Chris Lattner6970b662005-04-23 15:31:55 +00006121 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00006122 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Chris Lattner6970b662005-04-23 15:31:55 +00006123 break;
6124 }
Chris Lattner4802d902007-04-06 18:57:34 +00006125 case Instruction::Malloc:
6126 // If we have (malloc != null), and if the malloc has a single use, we
6127 // can assume it is successful and remove the malloc.
6128 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
6129 AddToWorkList(LHSI);
6130 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00006131 !I.isTrueWhenEqual()));
Chris Lattner4802d902007-04-06 18:57:34 +00006132 }
6133 break;
6134 }
Chris Lattner6970b662005-04-23 15:31:55 +00006135 }
6136
Reid Spencere4d87aa2006-12-23 06:05:41 +00006137 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Chris Lattner574da9b2005-01-13 20:14:25 +00006138 if (User *GEP = dyn_castGetElementPtr(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006139 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006140 return NI;
6141 if (User *GEP = dyn_castGetElementPtr(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006142 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6143 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006144 return NI;
6145
Reid Spencere4d87aa2006-12-23 06:05:41 +00006146 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner57d86372007-01-06 01:45:59 +00006147 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
6148 // now.
6149 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6150 if (isa<PointerType>(Op0->getType()) &&
6151 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006152 // We keep moving the cast from the left operand over to the right
6153 // operand, where it can often be eliminated completely.
Chris Lattner57d86372007-01-06 01:45:59 +00006154 Op0 = CI->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006155
Chris Lattner57d86372007-01-06 01:45:59 +00006156 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6157 // so eliminate it as well.
6158 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6159 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006160
Chris Lattnerde90b762003-11-03 04:25:02 +00006161 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006162 if (Op0->getType() != Op1->getType()) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006163 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Reid Spencerd977d862006-12-12 23:36:14 +00006164 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00006165 } else {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006166 // Otherwise, cast the RHS right before the icmp
Chris Lattner6d0339d2008-01-13 22:23:22 +00006167 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
Chris Lattnerde90b762003-11-03 04:25:02 +00006168 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006169 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00006170 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattnerde90b762003-11-03 04:25:02 +00006171 }
Chris Lattner57d86372007-01-06 01:45:59 +00006172 }
6173
6174 if (isa<CastInst>(Op0)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006175 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner68708052003-11-03 05:17:03 +00006176 // This comes up when you have code like
6177 // int X = A < B;
6178 // if (X) ...
6179 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00006180 // with a constant or another cast from the same type.
6181 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006182 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattner484d3cf2005-04-24 06:59:08 +00006183 return R;
Chris Lattner68708052003-11-03 05:17:03 +00006184 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006185
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006186 // See if it's the same type of instruction on the left and right.
6187 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6188 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Nick Lewycky5d52c452008-08-21 05:56:10 +00006189 if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
Nick Lewycky4333f492009-01-31 21:30:05 +00006190 Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
Nick Lewycky23c04302008-09-03 06:24:21 +00006191 switch (Op0I->getOpcode()) {
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006192 default: break;
6193 case Instruction::Add:
6194 case Instruction::Sub:
6195 case Instruction::Xor:
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006196 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
Nick Lewycky4333f492009-01-31 21:30:05 +00006197 return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
6198 Op1I->getOperand(0));
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006199 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6200 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6201 if (CI->getValue().isSignBit()) {
6202 ICmpInst::Predicate Pred = I.isSignedPredicate()
6203 ? I.getUnsignedPredicate()
6204 : I.getSignedPredicate();
6205 return new ICmpInst(Pred, Op0I->getOperand(0),
6206 Op1I->getOperand(0));
6207 }
6208
6209 if (CI->getValue().isMaxSignedValue()) {
6210 ICmpInst::Predicate Pred = I.isSignedPredicate()
6211 ? I.getUnsignedPredicate()
6212 : I.getSignedPredicate();
6213 Pred = I.getSwappedPredicate(Pred);
6214 return new ICmpInst(Pred, Op0I->getOperand(0),
6215 Op1I->getOperand(0));
Nick Lewycky4333f492009-01-31 21:30:05 +00006216 }
6217 }
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006218 break;
6219 case Instruction::Mul:
Nick Lewycky4333f492009-01-31 21:30:05 +00006220 if (!I.isEquality())
6221 break;
6222
Nick Lewycky5d52c452008-08-21 05:56:10 +00006223 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6224 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6225 // Mask = -1 >> count-trailing-zeros(Cst).
6226 if (!CI->isZero() && !CI->isOne()) {
6227 const APInt &AP = CI->getValue();
6228 ConstantInt *Mask = ConstantInt::get(
6229 APInt::getLowBitsSet(AP.getBitWidth(),
6230 AP.getBitWidth() -
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006231 AP.countTrailingZeros()));
Nick Lewycky5d52c452008-08-21 05:56:10 +00006232 Instruction *And1 = BinaryOperator::CreateAnd(Op0I->getOperand(0),
6233 Mask);
6234 Instruction *And2 = BinaryOperator::CreateAnd(Op1I->getOperand(0),
6235 Mask);
6236 InsertNewInstBefore(And1, I);
6237 InsertNewInstBefore(And2, I);
6238 return new ICmpInst(I.getPredicate(), And1, And2);
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006239 }
6240 }
6241 break;
6242 }
6243 }
6244 }
6245 }
6246
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006247 // ~x < ~y --> y < x
6248 { Value *A, *B;
6249 if (match(Op0, m_Not(m_Value(A))) &&
6250 match(Op1, m_Not(m_Value(B))))
6251 return new ICmpInst(I.getPredicate(), B, A);
6252 }
6253
Chris Lattner65b72ba2006-09-18 04:22:48 +00006254 if (I.isEquality()) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006255 Value *A, *B, *C, *D;
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006256
6257 // -x == -y --> x == y
6258 if (match(Op0, m_Neg(m_Value(A))) &&
6259 match(Op1, m_Neg(m_Value(B))))
6260 return new ICmpInst(I.getPredicate(), A, B);
6261
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006262 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
6263 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6264 Value *OtherVal = A == Op1 ? B : A;
6265 return new ICmpInst(I.getPredicate(), OtherVal,
6266 Constant::getNullValue(A->getType()));
6267 }
6268
6269 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
6270 // A^c1 == C^c2 --> A == C^(c1^c2)
Chris Lattnercb504b92008-11-16 05:38:51 +00006271 ConstantInt *C1, *C2;
6272 if (match(B, m_ConstantInt(C1)) &&
6273 match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
6274 Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
6275 Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
6276 return new ICmpInst(I.getPredicate(), A,
6277 InsertNewInstBefore(Xor, I));
6278 }
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006279
6280 // A^B == A^D -> B == D
6281 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6282 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6283 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6284 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
6285 }
6286 }
6287
6288 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
6289 (A == Op0 || B == Op0)) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00006290 // A == (A^B) -> B == 0
6291 Value *OtherVal = A == Op0 ? B : A;
Reid Spencere4d87aa2006-12-23 06:05:41 +00006292 return new ICmpInst(I.getPredicate(), OtherVal,
6293 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006294 }
Chris Lattnercb504b92008-11-16 05:38:51 +00006295
6296 // (A-B) == A -> B == 0
6297 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
6298 return new ICmpInst(I.getPredicate(), B,
6299 Constant::getNullValue(B->getType()));
6300
6301 // A == (A-B) -> B == 0
6302 if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006303 return new ICmpInst(I.getPredicate(), B,
6304 Constant::getNullValue(B->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006305
Chris Lattner9c2328e2006-11-14 06:06:06 +00006306 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6307 if (Op0->hasOneUse() && Op1->hasOneUse() &&
6308 match(Op0, m_And(m_Value(A), m_Value(B))) &&
6309 match(Op1, m_And(m_Value(C), m_Value(D)))) {
6310 Value *X = 0, *Y = 0, *Z = 0;
6311
6312 if (A == C) {
6313 X = B; Y = D; Z = A;
6314 } else if (A == D) {
6315 X = B; Y = C; Z = A;
6316 } else if (B == C) {
6317 X = A; Y = D; Z = B;
6318 } else if (B == D) {
6319 X = A; Y = C; Z = B;
6320 }
6321
6322 if (X) { // Build (X^Y) & Z
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006323 Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
6324 Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
Chris Lattner9c2328e2006-11-14 06:06:06 +00006325 I.setOperand(0, Op1);
6326 I.setOperand(1, Constant::getNullValue(Op1->getType()));
6327 return &I;
6328 }
6329 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006330 }
Chris Lattner7e708292002-06-25 16:13:24 +00006331 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006332}
6333
Chris Lattner562ef782007-06-20 23:46:26 +00006334
6335/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6336/// and CmpRHS are both known to be integer constants.
6337Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6338 ConstantInt *DivRHS) {
6339 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6340 const APInt &CmpRHSV = CmpRHS->getValue();
6341
6342 // FIXME: If the operand types don't match the type of the divide
6343 // then don't attempt this transform. The code below doesn't have the
6344 // logic to deal with a signed divide and an unsigned compare (and
6345 // vice versa). This is because (x /s C1) <s C2 produces different
6346 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6347 // (x /u C1) <u C2. Simply casting the operands and result won't
6348 // work. :( The if statement below tests that condition and bails
6349 // if it finds it.
6350 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6351 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6352 return 0;
6353 if (DivRHS->isZero())
Chris Lattner1dbfd482007-06-21 18:11:19 +00006354 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattnera6321b42008-10-11 22:55:00 +00006355 if (DivIsSigned && DivRHS->isAllOnesValue())
6356 return 0; // The overflow computation also screws up here
6357 if (DivRHS->isOne())
6358 return 0; // Not worth bothering, and eliminates some funny cases
6359 // with INT_MIN.
Chris Lattner562ef782007-06-20 23:46:26 +00006360
6361 // Compute Prod = CI * DivRHS. We are essentially solving an equation
6362 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
6363 // C2 (CI). By solving for X we can turn this into a range check
6364 // instead of computing a divide.
6365 ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
6366
6367 // Determine if the product overflows by seeing if the product is
6368 // not equal to the divide. Make sure we do the same kind of divide
6369 // as in the LHS instruction that we're folding.
6370 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6371 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
6372
6373 // Get the ICmp opcode
Chris Lattner1dbfd482007-06-21 18:11:19 +00006374 ICmpInst::Predicate Pred = ICI.getPredicate();
Chris Lattner562ef782007-06-20 23:46:26 +00006375
Chris Lattner1dbfd482007-06-21 18:11:19 +00006376 // Figure out the interval that is being checked. For example, a comparison
6377 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
6378 // Compute this interval based on the constants involved and the signedness of
6379 // the compare/divide. This computes a half-open interval, keeping track of
6380 // whether either value in the interval overflows. After analysis each
6381 // overflow variable is set to 0 if it's corresponding bound variable is valid
6382 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6383 int LoOverflow = 0, HiOverflow = 0;
6384 ConstantInt *LoBound = 0, *HiBound = 0;
6385
Chris Lattner562ef782007-06-20 23:46:26 +00006386 if (!DivIsSigned) { // udiv
Chris Lattner1dbfd482007-06-21 18:11:19 +00006387 // e.g. X/5 op 3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00006388 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006389 HiOverflow = LoOverflow = ProdOV;
6390 if (!HiOverflow)
6391 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
Dan Gohman76491272008-02-13 22:09:18 +00006392 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006393 if (CmpRHSV == 0) { // (X / pos) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006394 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Chris Lattner562ef782007-06-20 23:46:26 +00006395 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
6396 HiBound = DivRHS;
Dan Gohman76491272008-02-13 22:09:18 +00006397 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006398 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
6399 HiOverflow = LoOverflow = ProdOV;
6400 if (!HiOverflow)
6401 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006402 } else { // (X / pos) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00006403 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Chris Lattner562ef782007-06-20 23:46:26 +00006404 HiBound = AddOne(Prod);
Chris Lattnera6321b42008-10-11 22:55:00 +00006405 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6406 if (!LoOverflow) {
6407 ConstantInt* DivNeg = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6408 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg,
6409 true) ? -1 : 0;
6410 }
Chris Lattner562ef782007-06-20 23:46:26 +00006411 }
Dan Gohman76491272008-02-13 22:09:18 +00006412 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006413 if (CmpRHSV == 0) { // (X / neg) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006414 // e.g. X/-5 op 0 --> [-4, 5)
Chris Lattner562ef782007-06-20 23:46:26 +00006415 LoBound = AddOne(DivRHS);
6416 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006417 if (HiBound == DivRHS) { // -INTMIN = INTMIN
6418 HiOverflow = 1; // [INTMIN+1, overflow)
6419 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
6420 }
Dan Gohman76491272008-02-13 22:09:18 +00006421 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006422 // e.g. X/-5 op 3 --> [-19, -14)
Chris Lattnera6321b42008-10-11 22:55:00 +00006423 HiBound = AddOne(Prod);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006424 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006425 if (!LoOverflow)
Chris Lattnera6321b42008-10-11 22:55:00 +00006426 LoOverflow = AddWithOverflow(LoBound, HiBound, DivRHS, true) ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006427 } else { // (X / neg) op neg
Chris Lattnera6321b42008-10-11 22:55:00 +00006428 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
6429 LoOverflow = HiOverflow = ProdOV;
Dan Gohman7f85fbd2008-09-11 00:25:00 +00006430 if (!HiOverflow)
6431 HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006432 }
6433
Chris Lattner1dbfd482007-06-21 18:11:19 +00006434 // Dividing by a negative swaps the condition. LT <-> GT
6435 Pred = ICmpInst::getSwappedPredicate(Pred);
Chris Lattner562ef782007-06-20 23:46:26 +00006436 }
6437
6438 Value *X = DivI->getOperand(0);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006439 switch (Pred) {
Chris Lattner562ef782007-06-20 23:46:26 +00006440 default: assert(0 && "Unhandled icmp opcode!");
6441 case ICmpInst::ICMP_EQ:
6442 if (LoOverflow && HiOverflow)
6443 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6444 else if (HiOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00006445 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006446 ICmpInst::ICMP_UGE, X, LoBound);
6447 else if (LoOverflow)
6448 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
6449 ICmpInst::ICMP_ULT, X, HiBound);
6450 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006451 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006452 case ICmpInst::ICMP_NE:
6453 if (LoOverflow && HiOverflow)
6454 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6455 else if (HiOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00006456 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006457 ICmpInst::ICMP_ULT, X, LoBound);
6458 else if (LoOverflow)
6459 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
6460 ICmpInst::ICMP_UGE, X, HiBound);
6461 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006462 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006463 case ICmpInst::ICMP_ULT:
6464 case ICmpInst::ICMP_SLT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006465 if (LoOverflow == +1) // Low bound is greater than input range.
6466 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6467 if (LoOverflow == -1) // Low bound is less than input range.
Chris Lattner562ef782007-06-20 23:46:26 +00006468 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00006469 return new ICmpInst(Pred, X, LoBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006470 case ICmpInst::ICMP_UGT:
6471 case ICmpInst::ICMP_SGT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006472 if (HiOverflow == +1) // High bound greater than input range.
Chris Lattner562ef782007-06-20 23:46:26 +00006473 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00006474 else if (HiOverflow == -1) // High bound less than input range.
6475 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6476 if (Pred == ICmpInst::ICMP_UGT)
Chris Lattner562ef782007-06-20 23:46:26 +00006477 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
6478 else
6479 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
6480 }
6481}
6482
6483
Chris Lattner01deb9d2007-04-03 17:43:25 +00006484/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6485///
6486Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6487 Instruction *LHSI,
6488 ConstantInt *RHS) {
6489 const APInt &RHSV = RHS->getValue();
6490
6491 switch (LHSI->getOpcode()) {
Chris Lattnera80d6682009-01-09 07:47:06 +00006492 case Instruction::Trunc:
6493 if (ICI.isEquality() && LHSI->hasOneUse()) {
6494 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6495 // of the high bits truncated out of x are known.
6496 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6497 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6498 APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6499 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6500 ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6501
6502 // If all the high bits are known, we can do this xform.
6503 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6504 // Pull in the high bits from known-ones set.
6505 APInt NewRHS(RHS->getValue());
6506 NewRHS.zext(SrcBits);
6507 NewRHS |= KnownOne;
6508 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6509 ConstantInt::get(NewRHS));
6510 }
6511 }
6512 break;
6513
Duncan Sands0091bf22007-04-04 06:42:45 +00006514 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
Chris Lattner01deb9d2007-04-03 17:43:25 +00006515 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6516 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6517 // fold the xor.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006518 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6519 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006520 Value *CompareVal = LHSI->getOperand(0);
6521
6522 // If the sign bit of the XorCST is not set, there is no change to
6523 // the operation, just stop using the Xor.
6524 if (!XorCST->getValue().isNegative()) {
6525 ICI.setOperand(0, CompareVal);
6526 AddToWorkList(LHSI);
6527 return &ICI;
6528 }
6529
6530 // Was the old condition true if the operand is positive?
6531 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6532
6533 // If so, the new one isn't.
6534 isTrueIfPositive ^= true;
6535
6536 if (isTrueIfPositive)
6537 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
6538 else
6539 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
6540 }
Nick Lewycky4333f492009-01-31 21:30:05 +00006541
6542 if (LHSI->hasOneUse()) {
6543 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6544 if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6545 const APInt &SignBit = XorCST->getValue();
6546 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6547 ? ICI.getUnsignedPredicate()
6548 : ICI.getSignedPredicate();
6549 return new ICmpInst(Pred, LHSI->getOperand(0),
6550 ConstantInt::get(RHSV ^ SignBit));
6551 }
6552
6553 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006554 if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
Nick Lewycky4333f492009-01-31 21:30:05 +00006555 const APInt &NotSignBit = XorCST->getValue();
6556 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6557 ? ICI.getUnsignedPredicate()
6558 : ICI.getSignedPredicate();
6559 Pred = ICI.getSwappedPredicate(Pred);
6560 return new ICmpInst(Pred, LHSI->getOperand(0),
6561 ConstantInt::get(RHSV ^ NotSignBit));
6562 }
6563 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006564 }
6565 break;
6566 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
6567 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6568 LHSI->getOperand(0)->hasOneUse()) {
6569 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6570
6571 // If the LHS is an AND of a truncating cast, we can widen the
6572 // and/compare to be the input width without changing the value
6573 // produced, eliminating a cast.
6574 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6575 // We can do this transformation if either the AND constant does not
6576 // have its sign bit set or if it is an equality comparison.
6577 // Extending a relational comparison when we're checking the sign
6578 // bit would not work.
6579 if (Cast->hasOneUse() &&
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00006580 (ICI.isEquality() ||
6581 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006582 uint32_t BitWidth =
6583 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6584 APInt NewCST = AndCST->getValue();
6585 NewCST.zext(BitWidth);
6586 APInt NewCI = RHSV;
6587 NewCI.zext(BitWidth);
6588 Instruction *NewAnd =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006589 BinaryOperator::CreateAnd(Cast->getOperand(0),
Chris Lattner01deb9d2007-04-03 17:43:25 +00006590 ConstantInt::get(NewCST),LHSI->getName());
6591 InsertNewInstBefore(NewAnd, ICI);
6592 return new ICmpInst(ICI.getPredicate(), NewAnd,
6593 ConstantInt::get(NewCI));
6594 }
6595 }
6596
6597 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6598 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
6599 // happens a LOT in code produced by the C front-end, for bitfield
6600 // access.
6601 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6602 if (Shift && !Shift->isShift())
6603 Shift = 0;
6604
6605 ConstantInt *ShAmt;
6606 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6607 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
6608 const Type *AndTy = AndCST->getType(); // Type of the and.
6609
6610 // We can fold this as long as we can't shift unknown bits
6611 // into the mask. This can only happen with signed shift
6612 // rights, as they sign-extend.
6613 if (ShAmt) {
6614 bool CanFold = Shift->isLogicalShift();
6615 if (!CanFold) {
6616 // To test for the bad case of the signed shr, see if any
6617 // of the bits shifted in could be tested after the mask.
6618 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6619 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6620
6621 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6622 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
6623 AndCST->getValue()) == 0)
6624 CanFold = true;
6625 }
6626
6627 if (CanFold) {
6628 Constant *NewCst;
6629 if (Shift->getOpcode() == Instruction::Shl)
6630 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
6631 else
6632 NewCst = ConstantExpr::getShl(RHS, ShAmt);
6633
6634 // Check to see if we are shifting out any of the bits being
6635 // compared.
6636 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
6637 // If we shifted bits out, the fold is not going to work out.
6638 // As a special case, check to see if this means that the
6639 // result is always true or false now.
6640 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6641 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6642 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6643 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6644 } else {
6645 ICI.setOperand(1, NewCst);
6646 Constant *NewAndCST;
6647 if (Shift->getOpcode() == Instruction::Shl)
6648 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
6649 else
6650 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
6651 LHSI->setOperand(1, NewAndCST);
6652 LHSI->setOperand(0, Shift->getOperand(0));
6653 AddToWorkList(Shift); // Shift is dead.
6654 AddUsesToWorkList(ICI);
6655 return &ICI;
6656 }
6657 }
6658 }
6659
6660 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
6661 // preferable because it allows the C<<Y expression to be hoisted out
6662 // of a loop if Y is invariant and X is not.
6663 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
Chris Lattnere8e49212009-03-25 00:28:58 +00006664 ICI.isEquality() && !Shift->isArithmeticShift() &&
6665 !isa<Constant>(Shift->getOperand(0))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006666 // Compute C << Y.
6667 Value *NS;
6668 if (Shift->getOpcode() == Instruction::LShr) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006669 NS = BinaryOperator::CreateShl(AndCST,
Chris Lattner01deb9d2007-04-03 17:43:25 +00006670 Shift->getOperand(1), "tmp");
6671 } else {
6672 // Insert a logical shift.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006673 NS = BinaryOperator::CreateLShr(AndCST,
Chris Lattner01deb9d2007-04-03 17:43:25 +00006674 Shift->getOperand(1), "tmp");
6675 }
6676 InsertNewInstBefore(cast<Instruction>(NS), ICI);
6677
6678 // Compute X & (C << Y).
6679 Instruction *NewAnd =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006680 BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006681 InsertNewInstBefore(NewAnd, ICI);
6682
6683 ICI.setOperand(0, NewAnd);
6684 return &ICI;
6685 }
6686 }
6687 break;
6688
Chris Lattnera0141b92007-07-15 20:42:37 +00006689 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6690 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6691 if (!ShAmt) break;
6692
6693 uint32_t TypeBits = RHSV.getBitWidth();
6694
6695 // Check that the shift amount is in range. If not, don't perform
6696 // undefined shifts. When the shift is visited it will be
6697 // simplified.
6698 if (ShAmt->uge(TypeBits))
6699 break;
6700
6701 if (ICI.isEquality()) {
6702 // If we are comparing against bits always shifted out, the
6703 // comparison cannot succeed.
6704 Constant *Comp =
6705 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
6706 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6707 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6708 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6709 return ReplaceInstUsesWith(ICI, Cst);
6710 }
6711
6712 if (LHSI->hasOneUse()) {
6713 // Otherwise strength reduce the shift into an and.
6714 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6715 Constant *Mask =
6716 ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006717
Chris Lattnera0141b92007-07-15 20:42:37 +00006718 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006719 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattnera0141b92007-07-15 20:42:37 +00006720 Mask, LHSI->getName()+".mask");
6721 Value *And = InsertNewInstBefore(AndI, ICI);
6722 return new ICmpInst(ICI.getPredicate(), And,
6723 ConstantInt::get(RHSV.lshr(ShAmtVal)));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006724 }
6725 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006726
6727 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6728 bool TrueIfSigned = false;
6729 if (LHSI->hasOneUse() &&
6730 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6731 // (X << 31) <s 0 --> (X&1) != 0
6732 Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
6733 (TypeBits-ShAmt->getZExtValue()-1));
6734 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006735 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattnera0141b92007-07-15 20:42:37 +00006736 Mask, LHSI->getName()+".mask");
6737 Value *And = InsertNewInstBefore(AndI, ICI);
6738
6739 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6740 And, Constant::getNullValue(And->getType()));
6741 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006742 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006743 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006744
6745 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Chris Lattnera0141b92007-07-15 20:42:37 +00006746 case Instruction::AShr: {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006747 // Only handle equality comparisons of shift-by-constant.
Chris Lattnera0141b92007-07-15 20:42:37 +00006748 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006749 if (!ShAmt || !ICI.isEquality()) break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006750
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006751 // Check that the shift amount is in range. If not, don't perform
6752 // undefined shifts. When the shift is visited it will be
6753 // simplified.
6754 uint32_t TypeBits = RHSV.getBitWidth();
6755 if (ShAmt->uge(TypeBits))
6756 break;
6757
6758 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattnera0141b92007-07-15 20:42:37 +00006759
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006760 // If we are comparing against bits always shifted out, the
6761 // comparison cannot succeed.
6762 APInt Comp = RHSV << ShAmtVal;
6763 if (LHSI->getOpcode() == Instruction::LShr)
6764 Comp = Comp.lshr(ShAmtVal);
6765 else
6766 Comp = Comp.ashr(ShAmtVal);
6767
6768 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6769 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6770 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6771 return ReplaceInstUsesWith(ICI, Cst);
6772 }
6773
6774 // Otherwise, check to see if the bits shifted out are known to be zero.
6775 // If so, we can compare against the unshifted value:
6776 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengf30752c2008-04-23 00:38:06 +00006777 if (LHSI->hasOneUse() &&
6778 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006779 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
6780 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6781 ConstantExpr::getShl(RHS, ShAmt));
6782 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006783
Evan Chengf30752c2008-04-23 00:38:06 +00006784 if (LHSI->hasOneUse()) {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006785 // Otherwise strength reduce the shift into an and.
6786 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
6787 Constant *Mask = ConstantInt::get(Val);
Chris Lattnera0141b92007-07-15 20:42:37 +00006788
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006789 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006790 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006791 Mask, LHSI->getName()+".mask");
6792 Value *And = InsertNewInstBefore(AndI, ICI);
6793 return new ICmpInst(ICI.getPredicate(), And,
6794 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006795 }
6796 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006797 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006798
6799 case Instruction::SDiv:
6800 case Instruction::UDiv:
6801 // Fold: icmp pred ([us]div X, C1), C2 -> range test
6802 // Fold this div into the comparison, producing a range check.
6803 // Determine, based on the divide type, what the range is being
6804 // checked. If there is an overflow on the low or high side, remember
6805 // it, otherwise compute the range [low, hi) bounding the new value.
6806 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner562ef782007-06-20 23:46:26 +00006807 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6808 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6809 DivRHS))
6810 return R;
Chris Lattner01deb9d2007-04-03 17:43:25 +00006811 break;
Nick Lewycky5be29202008-02-03 16:33:09 +00006812
6813 case Instruction::Add:
6814 // Fold: icmp pred (add, X, C1), C2
6815
6816 if (!ICI.isEquality()) {
6817 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6818 if (!LHSC) break;
6819 const APInt &LHSV = LHSC->getValue();
6820
6821 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6822 .subtract(LHSV);
6823
6824 if (ICI.isSignedPredicate()) {
6825 if (CR.getLower().isSignBit()) {
6826 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
6827 ConstantInt::get(CR.getUpper()));
6828 } else if (CR.getUpper().isSignBit()) {
6829 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
6830 ConstantInt::get(CR.getLower()));
6831 }
6832 } else {
6833 if (CR.getLower().isMinValue()) {
6834 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
6835 ConstantInt::get(CR.getUpper()));
6836 } else if (CR.getUpper().isMinValue()) {
6837 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
6838 ConstantInt::get(CR.getLower()));
6839 }
6840 }
6841 }
6842 break;
Chris Lattner01deb9d2007-04-03 17:43:25 +00006843 }
6844
6845 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6846 if (ICI.isEquality()) {
6847 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6848
6849 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
6850 // the second operand is a constant, simplify a bit.
6851 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6852 switch (BO->getOpcode()) {
6853 case Instruction::SRem:
6854 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6855 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6856 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6857 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
6858 Instruction *NewRem =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006859 BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
Chris Lattner01deb9d2007-04-03 17:43:25 +00006860 BO->getName());
6861 InsertNewInstBefore(NewRem, ICI);
6862 return new ICmpInst(ICI.getPredicate(), NewRem,
6863 Constant::getNullValue(BO->getType()));
6864 }
6865 }
6866 break;
6867 case Instruction::Add:
6868 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
6869 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6870 if (BO->hasOneUse())
6871 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6872 Subtract(RHS, BOp1C));
6873 } else if (RHSV == 0) {
6874 // Replace ((add A, B) != 0) with (A != -B) if A or B is
6875 // efficiently invertible, or if the add has just this one use.
6876 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
6877
6878 if (Value *NegVal = dyn_castNegVal(BOp1))
6879 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
6880 else if (Value *NegVal = dyn_castNegVal(BOp0))
6881 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
6882 else if (BO->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006883 Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006884 InsertNewInstBefore(Neg, ICI);
6885 Neg->takeName(BO);
6886 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
6887 }
6888 }
6889 break;
6890 case Instruction::Xor:
6891 // For the xor case, we can xor two constants together, eliminating
6892 // the explicit xor.
6893 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
6894 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6895 ConstantExpr::getXor(RHS, BOC));
6896
6897 // FALLTHROUGH
6898 case Instruction::Sub:
6899 // Replace (([sub|xor] A, B) != 0) with (A != B)
6900 if (RHSV == 0)
6901 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6902 BO->getOperand(1));
6903 break;
6904
6905 case Instruction::Or:
6906 // If bits are being or'd in that are not present in the constant we
6907 // are comparing against, then the comparison could never succeed!
6908 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
6909 Constant *NotCI = ConstantExpr::getNot(RHS);
6910 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
6911 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6912 isICMP_NE));
6913 }
6914 break;
6915
6916 case Instruction::And:
6917 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6918 // If bits are being compared against that are and'd out, then the
6919 // comparison can never succeed!
6920 if ((RHSV & ~BOC->getValue()) != 0)
6921 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6922 isICMP_NE));
6923
6924 // If we have ((X & C) == C), turn it into ((X & C) != 0).
6925 if (RHS == BOC && RHSV.isPowerOf2())
6926 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
6927 ICmpInst::ICMP_NE, LHSI,
6928 Constant::getNullValue(RHS->getType()));
6929
6930 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattner833f25d2008-06-02 01:29:46 +00006931 if (BOC->getValue().isSignBit()) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006932 Value *X = BO->getOperand(0);
6933 Constant *Zero = Constant::getNullValue(X->getType());
6934 ICmpInst::Predicate pred = isICMP_NE ?
6935 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
6936 return new ICmpInst(pred, X, Zero);
6937 }
6938
6939 // ((X & ~7) == 0) --> X < 8
6940 if (RHSV == 0 && isHighOnes(BOC)) {
6941 Value *X = BO->getOperand(0);
6942 Constant *NegX = ConstantExpr::getNeg(BOC);
6943 ICmpInst::Predicate pred = isICMP_NE ?
6944 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
6945 return new ICmpInst(pred, X, NegX);
6946 }
6947 }
6948 default: break;
6949 }
6950 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
6951 // Handle icmp {eq|ne} <intrinsic>, intcst.
6952 if (II->getIntrinsicID() == Intrinsic::bswap) {
6953 AddToWorkList(II);
6954 ICI.setOperand(0, II->getOperand(1));
6955 ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
6956 return &ICI;
6957 }
6958 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006959 }
6960 return 0;
6961}
6962
6963/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
6964/// We only handle extending casts so far.
6965///
Reid Spencere4d87aa2006-12-23 06:05:41 +00006966Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
6967 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +00006968 Value *LHSCIOp = LHSCI->getOperand(0);
6969 const Type *SrcTy = LHSCIOp->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00006970 const Type *DestTy = LHSCI->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00006971 Value *RHSCIOp;
6972
Chris Lattner8c756c12007-05-05 22:41:33 +00006973 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
6974 // integer type is the same size as the pointer type.
6975 if (LHSCI->getOpcode() == Instruction::PtrToInt &&
6976 getTargetData().getPointerSizeInBits() ==
6977 cast<IntegerType>(DestTy)->getBitWidth()) {
6978 Value *RHSOp = 0;
6979 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Chris Lattner6f6f5122007-05-06 07:24:03 +00006980 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Chris Lattner8c756c12007-05-05 22:41:33 +00006981 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
6982 RHSOp = RHSC->getOperand(0);
6983 // If the pointer types don't match, insert a bitcast.
6984 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner6d0339d2008-01-13 22:23:22 +00006985 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
Chris Lattner8c756c12007-05-05 22:41:33 +00006986 }
6987
6988 if (RHSOp)
6989 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
6990 }
6991
6992 // The code below only handles extension cast instructions, so far.
6993 // Enforce this.
Reid Spencere4d87aa2006-12-23 06:05:41 +00006994 if (LHSCI->getOpcode() != Instruction::ZExt &&
6995 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattnerb352fa52005-01-17 03:20:02 +00006996 return 0;
6997
Reid Spencere4d87aa2006-12-23 06:05:41 +00006998 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
6999 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattner484d3cf2005-04-24 06:59:08 +00007000
Reid Spencere4d87aa2006-12-23 06:05:41 +00007001 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00007002 // Not an extension from the same type?
7003 RHSCIOp = CI->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007004 if (RHSCIOp->getType() != LHSCIOp->getType())
7005 return 0;
Chris Lattnera5c5e772007-01-13 23:11:38 +00007006
Nick Lewycky4189a532008-01-28 03:48:02 +00007007 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Chris Lattnera5c5e772007-01-13 23:11:38 +00007008 // and the other is a zext), then we can't handle this.
7009 if (CI->getOpcode() != LHSCI->getOpcode())
7010 return 0;
7011
Nick Lewycky4189a532008-01-28 03:48:02 +00007012 // Deal with equality cases early.
7013 if (ICI.isEquality())
7014 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
7015
7016 // A signed comparison of sign extended values simplifies into a
7017 // signed comparison.
7018 if (isSignedCmp && isSignedExt)
7019 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
7020
7021 // The other three cases all fold into an unsigned comparison.
7022 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer6731d5c2004-11-28 21:31:15 +00007023 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007024
Reid Spencere4d87aa2006-12-23 06:05:41 +00007025 // If we aren't dealing with a constant on the RHS, exit early
7026 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7027 if (!CI)
7028 return 0;
7029
7030 // Compute the constant that would happen if we truncated to SrcTy then
7031 // reextended to DestTy.
7032 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
7033 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
7034
7035 // If the re-extended constant didn't change...
7036 if (Res2 == CI) {
7037 // Make sure that sign of the Cmp and the sign of the Cast are the same.
7038 // For example, we might have:
7039 // %A = sext short %X to uint
7040 // %B = icmp ugt uint %A, 1330
7041 // It is incorrect to transform this into
7042 // %B = icmp ugt short %X, 1330
7043 // because %A may have negative value.
7044 //
Chris Lattnerf2991842008-07-11 04:09:09 +00007045 // However, we allow this when the compare is EQ/NE, because they are
7046 // signless.
7047 if (isSignedExt == isSignedCmp || ICI.isEquality())
Reid Spencere4d87aa2006-12-23 06:05:41 +00007048 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
Chris Lattnerf2991842008-07-11 04:09:09 +00007049 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +00007050 }
7051
7052 // The re-extended constant changed so the constant cannot be represented
7053 // in the shorter type. Consequently, we cannot emit a simple comparison.
7054
7055 // First, handle some easy cases. We know the result cannot be equal at this
7056 // point so handle the ICI.isEquality() cases
7057 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007058 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00007059 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007060 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00007061
7062 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7063 // should have been folded away previously and not enter in here.
7064 Value *Result;
7065 if (isSignedCmp) {
7066 // We're performing a signed comparison.
Reid Spencer0460fb32007-03-22 20:36:03 +00007067 if (cast<ConstantInt>(CI)->getValue().isNegative())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007068 Result = ConstantInt::getFalse(); // X < (small) --> false
Reid Spencere4d87aa2006-12-23 06:05:41 +00007069 else
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007070 Result = ConstantInt::getTrue(); // X < (large) --> true
Reid Spencere4d87aa2006-12-23 06:05:41 +00007071 } else {
7072 // We're performing an unsigned comparison.
7073 if (isSignedExt) {
7074 // We're performing an unsigned comp with a sign extended value.
7075 // This is true if the input is >= 0. [aka >s -1]
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007076 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007077 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
7078 NegOne, ICI.getName()), ICI);
7079 } else {
7080 // Unsigned extend & unsigned compare -> always true.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007081 Result = ConstantInt::getTrue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00007082 }
7083 }
7084
7085 // Finally, return the value computed.
7086 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
Chris Lattnerf2991842008-07-11 04:09:09 +00007087 ICI.getPredicate() == ICmpInst::ICMP_SLT)
Reid Spencere4d87aa2006-12-23 06:05:41 +00007088 return ReplaceInstUsesWith(ICI, Result);
Chris Lattnerf2991842008-07-11 04:09:09 +00007089
7090 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
7091 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7092 "ICmp should be folded!");
7093 if (Constant *CI = dyn_cast<Constant>(Result))
7094 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
7095 return BinaryOperator::CreateNot(Result);
Chris Lattner484d3cf2005-04-24 06:59:08 +00007096}
Chris Lattner3f5b8772002-05-06 16:14:14 +00007097
Reid Spencer832254e2007-02-02 02:16:23 +00007098Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7099 return commonShiftTransforms(I);
7100}
7101
7102Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7103 return commonShiftTransforms(I);
7104}
7105
7106Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner348f6652007-12-06 01:59:46 +00007107 if (Instruction *R = commonShiftTransforms(I))
7108 return R;
7109
7110 Value *Op0 = I.getOperand(0);
7111
7112 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
7113 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7114 if (CSI->isAllOnesValue())
7115 return ReplaceInstUsesWith(I, CSI);
7116
7117 // See if we can turn a signed shr into an unsigned shr.
Chris Lattnerb44b3662009-03-18 16:32:19 +00007118 if (!isa<VectorType>(I.getType())) {
7119 if (MaskedValueIsZero(Op0,
Chris Lattner348f6652007-12-06 01:59:46 +00007120 APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
Chris Lattnerb44b3662009-03-18 16:32:19 +00007121 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
Dan Gohman0001e562009-02-24 02:00:40 +00007122
Chris Lattnerb44b3662009-03-18 16:32:19 +00007123 // Arithmetic shifting an all-sign-bit value is a no-op.
7124 unsigned NumSignBits = ComputeNumSignBits(Op0);
7125 if (NumSignBits == Op0->getType()->getPrimitiveSizeInBits())
7126 return ReplaceInstUsesWith(I, Op0);
7127 }
Dan Gohman0001e562009-02-24 02:00:40 +00007128
Chris Lattner348f6652007-12-06 01:59:46 +00007129 return 0;
Reid Spencer832254e2007-02-02 02:16:23 +00007130}
7131
7132Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7133 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00007134 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00007135
7136 // shl X, 0 == X and shr X, 0 == X
7137 // shl 0, X == 0 and shr 0, X == 0
Reid Spencer832254e2007-02-02 02:16:23 +00007138 if (Op1 == Constant::getNullValue(Op1->getType()) ||
Chris Lattner233f7dc2002-08-12 21:17:25 +00007139 Op0 == Constant::getNullValue(Op0->getType()))
7140 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007141
Reid Spencere4d87aa2006-12-23 06:05:41 +00007142 if (isa<UndefValue>(Op0)) {
7143 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00007144 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007145 else // undef << X -> 0, undef >>u X -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00007146 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7147 }
7148 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00007149 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
7150 return ReplaceInstUsesWith(I, Op0);
7151 else // X << undef, X >>u undef -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00007152 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007153 }
7154
Chris Lattner2eefe512004-04-09 19:05:30 +00007155 // Try to fold constant and into select arguments.
7156 if (isa<Constant>(Op0))
7157 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00007158 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00007159 return R;
7160
Reid Spencerb83eb642006-10-20 07:07:24 +00007161 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00007162 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7163 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007164 return 0;
7165}
7166
Reid Spencerb83eb642006-10-20 07:07:24 +00007167Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00007168 BinaryOperator &I) {
Chris Lattner4598c942009-01-31 08:24:16 +00007169 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007170
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007171 // See if we can simplify any instructions used by the instruction whose sole
7172 // purpose is to compute bits we don't care about.
Reid Spencerb35ae032007-03-23 18:46:34 +00007173 uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
Chris Lattner886ab6c2009-01-31 08:15:18 +00007174 if (SimplifyDemandedInstructionBits(I))
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007175 return &I;
7176
Chris Lattner4d5542c2006-01-06 07:12:35 +00007177 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
7178 // of a signed value.
7179 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007180 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00007181 if (I.getOpcode() != Instruction::AShr)
Chris Lattner4d5542c2006-01-06 07:12:35 +00007182 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
7183 else {
Chris Lattner0737c242007-02-02 05:29:55 +00007184 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007185 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00007186 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007187 }
7188
7189 // ((X*C1) << C2) == (X * (C1 << C2))
7190 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7191 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7192 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007193 return BinaryOperator::CreateMul(BO->getOperand(0),
Chris Lattner4d5542c2006-01-06 07:12:35 +00007194 ConstantExpr::getShl(BOOp, Op1));
7195
7196 // Try to fold constant and into select arguments.
7197 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7198 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7199 return R;
7200 if (isa<PHINode>(Op0))
7201 if (Instruction *NV = FoldOpIntoPhi(I))
7202 return NV;
7203
Chris Lattner8999dd32007-12-22 09:07:47 +00007204 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7205 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7206 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7207 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7208 // place. Don't try to do this transformation in this case. Also, we
7209 // require that the input operand is a shift-by-constant so that we have
7210 // confidence that the shifts will get folded together. We could do this
7211 // xform in more cases, but it is unlikely to be profitable.
7212 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
7213 isa<ConstantInt>(TrOp->getOperand(1))) {
7214 // Okay, we'll do this xform. Make the shift of shift.
7215 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007216 Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
Chris Lattner8999dd32007-12-22 09:07:47 +00007217 I.getName());
7218 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
7219
7220 // For logical shifts, the truncation has the effect of making the high
7221 // part of the register be zeros. Emulate this by inserting an AND to
7222 // clear the top bits as needed. This 'and' will usually be zapped by
7223 // other xforms later if dead.
7224 unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
7225 unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
7226 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7227
7228 // The mask we constructed says what the trunc would do if occurring
7229 // between the shifts. We want to know the effect *after* the second
7230 // shift. We know that it is a logical shift by a constant, so adjust the
7231 // mask as appropriate.
7232 if (I.getOpcode() == Instruction::Shl)
7233 MaskV <<= Op1->getZExtValue();
7234 else {
7235 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7236 MaskV = MaskV.lshr(Op1->getZExtValue());
7237 }
7238
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007239 Instruction *And = BinaryOperator::CreateAnd(NSh, ConstantInt::get(MaskV),
Chris Lattner8999dd32007-12-22 09:07:47 +00007240 TI->getName());
7241 InsertNewInstBefore(And, I); // shift1 & 0x00FF
7242
7243 // Return the value truncated to the interesting size.
7244 return new TruncInst(And, I.getType());
7245 }
7246 }
7247
Chris Lattner4d5542c2006-01-06 07:12:35 +00007248 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00007249 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7250 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7251 Value *V1, *V2;
7252 ConstantInt *CC;
7253 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00007254 default: break;
7255 case Instruction::Add:
7256 case Instruction::And:
7257 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00007258 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007259 // These operators commute.
7260 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007261 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
Chris Lattnercb504b92008-11-16 05:38:51 +00007262 match(Op0BO->getOperand(1), m_Shr(m_Value(V1), m_Specific(Op1)))){
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007263 Instruction *YS = BinaryOperator::CreateShl(
Chris Lattner4d5542c2006-01-06 07:12:35 +00007264 Op0BO->getOperand(0), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00007265 Op0BO->getName());
7266 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007267 Instruction *X =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007268 BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007269 Op0BO->getOperand(1)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007270 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00007271 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007272 return BinaryOperator::CreateAnd(X, ConstantInt::get(
Zhou Sheng90b96812007-03-30 05:45:18 +00007273 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007274 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007275
Chris Lattner150f12a2005-09-18 06:30:59 +00007276 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00007277 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00007278 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00007279 match(Op0BOOp1,
Chris Lattnercb504b92008-11-16 05:38:51 +00007280 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
7281 m_ConstantInt(CC))) &&
7282 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007283 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007284 Op0BO->getOperand(0), Op1,
7285 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007286 InsertNewInstBefore(YS, I); // (Y << C)
7287 Instruction *XM =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007288 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00007289 V1->getName()+".mask");
7290 InsertNewInstBefore(XM, I); // X & (CC << C)
7291
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007292 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Chris Lattner150f12a2005-09-18 06:30:59 +00007293 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00007294 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007295
Reid Spencera07cb7d2007-02-02 14:41:37 +00007296 // FALL THROUGH.
7297 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007298 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007299 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
Chris Lattnercb504b92008-11-16 05:38:51 +00007300 match(Op0BO->getOperand(0), m_Shr(m_Value(V1), m_Specific(Op1)))){
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007301 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007302 Op0BO->getOperand(1), Op1,
7303 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007304 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007305 Instruction *X =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007306 BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007307 Op0BO->getOperand(0)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007308 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00007309 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007310 return BinaryOperator::CreateAnd(X, ConstantInt::get(
Zhou Sheng90b96812007-03-30 05:45:18 +00007311 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007312 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007313
Chris Lattner13d4ab42006-05-31 21:14:00 +00007314 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007315 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7316 match(Op0BO->getOperand(0),
7317 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner4d5542c2006-01-06 07:12:35 +00007318 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007319 cast<BinaryOperator>(Op0BO->getOperand(0))
7320 ->getOperand(0)->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007321 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007322 Op0BO->getOperand(1), Op1,
7323 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007324 InsertNewInstBefore(YS, I); // (Y << C)
7325 Instruction *XM =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007326 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00007327 V1->getName()+".mask");
7328 InsertNewInstBefore(XM, I); // X & (CC << C)
7329
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007330 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00007331 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007332
Chris Lattner11021cb2005-09-18 05:12:10 +00007333 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00007334 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007335 }
7336
7337
7338 // If the operand is an bitwise operator with a constant RHS, and the
7339 // shift is the only use, we can pull it out of the shift.
7340 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7341 bool isValid = true; // Valid only for And, Or, Xor
7342 bool highBitSet = false; // Transform if high bit of constant set?
7343
7344 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00007345 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00007346 case Instruction::Add:
7347 isValid = isLeftShift;
7348 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00007349 case Instruction::Or:
7350 case Instruction::Xor:
7351 highBitSet = false;
7352 break;
7353 case Instruction::And:
7354 highBitSet = true;
7355 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007356 }
7357
7358 // If this is a signed shift right, and the high bit is modified
7359 // by the logical operation, do not perform the transformation.
7360 // The highBitSet boolean indicates the value of the high bit of
7361 // the constant which would cause it to be modified for this
7362 // operation.
7363 //
Chris Lattnerc95ba442007-12-06 06:25:04 +00007364 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Shenge9e03f62007-03-28 15:02:20 +00007365 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007366
7367 if (isValid) {
7368 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
7369
7370 Instruction *NewShift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007371 BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007372 InsertNewInstBefore(NewShift, I);
Chris Lattner6934a042007-02-11 01:23:03 +00007373 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007374
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007375 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Chris Lattner4d5542c2006-01-06 07:12:35 +00007376 NewRHS);
7377 }
7378 }
7379 }
7380 }
7381
Chris Lattnerad0124c2006-01-06 07:52:12 +00007382 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00007383 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7384 if (ShiftOp && !ShiftOp->isShift())
7385 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007386
Reid Spencerb83eb642006-10-20 07:07:24 +00007387 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00007388 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007389 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7390 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00007391 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7392 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
7393 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00007394
Zhou Sheng4351c642007-04-02 08:20:41 +00007395 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Chris Lattnerb87056f2007-02-05 00:57:54 +00007396
7397 const IntegerType *Ty = cast<IntegerType>(I.getType());
7398
7399 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00007400 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattner344c7c52009-03-20 22:41:15 +00007401 // If this is oversized composite shift, then unsigned shifts get 0, ashr
7402 // saturates.
7403 if (AmtSum >= TypeBits) {
7404 if (I.getOpcode() != Instruction::AShr)
7405 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7406 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
7407 }
7408
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007409 return BinaryOperator::Create(I.getOpcode(), X,
Chris Lattnerb87056f2007-02-05 00:57:54 +00007410 ConstantInt::get(Ty, AmtSum));
7411 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
7412 I.getOpcode() == Instruction::AShr) {
Chris Lattner344c7c52009-03-20 22:41:15 +00007413 if (AmtSum >= TypeBits)
7414 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7415
Chris Lattnerb87056f2007-02-05 00:57:54 +00007416 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007417 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007418 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
7419 I.getOpcode() == Instruction::LShr) {
7420 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
Chris Lattner344c7c52009-03-20 22:41:15 +00007421 if (AmtSum >= TypeBits)
7422 AmtSum = TypeBits-1;
7423
Chris Lattnerb87056f2007-02-05 00:57:54 +00007424 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007425 BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007426 InsertNewInstBefore(Shift, I);
7427
Zhou Shenge9e03f62007-03-28 15:02:20 +00007428 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007429 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007430 }
7431
Chris Lattnerb87056f2007-02-05 00:57:54 +00007432 // Okay, if we get here, one shift must be left, and the other shift must be
7433 // right. See if the amounts are equal.
7434 if (ShiftAmt1 == ShiftAmt2) {
7435 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7436 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00007437 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007438 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007439 }
7440 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7441 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00007442 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007443 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007444 }
7445 // We can simplify ((X << C) >>s C) into a trunc + sext.
7446 // NOTE: we could do this for any C, but that would make 'unusual' integer
7447 // types. For now, just stick to ones well-supported by the code
7448 // generators.
7449 const Type *SExtType = 0;
7450 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00007451 case 1 :
7452 case 8 :
7453 case 16 :
7454 case 32 :
7455 case 64 :
7456 case 128:
7457 SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
7458 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007459 default: break;
7460 }
7461 if (SExtType) {
7462 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7463 InsertNewInstBefore(NewTrunc, I);
7464 return new SExtInst(NewTrunc, Ty);
7465 }
7466 // Otherwise, we can't handle it yet.
7467 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00007468 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007469
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007470 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007471 if (I.getOpcode() == Instruction::Shl) {
7472 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7473 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnere8d56c52006-01-07 01:32:28 +00007474 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007475 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00007476 InsertNewInstBefore(Shift, I);
7477
Reid Spencer55702aa2007-03-25 21:11:44 +00007478 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007479 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007480 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007481
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007482 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007483 if (I.getOpcode() == Instruction::LShr) {
7484 assert(ShiftOp->getOpcode() == Instruction::Shl);
7485 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007486 BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007487 InsertNewInstBefore(Shift, I);
Chris Lattnerad0124c2006-01-06 07:52:12 +00007488
Reid Spencerd5e30f02007-03-26 17:18:58 +00007489 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007490 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00007491 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007492
7493 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7494 } else {
7495 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00007496 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007497
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007498 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007499 if (I.getOpcode() == Instruction::Shl) {
7500 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7501 ShiftOp->getOpcode() == Instruction::AShr);
7502 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007503 BinaryOperator::Create(ShiftOp->getOpcode(), X,
Chris Lattnerb87056f2007-02-05 00:57:54 +00007504 ConstantInt::get(Ty, ShiftDiff));
7505 InsertNewInstBefore(Shift, I);
7506
Reid Spencer55702aa2007-03-25 21:11:44 +00007507 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007508 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007509 }
7510
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007511 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007512 if (I.getOpcode() == Instruction::LShr) {
7513 assert(ShiftOp->getOpcode() == Instruction::Shl);
7514 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007515 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007516 InsertNewInstBefore(Shift, I);
7517
Reid Spencer68d27cf2007-03-26 23:45:51 +00007518 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007519 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007520 }
7521
7522 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00007523 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00007524 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007525 return 0;
7526}
7527
Chris Lattnera1be5662002-05-02 17:06:02 +00007528
Chris Lattnercfd65102005-10-29 04:36:15 +00007529/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7530/// expression. If so, decompose it, returning some value X, such that Val is
7531/// X*Scale+Offset.
7532///
7533static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Jeff Cohen86796be2007-04-04 16:58:57 +00007534 int &Offset) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007535 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00007536 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007537 Offset = CI->getZExtValue();
Chris Lattner6a94de22007-10-12 05:30:59 +00007538 Scale = 0;
Reid Spencerc5b206b2006-12-31 05:48:39 +00007539 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattner6a94de22007-10-12 05:30:59 +00007540 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7541 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7542 if (I->getOpcode() == Instruction::Shl) {
7543 // This is a value scaled by '1 << the shift amt'.
7544 Scale = 1U << RHS->getZExtValue();
7545 Offset = 0;
7546 return I->getOperand(0);
7547 } else if (I->getOpcode() == Instruction::Mul) {
7548 // This value is scaled by 'RHS'.
7549 Scale = RHS->getZExtValue();
7550 Offset = 0;
7551 return I->getOperand(0);
7552 } else if (I->getOpcode() == Instruction::Add) {
7553 // We have X+C. Check to see if we really have (X*C2)+C1,
7554 // where C1 is divisible by C2.
7555 unsigned SubScale;
7556 Value *SubVal =
7557 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
7558 Offset += RHS->getZExtValue();
7559 Scale = SubScale;
7560 return SubVal;
Chris Lattnercfd65102005-10-29 04:36:15 +00007561 }
7562 }
7563 }
7564
7565 // Otherwise, we can't look past this.
7566 Scale = 1;
7567 Offset = 0;
7568 return Val;
7569}
7570
7571
Chris Lattnerb3f83972005-10-24 06:03:58 +00007572/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7573/// try to eliminate the cast by moving the type information into the alloc.
Chris Lattnerd3e28342007-04-27 17:44:50 +00007574Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Chris Lattnerb3f83972005-10-24 06:03:58 +00007575 AllocationInst &AI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007576 const PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007577
Chris Lattnerb53c2382005-10-24 06:22:12 +00007578 // Remove any uses of AI that are dead.
7579 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner535014f2007-02-15 22:52:10 +00007580
Chris Lattnerb53c2382005-10-24 06:22:12 +00007581 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7582 Instruction *User = cast<Instruction>(*UI++);
7583 if (isInstructionTriviallyDead(User)) {
7584 while (UI != E && *UI == User)
7585 ++UI; // If this instruction uses AI more than once, don't break UI.
7586
Chris Lattnerb53c2382005-10-24 06:22:12 +00007587 ++NumDeadInst;
Bill Wendlingb7427032006-11-26 09:46:52 +00007588 DOUT << "IC: DCE: " << *User;
Chris Lattnerf22a5c62007-03-02 19:59:19 +00007589 EraseInstFromFunction(*User);
Chris Lattnerb53c2382005-10-24 06:22:12 +00007590 }
7591 }
7592
Chris Lattnerb3f83972005-10-24 06:03:58 +00007593 // Get the type really allocated and the type casted to.
7594 const Type *AllocElTy = AI.getAllocatedType();
7595 const Type *CastElTy = PTy->getElementType();
7596 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007597
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007598 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7599 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00007600 if (CastElTyAlign < AllocElTyAlign) return 0;
7601
Chris Lattner39387a52005-10-24 06:35:18 +00007602 // If the allocation has multiple uses, only promote it if we are strictly
7603 // increasing the alignment of the resultant allocation. If we keep it the
Dale Johannesena0a66372009-03-05 00:39:02 +00007604 // same, we open the door to infinite loops of various kinds. (A reference
7605 // from a dbg.declare doesn't count as a use for this purpose.)
7606 if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7607 CastElTyAlign == AllocElTyAlign) return 0;
Chris Lattner39387a52005-10-24 06:35:18 +00007608
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00007609 uint64_t AllocElTySize = TD->getTypePaddedSize(AllocElTy);
7610 uint64_t CastElTySize = TD->getTypePaddedSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007611 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007612
Chris Lattner455fcc82005-10-29 03:19:53 +00007613 // See if we can satisfy the modulus by pulling a scale out of the array
7614 // size argument.
Jeff Cohen86796be2007-04-04 16:58:57 +00007615 unsigned ArraySizeScale;
7616 int ArrayOffset;
Chris Lattnercfd65102005-10-29 04:36:15 +00007617 Value *NumElements = // See if the array size is a decomposable linear expr.
7618 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
7619
Chris Lattner455fcc82005-10-29 03:19:53 +00007620 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7621 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00007622 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7623 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00007624
Chris Lattner455fcc82005-10-29 03:19:53 +00007625 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7626 Value *Amt = 0;
7627 if (Scale == 1) {
7628 Amt = NumElements;
7629 } else {
Reid Spencerb83eb642006-10-20 07:07:24 +00007630 // If the allocation size is constant, form a constant mul expression
Reid Spencerc5b206b2006-12-31 05:48:39 +00007631 Amt = ConstantInt::get(Type::Int32Ty, Scale);
7632 if (isa<ConstantInt>(NumElements))
Zhou Sheng4a1822a2007-04-02 13:45:30 +00007633 Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
Reid Spencerb83eb642006-10-20 07:07:24 +00007634 // otherwise multiply the amount and the number of elements
Chris Lattner46d232d2009-03-17 17:55:15 +00007635 else {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007636 Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
Chris Lattner455fcc82005-10-29 03:19:53 +00007637 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattner8142b0a2005-10-27 06:12:00 +00007638 }
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007639 }
7640
Jeff Cohen86796be2007-04-04 16:58:57 +00007641 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7642 Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007643 Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
Chris Lattnercfd65102005-10-29 04:36:15 +00007644 Amt = InsertNewInstBefore(Tmp, AI);
7645 }
7646
Chris Lattnerb3f83972005-10-24 06:03:58 +00007647 AllocationInst *New;
7648 if (isa<MallocInst>(AI))
Chris Lattner6934a042007-02-11 01:23:03 +00007649 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007650 else
Chris Lattner6934a042007-02-11 01:23:03 +00007651 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007652 InsertNewInstBefore(New, AI);
Chris Lattner6934a042007-02-11 01:23:03 +00007653 New->takeName(&AI);
Chris Lattner39387a52005-10-24 06:35:18 +00007654
Dale Johannesena0a66372009-03-05 00:39:02 +00007655 // If the allocation has one real use plus a dbg.declare, just remove the
7656 // declare.
7657 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7658 EraseInstFromFunction(*DI);
7659 }
7660 // If the allocation has multiple real uses, insert a cast and change all
7661 // things that used it to use the new cast. This will also hack on CI, but it
7662 // will die soon.
7663 else if (!AI.hasOneUse()) {
Chris Lattner39387a52005-10-24 06:35:18 +00007664 AddUsesToWorkList(AI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007665 // New is the allocation instruction, pointer typed. AI is the original
7666 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7667 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner39387a52005-10-24 06:35:18 +00007668 InsertNewInstBefore(NewCast, AI);
7669 AI.replaceAllUsesWith(NewCast);
7670 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00007671 return ReplaceInstUsesWith(CI, New);
7672}
7673
Chris Lattner70074e02006-05-13 02:06:03 +00007674/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerc739cd62007-03-03 05:27:34 +00007675/// and return it as type Ty without inserting any new casts and without
7676/// changing the computed value. This is used by code that tries to decide
7677/// whether promoting or shrinking integer operations to wider or smaller types
7678/// will allow us to eliminate a truncate or extend.
7679///
7680/// This is a truncation operation if Ty is smaller than V->getType(), or an
7681/// extension operation if Ty is larger.
Chris Lattner8114b712008-06-18 04:00:49 +00007682///
7683/// If CastOpc is a truncation, then Ty will be a type smaller than V. We
7684/// should return true if trunc(V) can be computed by computing V in the smaller
7685/// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
7686/// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7687/// efficiently truncated.
7688///
7689/// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7690/// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7691/// the final result.
Evan Cheng4e56ab22009-01-16 02:11:43 +00007692bool InstCombiner::CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
7693 unsigned CastOpc,
7694 int &NumCastsRemoved){
Chris Lattnerc739cd62007-03-03 05:27:34 +00007695 // We can always evaluate constants in another type.
7696 if (isa<ConstantInt>(V))
7697 return true;
Chris Lattner70074e02006-05-13 02:06:03 +00007698
7699 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007700 if (!I) return false;
7701
7702 const IntegerType *OrigTy = cast<IntegerType>(V->getType());
Chris Lattner70074e02006-05-13 02:06:03 +00007703
Chris Lattner951626b2007-08-02 06:11:14 +00007704 // If this is an extension or truncate, we can often eliminate it.
7705 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7706 // If this is a cast from the destination type, we can trivially eliminate
7707 // it, and this will remove a cast overall.
7708 if (I->getOperand(0)->getType() == Ty) {
7709 // If the first operand is itself a cast, and is eliminable, do not count
7710 // this as an eliminable cast. We would prefer to eliminate those two
7711 // casts first.
Chris Lattner8114b712008-06-18 04:00:49 +00007712 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
Chris Lattner951626b2007-08-02 06:11:14 +00007713 ++NumCastsRemoved;
7714 return true;
7715 }
7716 }
7717
7718 // We can't extend or shrink something that has multiple uses: doing so would
7719 // require duplicating the instruction in general, which isn't profitable.
7720 if (!I->hasOneUse()) return false;
7721
Evan Chengf35fd542009-01-15 17:01:23 +00007722 unsigned Opc = I->getOpcode();
7723 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007724 case Instruction::Add:
7725 case Instruction::Sub:
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007726 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00007727 case Instruction::And:
7728 case Instruction::Or:
7729 case Instruction::Xor:
7730 // These operators can all arbitrarily be extended or truncated.
Chris Lattner951626b2007-08-02 06:11:14 +00007731 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007732 NumCastsRemoved) &&
Chris Lattner951626b2007-08-02 06:11:14 +00007733 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007734 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007735
Chris Lattner46b96052006-11-29 07:18:39 +00007736 case Instruction::Shl:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007737 // If we are truncating the result of this SHL, and if it's a shift of a
7738 // constant amount, we can always perform a SHL in a smaller type.
7739 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007740 uint32_t BitWidth = Ty->getBitWidth();
7741 if (BitWidth < OrigTy->getBitWidth() &&
7742 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattner951626b2007-08-02 06:11:14 +00007743 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007744 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007745 }
7746 break;
7747 case Instruction::LShr:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007748 // If this is a truncate of a logical shr, we can truncate it to a smaller
7749 // lshr iff we know that the bits we would otherwise be shifting in are
7750 // already zeros.
7751 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007752 uint32_t OrigBitWidth = OrigTy->getBitWidth();
7753 uint32_t BitWidth = Ty->getBitWidth();
7754 if (BitWidth < OrigBitWidth &&
Chris Lattnerc739cd62007-03-03 05:27:34 +00007755 MaskedValueIsZero(I->getOperand(0),
Zhou Sheng302748d2007-03-30 17:20:39 +00007756 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7757 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattner951626b2007-08-02 06:11:14 +00007758 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007759 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007760 }
7761 }
Chris Lattner46b96052006-11-29 07:18:39 +00007762 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007763 case Instruction::ZExt:
7764 case Instruction::SExt:
Chris Lattner951626b2007-08-02 06:11:14 +00007765 case Instruction::Trunc:
7766 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner5543a852007-08-02 17:23:38 +00007767 // can safely replace it. Note that replacing it does not reduce the number
7768 // of casts in the input.
Evan Chengf35fd542009-01-15 17:01:23 +00007769 if (Opc == CastOpc)
7770 return true;
7771
7772 // sext (zext ty1), ty2 -> zext ty2
Evan Cheng661d9c32009-01-15 17:09:07 +00007773 if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
Chris Lattner70074e02006-05-13 02:06:03 +00007774 return true;
Reid Spencer3da59db2006-11-27 01:05:10 +00007775 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007776 case Instruction::Select: {
7777 SelectInst *SI = cast<SelectInst>(I);
7778 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007779 NumCastsRemoved) &&
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007780 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007781 NumCastsRemoved);
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007782 }
Chris Lattner8114b712008-06-18 04:00:49 +00007783 case Instruction::PHI: {
7784 // We can change a phi if we can change all operands.
7785 PHINode *PN = cast<PHINode>(I);
7786 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
7787 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007788 NumCastsRemoved))
Chris Lattner8114b712008-06-18 04:00:49 +00007789 return false;
7790 return true;
7791 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007792 default:
Chris Lattner70074e02006-05-13 02:06:03 +00007793 // TODO: Can handle more cases here.
7794 break;
7795 }
7796
7797 return false;
7798}
7799
7800/// EvaluateInDifferentType - Given an expression that
7801/// CanEvaluateInDifferentType returns true for, actually insert the code to
7802/// evaluate the expression.
Reid Spencerc55b2432006-12-13 18:21:21 +00007803Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerc739cd62007-03-03 05:27:34 +00007804 bool isSigned) {
Chris Lattner70074e02006-05-13 02:06:03 +00007805 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencerc55b2432006-12-13 18:21:21 +00007806 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Chris Lattner70074e02006-05-13 02:06:03 +00007807
7808 // Otherwise, it must be an instruction.
7809 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00007810 Instruction *Res = 0;
Evan Chengf35fd542009-01-15 17:01:23 +00007811 unsigned Opc = I->getOpcode();
7812 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007813 case Instruction::Add:
7814 case Instruction::Sub:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00007815 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00007816 case Instruction::And:
7817 case Instruction::Or:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007818 case Instruction::Xor:
Chris Lattner46b96052006-11-29 07:18:39 +00007819 case Instruction::AShr:
7820 case Instruction::LShr:
7821 case Instruction::Shl: {
Reid Spencerc55b2432006-12-13 18:21:21 +00007822 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007823 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Evan Chengf35fd542009-01-15 17:01:23 +00007824 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Chris Lattner46b96052006-11-29 07:18:39 +00007825 break;
7826 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007827 case Instruction::Trunc:
7828 case Instruction::ZExt:
7829 case Instruction::SExt:
Reid Spencer3da59db2006-11-27 01:05:10 +00007830 // If the source type of the cast is the type we're trying for then we can
Chris Lattner951626b2007-08-02 06:11:14 +00007831 // just return the source. There's no need to insert it because it is not
7832 // new.
Chris Lattner70074e02006-05-13 02:06:03 +00007833 if (I->getOperand(0)->getType() == Ty)
7834 return I->getOperand(0);
7835
Chris Lattner8114b712008-06-18 04:00:49 +00007836 // Otherwise, must be the same type of cast, so just reinsert a new one.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007837 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
Chris Lattner8114b712008-06-18 04:00:49 +00007838 Ty);
Chris Lattner951626b2007-08-02 06:11:14 +00007839 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007840 case Instruction::Select: {
7841 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7842 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
7843 Res = SelectInst::Create(I->getOperand(0), True, False);
7844 break;
7845 }
Chris Lattner8114b712008-06-18 04:00:49 +00007846 case Instruction::PHI: {
7847 PHINode *OPN = cast<PHINode>(I);
7848 PHINode *NPN = PHINode::Create(Ty);
7849 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
7850 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
7851 NPN->addIncoming(V, OPN->getIncomingBlock(i));
7852 }
7853 Res = NPN;
7854 break;
7855 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007856 default:
Chris Lattner70074e02006-05-13 02:06:03 +00007857 // TODO: Can handle more cases here.
7858 assert(0 && "Unreachable!");
7859 break;
7860 }
7861
Chris Lattner8114b712008-06-18 04:00:49 +00007862 Res->takeName(I);
Chris Lattner70074e02006-05-13 02:06:03 +00007863 return InsertNewInstBefore(Res, *I);
7864}
7865
Reid Spencer3da59db2006-11-27 01:05:10 +00007866/// @brief Implement the transforms common to all CastInst visitors.
7867Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00007868 Value *Src = CI.getOperand(0);
7869
Dan Gohman23d9d272007-05-11 21:10:54 +00007870 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
Reid Spencer3da59db2006-11-27 01:05:10 +00007871 // eliminate it now.
Chris Lattner6e7ba452005-01-01 16:22:27 +00007872 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00007873 if (Instruction::CastOps opc =
7874 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
7875 // The first cast (CSrc) is eliminable so we need to fix up or replace
7876 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007877 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner8fd217c2002-08-02 20:00:25 +00007878 }
7879 }
Chris Lattnera710ddc2004-05-25 04:29:21 +00007880
Reid Spencer3da59db2006-11-27 01:05:10 +00007881 // If we are casting a select then fold the cast into the select
Chris Lattner6e7ba452005-01-01 16:22:27 +00007882 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
7883 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
7884 return NV;
Reid Spencer3da59db2006-11-27 01:05:10 +00007885
7886 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner4e998b22004-09-29 05:07:12 +00007887 if (isa<PHINode>(Src))
7888 if (Instruction *NV = FoldOpIntoPhi(CI))
7889 return NV;
Chris Lattner9fb92132006-04-12 18:09:35 +00007890
Reid Spencer3da59db2006-11-27 01:05:10 +00007891 return 0;
7892}
7893
Chris Lattner46cd5a12009-01-09 05:44:56 +00007894/// FindElementAtOffset - Given a type and a constant offset, determine whether
7895/// or not there is a sequence of GEP indices into the type that will land us at
Chris Lattner3914f722009-01-24 01:00:13 +00007896/// the specified offset. If so, fill them into NewIndices and return the
7897/// resultant element type, otherwise return null.
7898static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset,
7899 SmallVectorImpl<Value*> &NewIndices,
7900 const TargetData *TD) {
7901 if (!Ty->isSized()) return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00007902
7903 // Start with the index over the outer type. Note that the type size
7904 // might be zero (even if the offset isn't zero) if the indexed type
7905 // is something like [0 x {int, int}]
7906 const Type *IntPtrTy = TD->getIntPtrType();
7907 int64_t FirstIdx = 0;
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00007908 if (int64_t TySize = TD->getTypePaddedSize(Ty)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00007909 FirstIdx = Offset/TySize;
Chris Lattner31a69cb2009-01-11 20:41:36 +00007910 Offset -= FirstIdx*TySize;
Chris Lattner46cd5a12009-01-09 05:44:56 +00007911
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00007912 // Handle hosts where % returns negative instead of values [0..TySize).
Chris Lattner46cd5a12009-01-09 05:44:56 +00007913 if (Offset < 0) {
7914 --FirstIdx;
7915 Offset += TySize;
7916 assert(Offset >= 0);
7917 }
7918 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
7919 }
7920
7921 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
7922
7923 // Index into the types. If we fail, set OrigBase to null.
7924 while (Offset) {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00007925 // Indexing into tail padding between struct/array elements.
7926 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
Chris Lattner3914f722009-01-24 01:00:13 +00007927 return 0;
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00007928
Chris Lattner46cd5a12009-01-09 05:44:56 +00007929 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
7930 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00007931 assert(Offset < (int64_t)SL->getSizeInBytes() &&
7932 "Offset must stay within the indexed type");
7933
Chris Lattner46cd5a12009-01-09 05:44:56 +00007934 unsigned Elt = SL->getElementContainingOffset(Offset);
7935 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
7936
7937 Offset -= SL->getElementOffset(Elt);
7938 Ty = STy->getElementType(Elt);
Chris Lattner1c412d92009-01-11 20:23:52 +00007939 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00007940 uint64_t EltSize = TD->getTypePaddedSize(AT->getElementType());
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00007941 assert(EltSize && "Cannot index into a zero-sized array");
7942 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
7943 Offset %= EltSize;
Chris Lattner1c412d92009-01-11 20:23:52 +00007944 Ty = AT->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00007945 } else {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00007946 // Otherwise, we can't index into the middle of this atomic type, bail.
Chris Lattner3914f722009-01-24 01:00:13 +00007947 return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00007948 }
7949 }
7950
Chris Lattner3914f722009-01-24 01:00:13 +00007951 return Ty;
Chris Lattner46cd5a12009-01-09 05:44:56 +00007952}
7953
Chris Lattnerd3e28342007-04-27 17:44:50 +00007954/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
7955Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
7956 Value *Src = CI.getOperand(0);
7957
Chris Lattnerd3e28342007-04-27 17:44:50 +00007958 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner9bc14642007-04-28 00:57:34 +00007959 // If casting the result of a getelementptr instruction with no offset, turn
7960 // this into a cast of the original pointer!
Chris Lattnerd3e28342007-04-27 17:44:50 +00007961 if (GEP->hasAllZeroIndices()) {
7962 // Changing the cast operand is usually not a good idea but it is safe
7963 // here because the pointer operand is being replaced with another
7964 // pointer operand so the opcode doesn't need to change.
Chris Lattner9bc14642007-04-28 00:57:34 +00007965 AddToWorkList(GEP);
Chris Lattnerd3e28342007-04-27 17:44:50 +00007966 CI.setOperand(0, GEP->getOperand(0));
7967 return &CI;
7968 }
Chris Lattner9bc14642007-04-28 00:57:34 +00007969
7970 // If the GEP has a single use, and the base pointer is a bitcast, and the
7971 // GEP computes a constant offset, see if we can convert these three
7972 // instructions into fewer. This typically happens with unions and other
7973 // non-type-safe code.
7974 if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
7975 if (GEP->hasAllConstantIndices()) {
7976 // We are guaranteed to get a constant from EmitGEPOffset.
7977 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
7978 int64_t Offset = OffsetV->getSExtValue();
7979
7980 // Get the base pointer input of the bitcast, and the type it points to.
7981 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
7982 const Type *GEPIdxTy =
7983 cast<PointerType>(OrigBase->getType())->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00007984 SmallVector<Value*, 8> NewIndices;
7985 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD)) {
7986 // If we were able to index down into an element, create the GEP
7987 // and bitcast the result. This eliminates one bitcast, potentially
7988 // two.
7989 Instruction *NGEP = GetElementPtrInst::Create(OrigBase,
7990 NewIndices.begin(),
7991 NewIndices.end(), "");
7992 InsertNewInstBefore(NGEP, CI);
7993 NGEP->takeName(GEP);
Chris Lattner9bc14642007-04-28 00:57:34 +00007994
Chris Lattner46cd5a12009-01-09 05:44:56 +00007995 if (isa<BitCastInst>(CI))
7996 return new BitCastInst(NGEP, CI.getType());
7997 assert(isa<PtrToIntInst>(CI));
7998 return new PtrToIntInst(NGEP, CI.getType());
Chris Lattner9bc14642007-04-28 00:57:34 +00007999 }
8000 }
8001 }
Chris Lattnerd3e28342007-04-27 17:44:50 +00008002 }
8003
8004 return commonCastTransforms(CI);
8005}
8006
Chris Lattnerddfa57b2009-04-08 05:41:03 +00008007/// isSafeIntegerType - Return true if this is a basic integer type, not a crazy
8008/// type like i42. We don't want to introduce operations on random non-legal
8009/// integer types where they don't already exist in the code. In the future,
8010/// we should consider making this based off target-data, so that 32-bit targets
8011/// won't get i64 operations etc.
8012static bool isSafeIntegerType(const Type *Ty) {
8013 switch (Ty->getPrimitiveSizeInBits()) {
8014 case 8:
8015 case 16:
8016 case 32:
8017 case 64:
8018 return true;
8019 default:
8020 return false;
8021 }
8022}
Chris Lattnerd3e28342007-04-27 17:44:50 +00008023
Chris Lattnerc739cd62007-03-03 05:27:34 +00008024/// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
8025/// integer types. This function implements the common transforms for all those
Reid Spencer3da59db2006-11-27 01:05:10 +00008026/// cases.
8027/// @brief Implement the transforms common to CastInst with integer operands
8028Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8029 if (Instruction *Result = commonCastTransforms(CI))
8030 return Result;
8031
8032 Value *Src = CI.getOperand(0);
8033 const Type *SrcTy = Src->getType();
8034 const Type *DestTy = CI.getType();
Zhou Sheng4351c642007-04-02 08:20:41 +00008035 uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
8036 uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00008037
Reid Spencer3da59db2006-11-27 01:05:10 +00008038 // See if we can simplify any instructions used by the LHS whose sole
8039 // purpose is to compute bits we don't care about.
Chris Lattner886ab6c2009-01-31 08:15:18 +00008040 if (SimplifyDemandedInstructionBits(CI))
Reid Spencer3da59db2006-11-27 01:05:10 +00008041 return &CI;
8042
8043 // If the source isn't an instruction or has more than one use then we
8044 // can't do anything more.
Reid Spencere4d87aa2006-12-23 06:05:41 +00008045 Instruction *SrcI = dyn_cast<Instruction>(Src);
8046 if (!SrcI || !Src->hasOneUse())
Reid Spencer3da59db2006-11-27 01:05:10 +00008047 return 0;
8048
Chris Lattnerc739cd62007-03-03 05:27:34 +00008049 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00008050 int NumCastsRemoved = 0;
Chris Lattnerc739cd62007-03-03 05:27:34 +00008051 if (!isa<BitCastInst>(CI) &&
Chris Lattnerddfa57b2009-04-08 05:41:03 +00008052 // Only do this if the dest type is a simple type, don't convert the
8053 // expression tree to something weird like i93 unless the source is also
8054 // strange.
8055 (isSafeIntegerType(DestTy) || !isSafeIntegerType(SrcI->getType())) &&
Chris Lattnerc739cd62007-03-03 05:27:34 +00008056 CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
Evan Cheng4e56ab22009-01-16 02:11:43 +00008057 CI.getOpcode(), NumCastsRemoved)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008058 // If this cast is a truncate, evaluting in a different type always
Chris Lattner951626b2007-08-02 06:11:14 +00008059 // eliminates the cast, so it is always a win. If this is a zero-extension,
8060 // we need to do an AND to maintain the clear top-part of the computation,
8061 // so we require that the input have eliminated at least one cast. If this
8062 // is a sign extension, we insert two new casts (to do the extension) so we
Reid Spencer3da59db2006-11-27 01:05:10 +00008063 // require that two casts have been eliminated.
Evan Chengf35fd542009-01-15 17:01:23 +00008064 bool DoXForm = false;
8065 bool JustReplace = false;
Chris Lattnerc739cd62007-03-03 05:27:34 +00008066 switch (CI.getOpcode()) {
8067 default:
8068 // All the others use floating point so we shouldn't actually
8069 // get here because of the check above.
8070 assert(0 && "Unknown cast type");
8071 case Instruction::Trunc:
8072 DoXForm = true;
8073 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00008074 case Instruction::ZExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008075 DoXForm = NumCastsRemoved >= 1;
Chris Lattner39c27ed2009-01-31 19:05:27 +00008076 if (!DoXForm && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00008077 // If it's unnecessary to issue an AND to clear the high bits, it's
8078 // always profitable to do this xform.
Chris Lattner39c27ed2009-01-31 19:05:27 +00008079 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008080 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8081 if (MaskedValueIsZero(TryRes, Mask))
8082 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00008083
8084 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00008085 if (TryI->use_empty())
8086 EraseInstFromFunction(*TryI);
8087 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00008088 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00008089 }
Evan Chengf35fd542009-01-15 17:01:23 +00008090 case Instruction::SExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008091 DoXForm = NumCastsRemoved >= 2;
Chris Lattner39c27ed2009-01-31 19:05:27 +00008092 if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00008093 // If we do not have to emit the truncate + sext pair, then it's always
8094 // profitable to do this xform.
Evan Chengf35fd542009-01-15 17:01:23 +00008095 //
8096 // It's not safe to eliminate the trunc + sext pair if one of the
8097 // eliminated cast is a truncate. e.g.
8098 // t2 = trunc i32 t1 to i16
8099 // t3 = sext i16 t2 to i32
8100 // !=
8101 // i32 t1
Chris Lattner39c27ed2009-01-31 19:05:27 +00008102 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008103 unsigned NumSignBits = ComputeNumSignBits(TryRes);
8104 if (NumSignBits > (DestBitSize - SrcBitSize))
8105 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00008106
8107 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00008108 if (TryI->use_empty())
8109 EraseInstFromFunction(*TryI);
Evan Chengf35fd542009-01-15 17:01:23 +00008110 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00008111 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008112 }
Evan Chengf35fd542009-01-15 17:01:23 +00008113 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008114
8115 if (DoXForm) {
Chris Lattner39c27ed2009-01-31 19:05:27 +00008116 DOUT << "ICE: EvaluateInDifferentType converting expression type to avoid"
8117 << " cast: " << CI;
Reid Spencerc55b2432006-12-13 18:21:21 +00008118 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
8119 CI.getOpcode() == Instruction::SExt);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008120 if (JustReplace)
Chris Lattner39c27ed2009-01-31 19:05:27 +00008121 // Just replace this cast with the result.
8122 return ReplaceInstUsesWith(CI, Res);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008123
Reid Spencer3da59db2006-11-27 01:05:10 +00008124 assert(Res->getType() == DestTy);
8125 switch (CI.getOpcode()) {
8126 default: assert(0 && "Unknown cast type!");
8127 case Instruction::Trunc:
8128 case Instruction::BitCast:
8129 // Just replace this cast with the result.
8130 return ReplaceInstUsesWith(CI, Res);
8131 case Instruction::ZExt: {
Reid Spencer3da59db2006-11-27 01:05:10 +00008132 assert(SrcBitSize < DestBitSize && "Not a zext?");
Evan Cheng4e56ab22009-01-16 02:11:43 +00008133
8134 // If the high bits are already zero, just replace this cast with the
8135 // result.
8136 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8137 if (MaskedValueIsZero(Res, Mask))
8138 return ReplaceInstUsesWith(CI, Res);
8139
8140 // We need to emit an AND to clear the high bits.
Chris Lattnercd1d6d52007-04-02 05:48:58 +00008141 Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
8142 SrcBitSize));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008143 return BinaryOperator::CreateAnd(Res, C);
Reid Spencer3da59db2006-11-27 01:05:10 +00008144 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008145 case Instruction::SExt: {
8146 // If the high bits are already filled with sign bit, just replace this
8147 // cast with the result.
8148 unsigned NumSignBits = ComputeNumSignBits(Res);
8149 if (NumSignBits > (DestBitSize - SrcBitSize))
Evan Chengf35fd542009-01-15 17:01:23 +00008150 return ReplaceInstUsesWith(CI, Res);
8151
Reid Spencer3da59db2006-11-27 01:05:10 +00008152 // We need to emit a cast to truncate, then a cast to sext.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008153 return CastInst::Create(Instruction::SExt,
Reid Spencer17212df2006-12-12 09:18:51 +00008154 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
8155 CI), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00008156 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008157 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008158 }
8159 }
8160
8161 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8162 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8163
8164 switch (SrcI->getOpcode()) {
8165 case Instruction::Add:
8166 case Instruction::Mul:
8167 case Instruction::And:
8168 case Instruction::Or:
8169 case Instruction::Xor:
Chris Lattner01deb9d2007-04-03 17:43:25 +00008170 // If we are discarding information, rewrite.
Reid Spencer3da59db2006-11-27 01:05:10 +00008171 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
8172 // Don't insert two casts if they cannot be eliminated. We allow
8173 // two casts to be inserted if the sizes are the same. This could
8174 // only be converting signedness, which is a noop.
8175 if (DestBitSize == SrcBitSize ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00008176 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
8177 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer7eb76382006-12-13 17:19:09 +00008178 Instruction::CastOps opcode = CI.getOpcode();
Eli Friedmand1fd1da2008-11-30 21:09:11 +00008179 Value *Op0c = InsertCastBefore(opcode, Op0, DestTy, *SrcI);
8180 Value *Op1c = InsertCastBefore(opcode, Op1, DestTy, *SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008181 return BinaryOperator::Create(
Reid Spencer17212df2006-12-12 09:18:51 +00008182 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008183 }
8184 }
8185
8186 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
8187 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
8188 SrcI->getOpcode() == Instruction::Xor &&
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008189 Op1 == ConstantInt::getTrue() &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00008190 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00008191 Value *New = InsertCastBefore(Instruction::ZExt, Op0, DestTy, CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008192 return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
Reid Spencer3da59db2006-11-27 01:05:10 +00008193 }
8194 break;
8195 case Instruction::SDiv:
8196 case Instruction::UDiv:
8197 case Instruction::SRem:
8198 case Instruction::URem:
8199 // If we are just changing the sign, rewrite.
8200 if (DestBitSize == SrcBitSize) {
8201 // Don't insert two casts if they cannot be eliminated. We allow
8202 // two casts to be inserted if the sizes are the same. This could
8203 // only be converting signedness, which is a noop.
Reid Spencere4d87aa2006-12-23 06:05:41 +00008204 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
8205 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00008206 Value *Op0c = InsertCastBefore(Instruction::BitCast,
8207 Op0, DestTy, *SrcI);
8208 Value *Op1c = InsertCastBefore(Instruction::BitCast,
8209 Op1, DestTy, *SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008210 return BinaryOperator::Create(
Reid Spencer3da59db2006-11-27 01:05:10 +00008211 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8212 }
8213 }
8214 break;
8215
8216 case Instruction::Shl:
8217 // Allow changing the sign of the source operand. Do not allow
8218 // changing the size of the shift, UNLESS the shift amount is a
8219 // constant. We must not change variable sized shifts to a smaller
8220 // size, because it is undefined to shift more bits out than exist
8221 // in the value.
8222 if (DestBitSize == SrcBitSize ||
8223 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
Reid Spencer17212df2006-12-12 09:18:51 +00008224 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
8225 Instruction::BitCast : Instruction::Trunc);
Eli Friedmand1fd1da2008-11-30 21:09:11 +00008226 Value *Op0c = InsertCastBefore(opcode, Op0, DestTy, *SrcI);
8227 Value *Op1c = InsertCastBefore(opcode, Op1, DestTy, *SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008228 return BinaryOperator::CreateShl(Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008229 }
8230 break;
8231 case Instruction::AShr:
8232 // If this is a signed shr, and if all bits shifted in are about to be
8233 // truncated off, turn it into an unsigned shr to allow greater
8234 // simplifications.
8235 if (DestBitSize < SrcBitSize &&
8236 isa<ConstantInt>(Op1)) {
Zhou Sheng302748d2007-03-30 17:20:39 +00008237 uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
Reid Spencer3da59db2006-11-27 01:05:10 +00008238 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
8239 // Insert the new logical shift right.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008240 return BinaryOperator::CreateLShr(Op0, Op1);
Reid Spencer3da59db2006-11-27 01:05:10 +00008241 }
8242 }
8243 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008244 }
8245 return 0;
8246}
8247
Chris Lattner8a9f5712007-04-11 06:57:46 +00008248Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008249 if (Instruction *Result = commonIntCastTransforms(CI))
8250 return Result;
8251
8252 Value *Src = CI.getOperand(0);
8253 const Type *Ty = CI.getType();
Zhou Sheng4351c642007-04-02 08:20:41 +00008254 uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
8255 uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
Chris Lattner4f9797d2009-03-24 18:15:30 +00008256
8257 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
8258 if (DestBitWidth == 1) {
8259 Constant *One = ConstantInt::get(Src->getType(), 1);
8260 Src = InsertNewInstBefore(BinaryOperator::CreateAnd(Src, One, "tmp"), CI);
8261 Value *Zero = Constant::getNullValue(Src->getType());
8262 return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
8263 }
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008264
Chris Lattner4f9797d2009-03-24 18:15:30 +00008265 // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8266 ConstantInt *ShAmtV = 0;
8267 Value *ShiftOp = 0;
8268 if (Src->hasOneUse() &&
8269 match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)))) {
8270 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8271
8272 // Get a mask for the bits shifting in.
8273 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8274 if (MaskedValueIsZero(ShiftOp, Mask)) {
8275 if (ShAmt >= DestBitWidth) // All zeros.
8276 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
8277
8278 // Okay, we can shrink this. Truncate the input, then return a new
8279 // shift.
8280 Value *V1 = InsertCastBefore(Instruction::Trunc, ShiftOp, Ty, CI);
8281 Value *V2 = ConstantExpr::getTrunc(ShAmtV, Ty);
8282 return BinaryOperator::CreateLShr(V1, V2);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008283 }
8284 }
8285
8286 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008287}
8288
Evan Chengb98a10e2008-03-24 00:21:34 +00008289/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8290/// in order to eliminate the icmp.
8291Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8292 bool DoXform) {
8293 // If we are just checking for a icmp eq of a single bit and zext'ing it
8294 // to an integer, then shift the bit to the appropriate place and then
8295 // cast to integer to avoid the comparison.
8296 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8297 const APInt &Op1CV = Op1C->getValue();
8298
8299 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
8300 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
8301 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8302 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8303 if (!DoXform) return ICI;
8304
8305 Value *In = ICI->getOperand(0);
8306 Value *Sh = ConstantInt::get(In->getType(),
8307 In->getType()->getPrimitiveSizeInBits()-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008308 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
Evan Chengb98a10e2008-03-24 00:21:34 +00008309 In->getName()+".lobit"),
8310 CI);
8311 if (In->getType() != CI.getType())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008312 In = CastInst::CreateIntegerCast(In, CI.getType(),
Evan Chengb98a10e2008-03-24 00:21:34 +00008313 false/*ZExt*/, "tmp", &CI);
8314
8315 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
8316 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008317 In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
Evan Chengb98a10e2008-03-24 00:21:34 +00008318 In->getName()+".not"),
8319 CI);
8320 }
8321
8322 return ReplaceInstUsesWith(CI, In);
8323 }
8324
8325
8326
8327 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
8328 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8329 // zext (X == 1) to i32 --> X iff X has only the low bit set.
8330 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
8331 // zext (X != 0) to i32 --> X iff X has only the low bit set.
8332 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
8333 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
8334 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8335 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
8336 // This only works for EQ and NE
8337 ICI->isEquality()) {
8338 // If Op1C some other power of two, convert:
8339 uint32_t BitWidth = Op1C->getType()->getBitWidth();
8340 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8341 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8342 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8343
8344 APInt KnownZeroMask(~KnownZero);
8345 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8346 if (!DoXform) return ICI;
8347
8348 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8349 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8350 // (X&4) == 2 --> false
8351 // (X&4) != 2 --> true
8352 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
8353 Res = ConstantExpr::getZExt(Res, CI.getType());
8354 return ReplaceInstUsesWith(CI, Res);
8355 }
8356
8357 uint32_t ShiftAmt = KnownZeroMask.logBase2();
8358 Value *In = ICI->getOperand(0);
8359 if (ShiftAmt) {
8360 // Perform a logical shr by shiftamt.
8361 // Insert the shift to put the result in the low bit.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008362 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
Evan Chengb98a10e2008-03-24 00:21:34 +00008363 ConstantInt::get(In->getType(), ShiftAmt),
8364 In->getName()+".lobit"), CI);
8365 }
8366
8367 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
8368 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008369 In = BinaryOperator::CreateXor(In, One, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00008370 InsertNewInstBefore(cast<Instruction>(In), CI);
8371 }
8372
8373 if (CI.getType() == In->getType())
8374 return ReplaceInstUsesWith(CI, In);
8375 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008376 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chengb98a10e2008-03-24 00:21:34 +00008377 }
8378 }
8379 }
8380
8381 return 0;
8382}
8383
Chris Lattner8a9f5712007-04-11 06:57:46 +00008384Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008385 // If one of the common conversion will work ..
8386 if (Instruction *Result = commonIntCastTransforms(CI))
8387 return Result;
8388
8389 Value *Src = CI.getOperand(0);
8390
Chris Lattnera84f47c2009-02-17 20:47:23 +00008391 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8392 // types and if the sizes are just right we can convert this into a logical
8393 // 'and' which will be much cheaper than the pair of casts.
8394 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
8395 // Get the sizes of the types involved. We know that the intermediate type
8396 // will be smaller than A or C, but don't know the relation between A and C.
8397 Value *A = CSrc->getOperand(0);
8398 unsigned SrcSize = A->getType()->getPrimitiveSizeInBits();
8399 unsigned MidSize = CSrc->getType()->getPrimitiveSizeInBits();
8400 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
8401 // If we're actually extending zero bits, then if
8402 // SrcSize < DstSize: zext(a & mask)
8403 // SrcSize == DstSize: a & mask
8404 // SrcSize > DstSize: trunc(a) & mask
8405 if (SrcSize < DstSize) {
8406 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8407 Constant *AndConst = ConstantInt::get(AndValue);
8408 Instruction *And =
8409 BinaryOperator::CreateAnd(A, AndConst, CSrc->getName()+".mask");
8410 InsertNewInstBefore(And, CI);
8411 return new ZExtInst(And, CI.getType());
8412 } else if (SrcSize == DstSize) {
8413 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8414 return BinaryOperator::CreateAnd(A, ConstantInt::get(AndValue));
8415 } else if (SrcSize > DstSize) {
8416 Instruction *Trunc = new TruncInst(A, CI.getType(), "tmp");
8417 InsertNewInstBefore(Trunc, CI);
8418 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
8419 return BinaryOperator::CreateAnd(Trunc, ConstantInt::get(AndValue));
Reid Spencer3da59db2006-11-27 01:05:10 +00008420 }
8421 }
8422
Evan Chengb98a10e2008-03-24 00:21:34 +00008423 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8424 return transformZExtICmp(ICI, CI);
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00008425
Evan Chengb98a10e2008-03-24 00:21:34 +00008426 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8427 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8428 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8429 // of the (zext icmp) will be transformed.
8430 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8431 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8432 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8433 (transformZExtICmp(LHS, CI, false) ||
8434 transformZExtICmp(RHS, CI, false))) {
8435 Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8436 Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008437 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Chris Lattner66bc3252007-04-11 05:45:39 +00008438 }
Evan Chengb98a10e2008-03-24 00:21:34 +00008439 }
8440
Reid Spencer3da59db2006-11-27 01:05:10 +00008441 return 0;
8442}
8443
Chris Lattner8a9f5712007-04-11 06:57:46 +00008444Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattnerba417832007-04-11 06:12:58 +00008445 if (Instruction *I = commonIntCastTransforms(CI))
8446 return I;
8447
Chris Lattner8a9f5712007-04-11 06:57:46 +00008448 Value *Src = CI.getOperand(0);
8449
Dan Gohman1975d032008-10-30 20:40:10 +00008450 // Canonicalize sign-extend from i1 to a select.
8451 if (Src->getType() == Type::Int1Ty)
8452 return SelectInst::Create(Src,
8453 ConstantInt::getAllOnesValue(CI.getType()),
8454 Constant::getNullValue(CI.getType()));
Dan Gohmanf35c8822008-05-20 21:01:12 +00008455
8456 // See if the value being truncated is already sign extended. If so, just
8457 // eliminate the trunc/sext pair.
8458 if (getOpcode(Src) == Instruction::Trunc) {
8459 Value *Op = cast<User>(Src)->getOperand(0);
8460 unsigned OpBits = cast<IntegerType>(Op->getType())->getBitWidth();
8461 unsigned MidBits = cast<IntegerType>(Src->getType())->getBitWidth();
8462 unsigned DestBits = cast<IntegerType>(CI.getType())->getBitWidth();
8463 unsigned NumSignBits = ComputeNumSignBits(Op);
8464
8465 if (OpBits == DestBits) {
8466 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
8467 // bits, it is already ready.
8468 if (NumSignBits > DestBits-MidBits)
8469 return ReplaceInstUsesWith(CI, Op);
8470 } else if (OpBits < DestBits) {
8471 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
8472 // bits, just sext from i32.
8473 if (NumSignBits > OpBits-MidBits)
8474 return new SExtInst(Op, CI.getType(), "tmp");
8475 } else {
8476 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
8477 // bits, just truncate to i32.
8478 if (NumSignBits > OpBits-MidBits)
8479 return new TruncInst(Op, CI.getType(), "tmp");
8480 }
8481 }
Chris Lattner46bbad22008-08-06 07:35:52 +00008482
8483 // If the input is a shl/ashr pair of a same constant, then this is a sign
8484 // extension from a smaller value. If we could trust arbitrary bitwidth
8485 // integers, we could turn this into a truncate to the smaller bit and then
8486 // use a sext for the whole extension. Since we don't, look deeper and check
8487 // for a truncate. If the source and dest are the same type, eliminate the
8488 // trunc and extend and just do shifts. For example, turn:
8489 // %a = trunc i32 %i to i8
8490 // %b = shl i8 %a, 6
8491 // %c = ashr i8 %b, 6
8492 // %d = sext i8 %c to i32
8493 // into:
8494 // %a = shl i32 %i, 30
8495 // %d = ashr i32 %a, 30
8496 Value *A = 0;
8497 ConstantInt *BA = 0, *CA = 0;
8498 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
8499 m_ConstantInt(CA))) &&
8500 BA == CA && isa<TruncInst>(A)) {
8501 Value *I = cast<TruncInst>(A)->getOperand(0);
8502 if (I->getType() == CI.getType()) {
8503 unsigned MidSize = Src->getType()->getPrimitiveSizeInBits();
8504 unsigned SrcDstSize = CI.getType()->getPrimitiveSizeInBits();
8505 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
8506 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
8507 I = InsertNewInstBefore(BinaryOperator::CreateShl(I, ShAmtV,
8508 CI.getName()), CI);
8509 return BinaryOperator::CreateAShr(I, ShAmtV);
8510 }
8511 }
8512
Chris Lattnerba417832007-04-11 06:12:58 +00008513 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008514}
8515
Chris Lattnerb7530652008-01-27 05:29:54 +00008516/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8517/// in the specified FP type without changing its value.
Chris Lattner02a260a2008-04-20 00:41:09 +00008518static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
Dale Johannesen23a98552008-10-09 23:00:39 +00008519 bool losesInfo;
Chris Lattnerb7530652008-01-27 05:29:54 +00008520 APFloat F = CFP->getValueAPF();
Dale Johannesen23a98552008-10-09 23:00:39 +00008521 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8522 if (!losesInfo)
Chris Lattner02a260a2008-04-20 00:41:09 +00008523 return ConstantFP::get(F);
Chris Lattnerb7530652008-01-27 05:29:54 +00008524 return 0;
8525}
8526
8527/// LookThroughFPExtensions - If this is an fp extension instruction, look
8528/// through it until we get the source value.
8529static Value *LookThroughFPExtensions(Value *V) {
8530 if (Instruction *I = dyn_cast<Instruction>(V))
8531 if (I->getOpcode() == Instruction::FPExt)
8532 return LookThroughFPExtensions(I->getOperand(0));
8533
8534 // If this value is a constant, return the constant in the smallest FP type
8535 // that can accurately represent it. This allows us to turn
8536 // (float)((double)X+2.0) into x+2.0f.
8537 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8538 if (CFP->getType() == Type::PPC_FP128Ty)
8539 return V; // No constant folding of this.
8540 // See if the value can be truncated to float and then reextended.
Chris Lattner02a260a2008-04-20 00:41:09 +00008541 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
Chris Lattnerb7530652008-01-27 05:29:54 +00008542 return V;
8543 if (CFP->getType() == Type::DoubleTy)
8544 return V; // Won't shrink.
Chris Lattner02a260a2008-04-20 00:41:09 +00008545 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
Chris Lattnerb7530652008-01-27 05:29:54 +00008546 return V;
8547 // Don't try to shrink to various long double types.
8548 }
8549
8550 return V;
8551}
8552
8553Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8554 if (Instruction *I = commonCastTransforms(CI))
8555 return I;
8556
8557 // If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are
8558 // smaller than the destination type, we can eliminate the truncate by doing
8559 // the add as the smaller type. This applies to add/sub/mul/div as well as
8560 // many builtins (sqrt, etc).
8561 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8562 if (OpI && OpI->hasOneUse()) {
8563 switch (OpI->getOpcode()) {
8564 default: break;
8565 case Instruction::Add:
8566 case Instruction::Sub:
8567 case Instruction::Mul:
8568 case Instruction::FDiv:
8569 case Instruction::FRem:
8570 const Type *SrcTy = OpI->getType();
8571 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
8572 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
8573 if (LHSTrunc->getType() != SrcTy &&
8574 RHSTrunc->getType() != SrcTy) {
8575 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
8576 // If the source types were both smaller than the destination type of
8577 // the cast, do this xform.
8578 if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
8579 RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
8580 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8581 CI.getType(), CI);
8582 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8583 CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008584 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerb7530652008-01-27 05:29:54 +00008585 }
8586 }
8587 break;
8588 }
8589 }
8590 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008591}
8592
8593Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8594 return commonCastTransforms(CI);
8595}
8596
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008597Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00008598 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8599 if (OpI == 0)
8600 return commonCastTransforms(FI);
8601
8602 // fptoui(uitofp(X)) --> X
8603 // fptoui(sitofp(X)) --> X
8604 // This is safe if the intermediate type has enough bits in its mantissa to
8605 // accurately represent all values of X. For example, do not do this with
8606 // i64->float->i64. This is also safe for sitofp case, because any negative
8607 // 'X' value would cause an undefined result for the fptoui.
8608 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8609 OpI->getOperand(0)->getType() == FI.getType() &&
8610 (int)FI.getType()->getPrimitiveSizeInBits() < /*extra bit for sign */
8611 OpI->getType()->getFPMantissaWidth())
8612 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008613
8614 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008615}
8616
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008617Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00008618 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8619 if (OpI == 0)
8620 return commonCastTransforms(FI);
8621
8622 // fptosi(sitofp(X)) --> X
8623 // fptosi(uitofp(X)) --> X
8624 // This is safe if the intermediate type has enough bits in its mantissa to
8625 // accurately represent all values of X. For example, do not do this with
8626 // i64->float->i64. This is also safe for sitofp case, because any negative
8627 // 'X' value would cause an undefined result for the fptoui.
8628 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8629 OpI->getOperand(0)->getType() == FI.getType() &&
8630 (int)FI.getType()->getPrimitiveSizeInBits() <=
8631 OpI->getType()->getFPMantissaWidth())
8632 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008633
8634 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008635}
8636
8637Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8638 return commonCastTransforms(CI);
8639}
8640
8641Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8642 return commonCastTransforms(CI);
8643}
8644
Chris Lattnera0e69692009-03-24 18:35:40 +00008645Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8646 // If the destination integer type is smaller than the intptr_t type for
8647 // this target, do a ptrtoint to intptr_t then do a trunc. This allows the
8648 // trunc to be exposed to other transforms. Don't do this for extending
8649 // ptrtoint's, because we don't know if the target sign or zero extends its
8650 // pointers.
8651 if (CI.getType()->getPrimitiveSizeInBits() < TD->getPointerSizeInBits()) {
8652 Value *P = InsertNewInstBefore(new PtrToIntInst(CI.getOperand(0),
8653 TD->getIntPtrType(),
8654 "tmp"), CI);
8655 return new TruncInst(P, CI.getType());
8656 }
8657
Chris Lattnerd3e28342007-04-27 17:44:50 +00008658 return commonPointerCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008659}
8660
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008661Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
Chris Lattnera0e69692009-03-24 18:35:40 +00008662 // If the source integer type is larger than the intptr_t type for
8663 // this target, do a trunc to the intptr_t type, then inttoptr of it. This
8664 // allows the trunc to be exposed to other transforms. Don't do this for
8665 // extending inttoptr's, because we don't know if the target sign or zero
8666 // extends to pointers.
8667 if (CI.getOperand(0)->getType()->getPrimitiveSizeInBits() >
8668 TD->getPointerSizeInBits()) {
8669 Value *P = InsertNewInstBefore(new TruncInst(CI.getOperand(0),
8670 TD->getIntPtrType(),
8671 "tmp"), CI);
8672 return new IntToPtrInst(P, CI.getType());
8673 }
8674
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008675 if (Instruction *I = commonCastTransforms(CI))
8676 return I;
8677
8678 const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
8679 if (!DestPointee->isSized()) return 0;
8680
8681 // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
8682 ConstantInt *Cst;
8683 Value *X;
8684 if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
8685 m_ConstantInt(Cst)))) {
8686 // If the source and destination operands have the same type, see if this
8687 // is a single-index GEP.
8688 if (X->getType() == CI.getType()) {
8689 // Get the size of the pointee type.
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00008690 uint64_t Size = TD->getTypePaddedSize(DestPointee);
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008691
8692 // Convert the constant to intptr type.
8693 APInt Offset = Cst->getValue();
8694 Offset.sextOrTrunc(TD->getPointerSizeInBits());
8695
8696 // If Offset is evenly divisible by Size, we can do this xform.
8697 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8698 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
Gabor Greif051a9502008-04-06 20:25:17 +00008699 return GetElementPtrInst::Create(X, ConstantInt::get(Offset));
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008700 }
8701 }
8702 // TODO: Could handle other cases, e.g. where add is indexing into field of
8703 // struct etc.
8704 } else if (CI.getOperand(0)->hasOneUse() &&
8705 match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
8706 // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
8707 // "inttoptr+GEP" instead of "add+intptr".
8708
8709 // Get the size of the pointee type.
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00008710 uint64_t Size = TD->getTypePaddedSize(DestPointee);
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008711
8712 // Convert the constant to intptr type.
8713 APInt Offset = Cst->getValue();
8714 Offset.sextOrTrunc(TD->getPointerSizeInBits());
8715
8716 // If Offset is evenly divisible by Size, we can do this xform.
8717 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8718 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8719
8720 Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
8721 "tmp"), CI);
Gabor Greif051a9502008-04-06 20:25:17 +00008722 return GetElementPtrInst::Create(P, ConstantInt::get(Offset), "tmp");
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008723 }
8724 }
8725 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008726}
8727
Chris Lattnerd3e28342007-04-27 17:44:50 +00008728Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008729 // If the operands are integer typed then apply the integer transforms,
8730 // otherwise just apply the common ones.
8731 Value *Src = CI.getOperand(0);
8732 const Type *SrcTy = Src->getType();
8733 const Type *DestTy = CI.getType();
8734
Chris Lattner42a75512007-01-15 02:27:26 +00008735 if (SrcTy->isInteger() && DestTy->isInteger()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008736 if (Instruction *Result = commonIntCastTransforms(CI))
8737 return Result;
Chris Lattnerd3e28342007-04-27 17:44:50 +00008738 } else if (isa<PointerType>(SrcTy)) {
8739 if (Instruction *I = commonPointerCastTransforms(CI))
8740 return I;
Reid Spencer3da59db2006-11-27 01:05:10 +00008741 } else {
8742 if (Instruction *Result = commonCastTransforms(CI))
8743 return Result;
8744 }
8745
8746
8747 // Get rid of casts from one type to the same type. These are useless and can
8748 // be replaced by the operand.
8749 if (DestTy == Src->getType())
8750 return ReplaceInstUsesWith(CI, Src);
8751
Reid Spencer3da59db2006-11-27 01:05:10 +00008752 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008753 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8754 const Type *DstElTy = DstPTy->getElementType();
8755 const Type *SrcElTy = SrcPTy->getElementType();
8756
Nate Begeman83ad90a2008-03-31 00:22:16 +00008757 // If the address spaces don't match, don't eliminate the bitcast, which is
8758 // required for changing types.
8759 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8760 return 0;
8761
Chris Lattnerd3e28342007-04-27 17:44:50 +00008762 // If we are casting a malloc or alloca to a pointer to a type of the same
8763 // size, rewrite the allocation instruction to allocate the "right" type.
8764 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8765 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8766 return V;
8767
Chris Lattnerd717c182007-05-05 22:32:24 +00008768 // If the source and destination are pointers, and this cast is equivalent
8769 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
Chris Lattnerd3e28342007-04-27 17:44:50 +00008770 // This can enhance SROA and other transforms that want type-safe pointers.
8771 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
8772 unsigned NumZeros = 0;
8773 while (SrcElTy != DstElTy &&
8774 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8775 SrcElTy->getNumContainedTypes() /* not "{}" */) {
8776 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8777 ++NumZeros;
8778 }
Chris Lattner4e998b22004-09-29 05:07:12 +00008779
Chris Lattnerd3e28342007-04-27 17:44:50 +00008780 // If we found a path from the src to dest, create the getelementptr now.
8781 if (SrcElTy == DstElTy) {
8782 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Gabor Greif051a9502008-04-06 20:25:17 +00008783 return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "",
8784 ((Instruction*) NULL));
Chris Lattner9fb92132006-04-12 18:09:35 +00008785 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008786 }
Chris Lattner24c8e382003-07-24 17:35:25 +00008787
Reid Spencer3da59db2006-11-27 01:05:10 +00008788 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8789 if (SVI->hasOneUse()) {
8790 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
8791 // a bitconvert to a vector with the same # elts.
Reid Spencer9d6565a2007-02-15 02:26:10 +00008792 if (isa<VectorType>(DestTy) &&
Mon P Wangaeb06d22008-11-10 04:46:22 +00008793 cast<VectorType>(DestTy)->getNumElements() ==
8794 SVI->getType()->getNumElements() &&
8795 SVI->getType()->getNumElements() ==
8796 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008797 CastInst *Tmp;
8798 // If either of the operands is a cast from CI.getType(), then
8799 // evaluating the shuffle in the casted destination's type will allow
8800 // us to eliminate at least one cast.
8801 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
8802 Tmp->getOperand(0)->getType() == DestTy) ||
8803 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
8804 Tmp->getOperand(0)->getType() == DestTy)) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00008805 Value *LHS = InsertCastBefore(Instruction::BitCast,
8806 SVI->getOperand(0), DestTy, CI);
8807 Value *RHS = InsertCastBefore(Instruction::BitCast,
8808 SVI->getOperand(1), DestTy, CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008809 // Return a new shuffle vector. Use the same element ID's, as we
8810 // know the vector types match #elts.
8811 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner01575b72006-05-25 23:24:33 +00008812 }
8813 }
8814 }
8815 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00008816 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00008817}
8818
Chris Lattnere576b912004-04-09 23:46:01 +00008819/// GetSelectFoldableOperands - We want to turn code that looks like this:
8820/// %C = or %A, %B
8821/// %D = select %cond, %C, %A
8822/// into:
8823/// %C = select %cond, %B, 0
8824/// %D = or %A, %C
8825///
8826/// Assuming that the specified instruction is an operand to the select, return
8827/// a bitmask indicating which operands of this instruction are foldable if they
8828/// equal the other incoming value of the select.
8829///
8830static unsigned GetSelectFoldableOperands(Instruction *I) {
8831 switch (I->getOpcode()) {
8832 case Instruction::Add:
8833 case Instruction::Mul:
8834 case Instruction::And:
8835 case Instruction::Or:
8836 case Instruction::Xor:
8837 return 3; // Can fold through either operand.
8838 case Instruction::Sub: // Can only fold on the amount subtracted.
8839 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencer3822ff52006-11-08 06:47:33 +00008840 case Instruction::LShr:
8841 case Instruction::AShr:
Misha Brukmanfd939082005-04-21 23:48:37 +00008842 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00008843 default:
8844 return 0; // Cannot fold
8845 }
8846}
8847
8848/// GetSelectFoldableConstant - For the same transformation as the previous
8849/// function, return the identity constant that goes into the select.
8850static Constant *GetSelectFoldableConstant(Instruction *I) {
8851 switch (I->getOpcode()) {
8852 default: assert(0 && "This cannot happen!"); abort();
8853 case Instruction::Add:
8854 case Instruction::Sub:
8855 case Instruction::Or:
8856 case Instruction::Xor:
Chris Lattnere576b912004-04-09 23:46:01 +00008857 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00008858 case Instruction::LShr:
8859 case Instruction::AShr:
Reid Spencer832254e2007-02-02 02:16:23 +00008860 return Constant::getNullValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00008861 case Instruction::And:
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00008862 return Constant::getAllOnesValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00008863 case Instruction::Mul:
8864 return ConstantInt::get(I->getType(), 1);
8865 }
8866}
8867
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008868/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
8869/// have the same opcode and only one use each. Try to simplify this.
8870Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
8871 Instruction *FI) {
8872 if (TI->getNumOperands() == 1) {
8873 // If this is a non-volatile load or a cast from the same type,
8874 // merge.
Reid Spencer3da59db2006-11-27 01:05:10 +00008875 if (TI->isCast()) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008876 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
8877 return 0;
8878 } else {
8879 return 0; // unknown unary op.
8880 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008881
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008882 // Fold this by inserting a select from the input values.
Gabor Greif051a9502008-04-06 20:25:17 +00008883 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
8884 FI->getOperand(0), SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008885 InsertNewInstBefore(NewSI, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008886 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Reid Spencer3da59db2006-11-27 01:05:10 +00008887 TI->getType());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008888 }
8889
Reid Spencer832254e2007-02-02 02:16:23 +00008890 // Only handle binary operators here.
8891 if (!isa<BinaryOperator>(TI))
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008892 return 0;
8893
8894 // Figure out if the operations have any operands in common.
8895 Value *MatchOp, *OtherOpT, *OtherOpF;
8896 bool MatchIsOpZero;
8897 if (TI->getOperand(0) == FI->getOperand(0)) {
8898 MatchOp = TI->getOperand(0);
8899 OtherOpT = TI->getOperand(1);
8900 OtherOpF = FI->getOperand(1);
8901 MatchIsOpZero = true;
8902 } else if (TI->getOperand(1) == FI->getOperand(1)) {
8903 MatchOp = TI->getOperand(1);
8904 OtherOpT = TI->getOperand(0);
8905 OtherOpF = FI->getOperand(0);
8906 MatchIsOpZero = false;
8907 } else if (!TI->isCommutative()) {
8908 return 0;
8909 } else if (TI->getOperand(0) == FI->getOperand(1)) {
8910 MatchOp = TI->getOperand(0);
8911 OtherOpT = TI->getOperand(1);
8912 OtherOpF = FI->getOperand(0);
8913 MatchIsOpZero = true;
8914 } else if (TI->getOperand(1) == FI->getOperand(0)) {
8915 MatchOp = TI->getOperand(1);
8916 OtherOpT = TI->getOperand(0);
8917 OtherOpF = FI->getOperand(1);
8918 MatchIsOpZero = true;
8919 } else {
8920 return 0;
8921 }
8922
8923 // If we reach here, they do have operations in common.
Gabor Greif051a9502008-04-06 20:25:17 +00008924 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
8925 OtherOpF, SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008926 InsertNewInstBefore(NewSI, SI);
8927
8928 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
8929 if (MatchIsOpZero)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008930 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008931 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008932 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008933 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00008934 assert(0 && "Shouldn't get here");
8935 return 0;
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008936}
8937
Evan Chengde621922009-03-31 20:42:45 +00008938static bool isSelect01(Constant *C1, Constant *C2) {
8939 ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
8940 if (!C1I)
8941 return false;
8942 ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
8943 if (!C2I)
8944 return false;
8945 return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
8946}
8947
8948/// FoldSelectIntoOp - Try fold the select into one of the operands to
8949/// facilitate further optimization.
8950Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
8951 Value *FalseVal) {
8952 // See the comment above GetSelectFoldableOperands for a description of the
8953 // transformation we are doing here.
8954 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
8955 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
8956 !isa<Constant>(FalseVal)) {
8957 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
8958 unsigned OpToFold = 0;
8959 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
8960 OpToFold = 1;
8961 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
8962 OpToFold = 2;
8963 }
8964
8965 if (OpToFold) {
8966 Constant *C = GetSelectFoldableConstant(TVI);
8967 Value *OOp = TVI->getOperand(2-OpToFold);
8968 // Avoid creating select between 2 constants unless it's selecting
8969 // between 0 and 1.
8970 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
8971 Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
8972 InsertNewInstBefore(NewSel, SI);
8973 NewSel->takeName(TVI);
8974 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
8975 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
8976 assert(0 && "Unknown instruction!!");
8977 }
8978 }
8979 }
8980 }
8981 }
8982
8983 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
8984 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
8985 !isa<Constant>(TrueVal)) {
8986 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
8987 unsigned OpToFold = 0;
8988 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
8989 OpToFold = 1;
8990 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
8991 OpToFold = 2;
8992 }
8993
8994 if (OpToFold) {
8995 Constant *C = GetSelectFoldableConstant(FVI);
8996 Value *OOp = FVI->getOperand(2-OpToFold);
8997 // Avoid creating select between 2 constants unless it's selecting
8998 // between 0 and 1.
8999 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9000 Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9001 InsertNewInstBefore(NewSel, SI);
9002 NewSel->takeName(FVI);
9003 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9004 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
9005 assert(0 && "Unknown instruction!!");
9006 }
9007 }
9008 }
9009 }
9010 }
9011
9012 return 0;
9013}
9014
Dan Gohman81b28ce2008-09-16 18:46:06 +00009015/// visitSelectInstWithICmp - Visit a SelectInst that has an
9016/// ICmpInst as its first operand.
9017///
9018Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9019 ICmpInst *ICI) {
9020 bool Changed = false;
9021 ICmpInst::Predicate Pred = ICI->getPredicate();
9022 Value *CmpLHS = ICI->getOperand(0);
9023 Value *CmpRHS = ICI->getOperand(1);
9024 Value *TrueVal = SI.getTrueValue();
9025 Value *FalseVal = SI.getFalseValue();
9026
9027 // Check cases where the comparison is with a constant that
9028 // can be adjusted to fit the min/max idiom. We may edit ICI in
9029 // place here, so make sure the select is the only user.
9030 if (ICI->hasOneUse())
Dan Gohman1975d032008-10-30 20:40:10 +00009031 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
Dan Gohman81b28ce2008-09-16 18:46:06 +00009032 switch (Pred) {
9033 default: break;
9034 case ICmpInst::ICMP_ULT:
9035 case ICmpInst::ICMP_SLT: {
9036 // X < MIN ? T : F --> F
9037 if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9038 return ReplaceInstUsesWith(SI, FalseVal);
9039 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
9040 Constant *AdjustedRHS = SubOne(CI);
9041 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9042 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9043 Pred = ICmpInst::getSwappedPredicate(Pred);
9044 CmpRHS = AdjustedRHS;
9045 std::swap(FalseVal, TrueVal);
9046 ICI->setPredicate(Pred);
9047 ICI->setOperand(1, CmpRHS);
9048 SI.setOperand(1, TrueVal);
9049 SI.setOperand(2, FalseVal);
9050 Changed = true;
9051 }
9052 break;
9053 }
9054 case ICmpInst::ICMP_UGT:
9055 case ICmpInst::ICMP_SGT: {
9056 // X > MAX ? T : F --> F
9057 if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9058 return ReplaceInstUsesWith(SI, FalseVal);
9059 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
9060 Constant *AdjustedRHS = AddOne(CI);
9061 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9062 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9063 Pred = ICmpInst::getSwappedPredicate(Pred);
9064 CmpRHS = AdjustedRHS;
9065 std::swap(FalseVal, TrueVal);
9066 ICI->setPredicate(Pred);
9067 ICI->setOperand(1, CmpRHS);
9068 SI.setOperand(1, TrueVal);
9069 SI.setOperand(2, FalseVal);
9070 Changed = true;
9071 }
9072 break;
9073 }
9074 }
9075
Dan Gohman1975d032008-10-30 20:40:10 +00009076 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed
9077 // (x >s -1) ? -1 : 0 -> ashr x, 31 -> all ones if not signed
Chris Lattnercb504b92008-11-16 05:38:51 +00009078 CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
Chris Lattner159c35b2009-01-05 23:53:12 +00009079 if (match(TrueVal, m_ConstantInt<-1>()) &&
9080 match(FalseVal, m_ConstantInt<0>()))
Chris Lattnercb504b92008-11-16 05:38:51 +00009081 Pred = ICI->getPredicate();
Chris Lattner159c35b2009-01-05 23:53:12 +00009082 else if (match(TrueVal, m_ConstantInt<0>()) &&
9083 match(FalseVal, m_ConstantInt<-1>()))
Chris Lattnercb504b92008-11-16 05:38:51 +00009084 Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9085
Dan Gohman1975d032008-10-30 20:40:10 +00009086 if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9087 // If we are just checking for a icmp eq of a single bit and zext'ing it
9088 // to an integer, then shift the bit to the appropriate place and then
9089 // cast to integer to avoid the comparison.
9090 const APInt &Op1CV = CI->getValue();
9091
9092 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
9093 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
9094 if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
Chris Lattnercb504b92008-11-16 05:38:51 +00009095 (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
Dan Gohman1975d032008-10-30 20:40:10 +00009096 Value *In = ICI->getOperand(0);
9097 Value *Sh = ConstantInt::get(In->getType(),
9098 In->getType()->getPrimitiveSizeInBits()-1);
9099 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
9100 In->getName()+".lobit"),
9101 *ICI);
Dan Gohman21440ac2008-11-02 00:17:33 +00009102 if (In->getType() != SI.getType())
9103 In = CastInst::CreateIntegerCast(In, SI.getType(),
Dan Gohman1975d032008-10-30 20:40:10 +00009104 true/*SExt*/, "tmp", ICI);
9105
9106 if (Pred == ICmpInst::ICMP_SGT)
9107 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
9108 In->getName()+".not"), *ICI);
9109
9110 return ReplaceInstUsesWith(SI, In);
9111 }
9112 }
9113 }
9114
Dan Gohman81b28ce2008-09-16 18:46:06 +00009115 if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9116 // Transform (X == Y) ? X : Y -> Y
9117 if (Pred == ICmpInst::ICMP_EQ)
9118 return ReplaceInstUsesWith(SI, FalseVal);
9119 // Transform (X != Y) ? X : Y -> X
9120 if (Pred == ICmpInst::ICMP_NE)
9121 return ReplaceInstUsesWith(SI, TrueVal);
9122 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9123
9124 } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9125 // Transform (X == Y) ? Y : X -> X
9126 if (Pred == ICmpInst::ICMP_EQ)
9127 return ReplaceInstUsesWith(SI, FalseVal);
9128 // Transform (X != Y) ? Y : X -> Y
9129 if (Pred == ICmpInst::ICMP_NE)
9130 return ReplaceInstUsesWith(SI, TrueVal);
9131 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9132 }
9133
9134 /// NOTE: if we wanted to, this is where to detect integer ABS
9135
9136 return Changed ? &SI : 0;
9137}
9138
Chris Lattner3d69f462004-03-12 05:52:32 +00009139Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009140 Value *CondVal = SI.getCondition();
9141 Value *TrueVal = SI.getTrueValue();
9142 Value *FalseVal = SI.getFalseValue();
9143
9144 // select true, X, Y -> X
9145 // select false, X, Y -> Y
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009146 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencer579dca12007-01-12 04:24:46 +00009147 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009148
9149 // select C, X, X -> X
9150 if (TrueVal == FalseVal)
9151 return ReplaceInstUsesWith(SI, TrueVal);
9152
Chris Lattnere87597f2004-10-16 18:11:37 +00009153 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
9154 return ReplaceInstUsesWith(SI, FalseVal);
9155 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
9156 return ReplaceInstUsesWith(SI, TrueVal);
9157 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
9158 if (isa<Constant>(TrueVal))
9159 return ReplaceInstUsesWith(SI, TrueVal);
9160 else
9161 return ReplaceInstUsesWith(SI, FalseVal);
9162 }
9163
Reid Spencer4fe16d62007-01-11 18:21:29 +00009164 if (SI.getType() == Type::Int1Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00009165 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00009166 if (C->getZExtValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00009167 // Change: A = select B, true, C --> A = or B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009168 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009169 } else {
9170 // Change: A = select B, false, C --> A = and !B, C
9171 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009172 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00009173 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009174 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009175 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00009176 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00009177 if (C->getZExtValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00009178 // Change: A = select B, C, false --> A = and B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009179 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009180 } else {
9181 // Change: A = select B, C, true --> A = or !B, C
9182 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009183 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00009184 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009185 return BinaryOperator::CreateOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009186 }
9187 }
Chris Lattnercfa59752007-11-25 21:27:53 +00009188
9189 // select a, b, a -> a&b
9190 // select a, a, b -> a|b
9191 if (CondVal == TrueVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009192 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattnercfa59752007-11-25 21:27:53 +00009193 else if (CondVal == FalseVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009194 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009195 }
Chris Lattner0c199a72004-04-08 04:43:23 +00009196
Chris Lattner2eefe512004-04-09 19:05:30 +00009197 // Selecting between two integer constants?
9198 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9199 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattnerba417832007-04-11 06:12:58 +00009200 // select C, 1, 0 -> zext C to int
Reid Spencer2ec619a2007-03-23 21:24:59 +00009201 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009202 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer2ec619a2007-03-23 21:24:59 +00009203 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattnerba417832007-04-11 06:12:58 +00009204 // select C, 0, 1 -> zext !C to int
Chris Lattner2eefe512004-04-09 19:05:30 +00009205 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009206 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00009207 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009208 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00009209 }
Chris Lattner457dd822004-06-09 07:59:58 +00009210
Reid Spencere4d87aa2006-12-23 06:05:41 +00009211 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattnerb8456462006-09-20 04:44:59 +00009212
Reid Spencere4d87aa2006-12-23 06:05:41 +00009213 // (x <s 0) ? -1 : 0 -> ashr x, 31
Reid Spencer2ec619a2007-03-23 21:24:59 +00009214 if (TrueValC->isAllOnesValue() && FalseValC->isZero())
Chris Lattnerb8456462006-09-20 04:44:59 +00009215 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
Chris Lattnerba417832007-04-11 06:12:58 +00009216 if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
Chris Lattnerb8456462006-09-20 04:44:59 +00009217 // The comparison constant and the result are not neccessarily the
Reid Spencer3da59db2006-11-27 01:05:10 +00009218 // same width. Make an all-ones value by inserting a AShr.
Chris Lattnerb8456462006-09-20 04:44:59 +00009219 Value *X = IC->getOperand(0);
Zhou Sheng4351c642007-04-02 08:20:41 +00009220 uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
Reid Spencer832254e2007-02-02 02:16:23 +00009221 Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009222 Instruction *SRA = BinaryOperator::Create(Instruction::AShr, X,
Reid Spencer832254e2007-02-02 02:16:23 +00009223 ShAmt, "ones");
Chris Lattnerb8456462006-09-20 04:44:59 +00009224 InsertNewInstBefore(SRA, SI);
Eli Friedmand1fd1da2008-11-30 21:09:11 +00009225
9226 // Then cast to the appropriate width.
9227 return CastInst::CreateIntegerCast(SRA, SI.getType(), true);
Chris Lattnerb8456462006-09-20 04:44:59 +00009228 }
9229 }
9230
9231
9232 // If one of the constants is zero (we know they can't both be) and we
Chris Lattnerba417832007-04-11 06:12:58 +00009233 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattnerb8456462006-09-20 04:44:59 +00009234 // non-constant value, eliminate this whole mess. This corresponds to
9235 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer2ec619a2007-03-23 21:24:59 +00009236 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattner65b72ba2006-09-18 04:22:48 +00009237 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009238 cast<Constant>(IC->getOperand(1))->isNullValue())
9239 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9240 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00009241 isa<ConstantInt>(ICA->getOperand(1)) &&
9242 (ICA->getOperand(1) == TrueValC ||
9243 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009244 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9245 // Okay, now we know that everything is set up, we just don't
Reid Spencere4d87aa2006-12-23 06:05:41 +00009246 // know whether we have a icmp_ne or icmp_eq and whether the
9247 // true or false val is the zero.
Reid Spencer2ec619a2007-03-23 21:24:59 +00009248 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencere4d87aa2006-12-23 06:05:41 +00009249 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner457dd822004-06-09 07:59:58 +00009250 Value *V = ICA;
9251 if (ShouldNotVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009252 V = InsertNewInstBefore(BinaryOperator::Create(
Chris Lattner457dd822004-06-09 07:59:58 +00009253 Instruction::Xor, V, ICA->getOperand(1)), SI);
9254 return ReplaceInstUsesWith(SI, V);
9255 }
Chris Lattnerb8456462006-09-20 04:44:59 +00009256 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009257 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009258
9259 // See if we are selecting two values based on a comparison of the two values.
Reid Spencere4d87aa2006-12-23 06:05:41 +00009260 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9261 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattnerd76956d2004-04-10 22:21:27 +00009262 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009263 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9264 // This is not safe in general for floating point:
9265 // consider X== -0, Y== +0.
9266 // It becomes safe if either operand is a nonzero constant.
9267 ConstantFP *CFPt, *CFPf;
9268 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9269 !CFPt->getValueAPF().isZero()) ||
9270 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9271 !CFPf->getValueAPF().isZero()))
Chris Lattnerd76956d2004-04-10 22:21:27 +00009272 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009273 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009274 // Transform (X != Y) ? X : Y -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00009275 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattnerd76956d2004-04-10 22:21:27 +00009276 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009277 // NOTE: if we wanted to, this is where to detect MIN/MAX
Chris Lattnerd76956d2004-04-10 22:21:27 +00009278
Reid Spencere4d87aa2006-12-23 06:05:41 +00009279 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattnerd76956d2004-04-10 22:21:27 +00009280 // Transform (X == Y) ? Y : X -> X
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009281 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9282 // This is not safe in general for floating point:
9283 // consider X== -0, Y== +0.
9284 // It becomes safe if either operand is a nonzero constant.
9285 ConstantFP *CFPt, *CFPf;
9286 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9287 !CFPt->getValueAPF().isZero()) ||
9288 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9289 !CFPf->getValueAPF().isZero()))
9290 return ReplaceInstUsesWith(SI, FalseVal);
9291 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009292 // Transform (X != Y) ? Y : X -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00009293 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9294 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009295 // NOTE: if we wanted to, this is where to detect MIN/MAX
Reid Spencere4d87aa2006-12-23 06:05:41 +00009296 }
Dan Gohman81b28ce2008-09-16 18:46:06 +00009297 // NOTE: if we wanted to, this is where to detect ABS
Reid Spencere4d87aa2006-12-23 06:05:41 +00009298 }
9299
9300 // See if we are selecting two values based on a comparison of the two values.
Dan Gohman81b28ce2008-09-16 18:46:06 +00009301 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9302 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9303 return Result;
Misha Brukmanfd939082005-04-21 23:48:37 +00009304
Chris Lattner87875da2005-01-13 22:52:24 +00009305 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9306 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9307 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattner87875da2005-01-13 22:52:24 +00009308 Instruction *AddOp = 0, *SubOp = 0;
9309
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009310 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9311 if (TI->getOpcode() == FI->getOpcode())
9312 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9313 return IV;
9314
9315 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
9316 // even legal for FP.
Chris Lattner87875da2005-01-13 22:52:24 +00009317 if (TI->getOpcode() == Instruction::Sub &&
9318 FI->getOpcode() == Instruction::Add) {
9319 AddOp = FI; SubOp = TI;
9320 } else if (FI->getOpcode() == Instruction::Sub &&
9321 TI->getOpcode() == Instruction::Add) {
9322 AddOp = TI; SubOp = FI;
9323 }
9324
9325 if (AddOp) {
9326 Value *OtherAddOp = 0;
9327 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9328 OtherAddOp = AddOp->getOperand(1);
9329 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9330 OtherAddOp = AddOp->getOperand(0);
9331 }
9332
9333 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00009334 // So at this point we know we have (Y -> OtherAddOp):
9335 // select C, (add X, Y), (sub X, Z)
9336 Value *NegVal; // Compute -Z
9337 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
9338 NegVal = ConstantExpr::getNeg(C);
9339 } else {
9340 NegVal = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009341 BinaryOperator::CreateNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00009342 }
Chris Lattner97f37a42006-02-24 18:05:58 +00009343
9344 Value *NewTrueOp = OtherAddOp;
9345 Value *NewFalseOp = NegVal;
9346 if (AddOp != TI)
9347 std::swap(NewTrueOp, NewFalseOp);
9348 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009349 SelectInst::Create(CondVal, NewTrueOp,
9350 NewFalseOp, SI.getName() + ".p");
Chris Lattner97f37a42006-02-24 18:05:58 +00009351
9352 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009353 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00009354 }
9355 }
9356 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009357
Chris Lattnere576b912004-04-09 23:46:01 +00009358 // See if we can fold the select into one of our operands.
Chris Lattner42a75512007-01-15 02:27:26 +00009359 if (SI.getType()->isInteger()) {
Evan Chengde621922009-03-31 20:42:45 +00009360 Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9361 if (FoldI)
9362 return FoldI;
Chris Lattnere576b912004-04-09 23:46:01 +00009363 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00009364
9365 if (BinaryOperator::isNot(CondVal)) {
9366 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9367 SI.setOperand(1, FalseVal);
9368 SI.setOperand(2, TrueVal);
9369 return &SI;
9370 }
9371
Chris Lattner3d69f462004-03-12 05:52:32 +00009372 return 0;
9373}
9374
Dan Gohmaneee962e2008-04-10 18:43:06 +00009375/// EnforceKnownAlignment - If the specified pointer points to an object that
9376/// we control, modify the object's alignment to PrefAlign. This isn't
9377/// often possible though. If alignment is important, a more reliable approach
9378/// is to simply align all global variables and allocation instructions to
9379/// their preferred alignment from the beginning.
9380///
9381static unsigned EnforceKnownAlignment(Value *V,
9382 unsigned Align, unsigned PrefAlign) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00009383
Dan Gohmaneee962e2008-04-10 18:43:06 +00009384 User *U = dyn_cast<User>(V);
9385 if (!U) return Align;
9386
9387 switch (getOpcode(U)) {
9388 default: break;
9389 case Instruction::BitCast:
9390 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9391 case Instruction::GetElementPtr: {
Chris Lattner95a959d2006-03-06 20:18:44 +00009392 // If all indexes are zero, it is just the alignment of the base pointer.
9393 bool AllZeroOperands = true;
Gabor Greif52ed3632008-06-12 21:51:29 +00009394 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
Gabor Greif177dd3f2008-06-12 21:37:33 +00009395 if (!isa<Constant>(*i) ||
9396 !cast<Constant>(*i)->isNullValue()) {
Chris Lattner95a959d2006-03-06 20:18:44 +00009397 AllZeroOperands = false;
9398 break;
9399 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00009400
9401 if (AllZeroOperands) {
9402 // Treat this like a bitcast.
Dan Gohmaneee962e2008-04-10 18:43:06 +00009403 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattnerf2369f22007-08-09 19:05:49 +00009404 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009405 break;
Chris Lattner95a959d2006-03-06 20:18:44 +00009406 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009407 }
9408
9409 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9410 // If there is a large requested alignment and we can, bump up the alignment
9411 // of the global.
9412 if (!GV->isDeclaration()) {
Dan Gohmanecd0fb52009-02-16 23:02:21 +00009413 if (GV->getAlignment() >= PrefAlign)
9414 Align = GV->getAlignment();
9415 else {
9416 GV->setAlignment(PrefAlign);
9417 Align = PrefAlign;
9418 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009419 }
9420 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
9421 // If there is a requested alignment and if this is an alloca, round up. We
9422 // don't do this for malloc, because some systems can't respect the request.
9423 if (isa<AllocaInst>(AI)) {
Dan Gohmanecd0fb52009-02-16 23:02:21 +00009424 if (AI->getAlignment() >= PrefAlign)
9425 Align = AI->getAlignment();
9426 else {
9427 AI->setAlignment(PrefAlign);
9428 Align = PrefAlign;
9429 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009430 }
9431 }
9432
9433 return Align;
9434}
9435
9436/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9437/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
9438/// and it is more than the alignment of the ultimate object, see if we can
9439/// increase the alignment of the ultimate object, making this check succeed.
9440unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9441 unsigned PrefAlign) {
9442 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9443 sizeof(PrefAlign) * CHAR_BIT;
9444 APInt Mask = APInt::getAllOnesValue(BitWidth);
9445 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9446 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9447 unsigned TrailZ = KnownZero.countTrailingOnes();
9448 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9449
9450 if (PrefAlign > Align)
9451 Align = EnforceKnownAlignment(V, Align, PrefAlign);
9452
9453 // We don't need to make any adjustment.
9454 return Align;
Chris Lattner95a959d2006-03-06 20:18:44 +00009455}
9456
Chris Lattnerf497b022008-01-13 23:50:23 +00009457Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00009458 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
Dan Gohmanbc989d42009-02-22 18:06:32 +00009459 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattnerf497b022008-01-13 23:50:23 +00009460 unsigned MinAlign = std::min(DstAlign, SrcAlign);
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009461 unsigned CopyAlign = MI->getAlignment();
Chris Lattnerf497b022008-01-13 23:50:23 +00009462
9463 if (CopyAlign < MinAlign) {
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009464 MI->setAlignment(MinAlign);
Chris Lattnerf497b022008-01-13 23:50:23 +00009465 return MI;
9466 }
9467
9468 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9469 // load/store.
9470 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9471 if (MemOpLength == 0) return 0;
9472
Chris Lattner37ac6082008-01-14 00:28:35 +00009473 // Source and destination pointer types are always "i8*" for intrinsic. See
9474 // if the size is something we can handle with a single primitive load/store.
9475 // A single load+store correctly handles overlapping memory in the memmove
9476 // case.
Chris Lattnerf497b022008-01-13 23:50:23 +00009477 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner69ea9d22008-04-30 06:39:11 +00009478 if (Size == 0) return MI; // Delete this mem transfer.
9479
9480 if (Size > 8 || (Size&(Size-1)))
Chris Lattner37ac6082008-01-14 00:28:35 +00009481 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattnerf497b022008-01-13 23:50:23 +00009482
Chris Lattner37ac6082008-01-14 00:28:35 +00009483 // Use an integer load+store unless we can find something better.
Chris Lattnerf497b022008-01-13 23:50:23 +00009484 Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
Chris Lattner37ac6082008-01-14 00:28:35 +00009485
9486 // Memcpy forces the use of i8* for the source and destination. That means
9487 // that if you're using memcpy to move one double around, you'll get a cast
9488 // from double* to i8*. We'd much rather use a double load+store rather than
9489 // an i64 load+store, here because this improves the odds that the source or
9490 // dest address will be promotable. See if we can find a better type than the
9491 // integer datatype.
9492 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9493 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9494 if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9495 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
9496 // down through these levels if so.
Dan Gohman8f8e2692008-05-23 01:52:21 +00009497 while (!SrcETy->isSingleValueType()) {
Chris Lattner37ac6082008-01-14 00:28:35 +00009498 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9499 if (STy->getNumElements() == 1)
9500 SrcETy = STy->getElementType(0);
9501 else
9502 break;
9503 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9504 if (ATy->getNumElements() == 1)
9505 SrcETy = ATy->getElementType();
9506 else
9507 break;
9508 } else
9509 break;
9510 }
9511
Dan Gohman8f8e2692008-05-23 01:52:21 +00009512 if (SrcETy->isSingleValueType())
Chris Lattner37ac6082008-01-14 00:28:35 +00009513 NewPtrTy = PointerType::getUnqual(SrcETy);
9514 }
9515 }
9516
9517
Chris Lattnerf497b022008-01-13 23:50:23 +00009518 // If the memcpy/memmove provides better alignment info than we can
9519 // infer, use it.
9520 SrcAlign = std::max(SrcAlign, CopyAlign);
9521 DstAlign = std::max(DstAlign, CopyAlign);
9522
9523 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
9524 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
Chris Lattner37ac6082008-01-14 00:28:35 +00009525 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9526 InsertNewInstBefore(L, *MI);
9527 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9528
9529 // Set the size of the copy to 0, it will be deleted on the next iteration.
9530 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
9531 return MI;
Chris Lattnerf497b022008-01-13 23:50:23 +00009532}
Chris Lattner3d69f462004-03-12 05:52:32 +00009533
Chris Lattner69ea9d22008-04-30 06:39:11 +00009534Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9535 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009536 if (MI->getAlignment() < Alignment) {
9537 MI->setAlignment(Alignment);
Chris Lattner69ea9d22008-04-30 06:39:11 +00009538 return MI;
9539 }
9540
9541 // Extract the length and alignment and fill if they are constant.
9542 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9543 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9544 if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
9545 return 0;
9546 uint64_t Len = LenC->getZExtValue();
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009547 Alignment = MI->getAlignment();
Chris Lattner69ea9d22008-04-30 06:39:11 +00009548
9549 // If the length is zero, this is a no-op
9550 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9551
9552 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9553 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
9554 const Type *ITy = IntegerType::get(Len*8); // n=1 -> i8.
9555
9556 Value *Dest = MI->getDest();
9557 Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
9558
9559 // Alignment 0 is identity for alignment 1 for memset, but not store.
9560 if (Alignment == 0) Alignment = 1;
9561
9562 // Extract the fill value and store.
9563 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
9564 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill), Dest, false,
9565 Alignment), *MI);
9566
9567 // Set the size of the copy to 0, it will be deleted on the next iteration.
9568 MI->setLength(Constant::getNullValue(LenC->getType()));
9569 return MI;
9570 }
9571
9572 return 0;
9573}
9574
9575
Chris Lattner8b0ea312006-01-13 20:11:04 +00009576/// visitCallInst - CallInst simplification. This mostly only handles folding
9577/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
9578/// the heavy lifting.
9579///
Chris Lattner9fe38862003-06-19 17:00:31 +00009580Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattner8b0ea312006-01-13 20:11:04 +00009581 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9582 if (!II) return visitCallSite(&CI);
9583
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009584 // Intrinsics cannot occur in an invoke, so handle them here instead of in
9585 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00009586 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009587 bool Changed = false;
9588
9589 // memmove/cpy/set of zero bytes is a noop.
9590 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9591 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9592
Chris Lattner35b9e482004-10-12 04:52:52 +00009593 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +00009594 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009595 // Replace the instruction with just byte operations. We would
9596 // transform other cases to loads/stores, but we don't know if
9597 // alignment is sufficient.
9598 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009599 }
9600
Chris Lattner35b9e482004-10-12 04:52:52 +00009601 // If we have a memmove and the source operation is a constant global,
9602 // then the source and dest pointers can't alias, so we can change this
9603 // into a call to memcpy.
Chris Lattnerf497b022008-01-13 23:50:23 +00009604 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009605 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9606 if (GVSrc->isConstant()) {
9607 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner824b9582008-11-21 16:42:48 +00009608 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9609 const Type *Tys[1];
9610 Tys[0] = CI.getOperand(3)->getType();
9611 CI.setOperand(0,
9612 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
Chris Lattner35b9e482004-10-12 04:52:52 +00009613 Changed = true;
9614 }
Chris Lattnera935db82008-05-28 05:30:41 +00009615
9616 // memmove(x,x,size) -> noop.
9617 if (MMI->getSource() == MMI->getDest())
9618 return EraseInstFromFunction(CI);
Chris Lattner95a959d2006-03-06 20:18:44 +00009619 }
Chris Lattner35b9e482004-10-12 04:52:52 +00009620
Chris Lattner95a959d2006-03-06 20:18:44 +00009621 // If we can determine a pointer alignment that is bigger than currently
9622 // set, update the alignment.
Chris Lattner3ce5e882009-03-08 03:37:16 +00009623 if (isa<MemTransferInst>(MI)) {
Chris Lattnerf497b022008-01-13 23:50:23 +00009624 if (Instruction *I = SimplifyMemTransfer(MI))
9625 return I;
Chris Lattner69ea9d22008-04-30 06:39:11 +00009626 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9627 if (Instruction *I = SimplifyMemSet(MSI))
9628 return I;
Chris Lattner95a959d2006-03-06 20:18:44 +00009629 }
9630
Chris Lattner8b0ea312006-01-13 20:11:04 +00009631 if (Changed) return II;
Chris Lattner0521e3c2008-06-18 04:33:20 +00009632 }
9633
9634 switch (II->getIntrinsicID()) {
9635 default: break;
9636 case Intrinsic::bswap:
9637 // bswap(bswap(x)) -> x
9638 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9639 if (Operand->getIntrinsicID() == Intrinsic::bswap)
9640 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9641 break;
9642 case Intrinsic::ppc_altivec_lvx:
9643 case Intrinsic::ppc_altivec_lvxl:
9644 case Intrinsic::x86_sse_loadu_ps:
9645 case Intrinsic::x86_sse2_loadu_pd:
9646 case Intrinsic::x86_sse2_loadu_dq:
9647 // Turn PPC lvx -> load if the pointer is known aligned.
9648 // Turn X86 loadups -> load if the pointer is known aligned.
9649 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9650 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
9651 PointerType::getUnqual(II->getType()),
9652 CI);
9653 return new LoadInst(Ptr);
Chris Lattner867b99f2006-10-05 06:55:50 +00009654 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009655 break;
9656 case Intrinsic::ppc_altivec_stvx:
9657 case Intrinsic::ppc_altivec_stvxl:
9658 // Turn stvx -> store if the pointer is known aligned.
9659 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9660 const Type *OpPtrTy =
9661 PointerType::getUnqual(II->getOperand(1)->getType());
9662 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
9663 return new StoreInst(II->getOperand(1), Ptr);
9664 }
9665 break;
9666 case Intrinsic::x86_sse_storeu_ps:
9667 case Intrinsic::x86_sse2_storeu_pd:
9668 case Intrinsic::x86_sse2_storeu_dq:
Chris Lattner0521e3c2008-06-18 04:33:20 +00009669 // Turn X86 storeu -> store if the pointer is known aligned.
9670 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9671 const Type *OpPtrTy =
9672 PointerType::getUnqual(II->getOperand(2)->getType());
9673 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
9674 return new StoreInst(II->getOperand(2), Ptr);
9675 }
9676 break;
9677
9678 case Intrinsic::x86_sse_cvttss2si: {
9679 // These intrinsics only demands the 0th element of its input vector. If
9680 // we can simplify the input based on that, do so now.
Evan Cheng388df622009-02-03 10:05:09 +00009681 unsigned VWidth =
9682 cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9683 APInt DemandedElts(VWidth, 1);
9684 APInt UndefElts(VWidth, 0);
9685 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
Chris Lattner0521e3c2008-06-18 04:33:20 +00009686 UndefElts)) {
9687 II->setOperand(1, V);
9688 return II;
9689 }
9690 break;
9691 }
9692
9693 case Intrinsic::ppc_altivec_vperm:
9694 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9695 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9696 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
Chris Lattner867b99f2006-10-05 06:55:50 +00009697
Chris Lattner0521e3c2008-06-18 04:33:20 +00009698 // Check that all of the elements are integer constants or undefs.
9699 bool AllEltsOk = true;
9700 for (unsigned i = 0; i != 16; ++i) {
9701 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
9702 !isa<UndefValue>(Mask->getOperand(i))) {
9703 AllEltsOk = false;
9704 break;
9705 }
9706 }
9707
9708 if (AllEltsOk) {
9709 // Cast the input vectors to byte vectors.
9710 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
9711 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
9712 Value *Result = UndefValue::get(Op0->getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00009713
Chris Lattner0521e3c2008-06-18 04:33:20 +00009714 // Only extract each element once.
9715 Value *ExtractedElts[32];
9716 memset(ExtractedElts, 0, sizeof(ExtractedElts));
9717
Chris Lattnere2ed0572006-04-06 19:19:17 +00009718 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0521e3c2008-06-18 04:33:20 +00009719 if (isa<UndefValue>(Mask->getOperand(i)))
9720 continue;
9721 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9722 Idx &= 31; // Match the hardware behavior.
9723
9724 if (ExtractedElts[Idx] == 0) {
9725 Instruction *Elt =
9726 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
9727 InsertNewInstBefore(Elt, CI);
9728 ExtractedElts[Idx] = Elt;
Chris Lattnere2ed0572006-04-06 19:19:17 +00009729 }
Chris Lattnere2ed0572006-04-06 19:19:17 +00009730
Chris Lattner0521e3c2008-06-18 04:33:20 +00009731 // Insert this value into the result vector.
9732 Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
9733 i, "tmp");
9734 InsertNewInstBefore(cast<Instruction>(Result), CI);
Chris Lattnere2ed0572006-04-06 19:19:17 +00009735 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009736 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00009737 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009738 }
9739 break;
Chris Lattnere2ed0572006-04-06 19:19:17 +00009740
Chris Lattner0521e3c2008-06-18 04:33:20 +00009741 case Intrinsic::stackrestore: {
9742 // If the save is right next to the restore, remove the restore. This can
9743 // happen when variable allocas are DCE'd.
9744 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9745 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9746 BasicBlock::iterator BI = SS;
9747 if (&*++BI == II)
9748 return EraseInstFromFunction(CI);
Chris Lattnera728ddc2006-01-13 21:28:09 +00009749 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009750 }
9751
9752 // Scan down this block to see if there is another stack restore in the
9753 // same block without an intervening call/alloca.
9754 BasicBlock::iterator BI = II;
9755 TerminatorInst *TI = II->getParent()->getTerminator();
9756 bool CannotRemove = false;
9757 for (++BI; &*BI != TI; ++BI) {
9758 if (isa<AllocaInst>(BI)) {
9759 CannotRemove = true;
9760 break;
9761 }
Chris Lattneraa0bf522008-06-25 05:59:28 +00009762 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
9763 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
9764 // If there is a stackrestore below this one, remove this one.
9765 if (II->getIntrinsicID() == Intrinsic::stackrestore)
9766 return EraseInstFromFunction(CI);
9767 // Otherwise, ignore the intrinsic.
9768 } else {
9769 // If we found a non-intrinsic call, we can't remove the stack
9770 // restore.
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00009771 CannotRemove = true;
9772 break;
9773 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009774 }
Chris Lattnera728ddc2006-01-13 21:28:09 +00009775 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009776
9777 // If the stack restore is in a return/unwind block and if there are no
9778 // allocas or calls between the restore and the return, nuke the restore.
9779 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
9780 return EraseInstFromFunction(CI);
9781 break;
9782 }
Chris Lattner35b9e482004-10-12 04:52:52 +00009783 }
9784
Chris Lattner8b0ea312006-01-13 20:11:04 +00009785 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +00009786}
9787
9788// InvokeInst simplification
9789//
9790Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +00009791 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +00009792}
9793
Dale Johannesenda30ccb2008-04-25 21:16:07 +00009794/// isSafeToEliminateVarargsCast - If this cast does not affect the value
9795/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen1f530a52008-04-23 18:34:37 +00009796static bool isSafeToEliminateVarargsCast(const CallSite CS,
9797 const CastInst * const CI,
9798 const TargetData * const TD,
9799 const int ix) {
9800 if (!CI->isLosslessCast())
9801 return false;
9802
9803 // The size of ByVal arguments is derived from the type, so we
9804 // can't change to a type with a different size. If the size were
9805 // passed explicitly we could avoid this check.
Devang Patel05988662008-09-25 21:00:45 +00009806 if (!CS.paramHasAttr(ix, Attribute::ByVal))
Dale Johannesen1f530a52008-04-23 18:34:37 +00009807 return true;
9808
9809 const Type* SrcTy =
9810 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
9811 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
9812 if (!SrcTy->isSized() || !DstTy->isSized())
9813 return false;
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00009814 if (TD->getTypePaddedSize(SrcTy) != TD->getTypePaddedSize(DstTy))
Dale Johannesen1f530a52008-04-23 18:34:37 +00009815 return false;
9816 return true;
9817}
9818
Chris Lattnera44d8a22003-10-07 22:32:43 +00009819// visitCallSite - Improvements for call and invoke instructions.
9820//
9821Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +00009822 bool Changed = false;
9823
9824 // If the callee is a constexpr cast of a function, attempt to move the cast
9825 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +00009826 if (transformConstExprCastCall(CS)) return 0;
9827
Chris Lattner6c266db2003-10-07 22:54:13 +00009828 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +00009829
Chris Lattner08b22ec2005-05-13 07:09:09 +00009830 if (Function *CalleeF = dyn_cast<Function>(Callee))
9831 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
9832 Instruction *OldCall = CS.getInstruction();
9833 // If the call and callee calling conventions don't match, this call must
9834 // be unreachable, as the call is undefined.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009835 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009836 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
9837 OldCall);
Chris Lattner08b22ec2005-05-13 07:09:09 +00009838 if (!OldCall->use_empty())
9839 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
9840 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
9841 return EraseInstFromFunction(*OldCall);
9842 return 0;
9843 }
9844
Chris Lattner17be6352004-10-18 02:59:09 +00009845 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
9846 // This instruction is not reachable, just remove it. We insert a store to
9847 // undef so that we know that this code is not reachable, despite the fact
9848 // that we can't modify the CFG here.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009849 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009850 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
Chris Lattner17be6352004-10-18 02:59:09 +00009851 CS.getInstruction());
9852
9853 if (!CS.getInstruction()->use_empty())
9854 CS.getInstruction()->
9855 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
9856
9857 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
9858 // Don't break the CFG, insert a dummy cond branch.
Gabor Greif051a9502008-04-06 20:25:17 +00009859 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
9860 ConstantInt::getTrue(), II);
Chris Lattnere87597f2004-10-16 18:11:37 +00009861 }
Chris Lattner17be6352004-10-18 02:59:09 +00009862 return EraseInstFromFunction(*CS.getInstruction());
9863 }
Chris Lattnere87597f2004-10-16 18:11:37 +00009864
Duncan Sandscdb6d922007-09-17 10:26:40 +00009865 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
9866 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
9867 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
9868 return transformCallThroughTrampoline(CS);
9869
Chris Lattner6c266db2003-10-07 22:54:13 +00009870 const PointerType *PTy = cast<PointerType>(Callee->getType());
9871 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
9872 if (FTy->isVarArg()) {
Dale Johannesen63e7eb42008-04-23 01:03:05 +00009873 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Chris Lattner6c266db2003-10-07 22:54:13 +00009874 // See if we can optimize any arguments passed through the varargs area of
9875 // the call.
9876 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen1f530a52008-04-23 18:34:37 +00009877 E = CS.arg_end(); I != E; ++I, ++ix) {
9878 CastInst *CI = dyn_cast<CastInst>(*I);
9879 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
9880 *I = CI->getOperand(0);
9881 Changed = true;
Chris Lattner6c266db2003-10-07 22:54:13 +00009882 }
Dale Johannesen1f530a52008-04-23 18:34:37 +00009883 }
Chris Lattner6c266db2003-10-07 22:54:13 +00009884 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009885
Duncan Sandsf0c33542007-12-19 21:13:37 +00009886 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sandsece2c042007-12-16 15:51:49 +00009887 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsf0c33542007-12-19 21:13:37 +00009888 CS.setDoesNotThrow();
Duncan Sandsece2c042007-12-16 15:51:49 +00009889 Changed = true;
9890 }
9891
Chris Lattner6c266db2003-10-07 22:54:13 +00009892 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +00009893}
9894
Chris Lattner9fe38862003-06-19 17:00:31 +00009895// transformConstExprCastCall - If the callee is a constexpr cast of a function,
9896// attempt to move the cast to the arguments of the call/invoke.
9897//
9898bool InstCombiner::transformConstExprCastCall(CallSite CS) {
9899 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
9900 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +00009901 if (CE->getOpcode() != Instruction::BitCast ||
9902 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +00009903 return false;
Reid Spencer8863f182004-07-18 00:38:32 +00009904 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +00009905 Instruction *Caller = CS.getInstruction();
Devang Patel05988662008-09-25 21:00:45 +00009906 const AttrListPtr &CallerPAL = CS.getAttributes();
Chris Lattner9fe38862003-06-19 17:00:31 +00009907
9908 // Okay, this is a cast from a function to a different type. Unless doing so
9909 // would cause a type conversion of one of our arguments, change this call to
9910 // be a direct call with arguments casted to the appropriate types.
9911 //
9912 const FunctionType *FT = Callee->getFunctionType();
9913 const Type *OldRetTy = Caller->getType();
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009914 const Type *NewRetTy = FT->getReturnType();
Chris Lattner9fe38862003-06-19 17:00:31 +00009915
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009916 if (isa<StructType>(NewRetTy))
Devang Patel75e6f022008-03-11 18:04:06 +00009917 return false; // TODO: Handle multiple return values.
9918
Chris Lattnerf78616b2004-01-14 06:06:08 +00009919 // Check to see if we are changing the return type...
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009920 if (OldRetTy != NewRetTy) {
Bill Wendlinga6c31122008-05-14 22:45:20 +00009921 if (Callee->isDeclaration() &&
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009922 // Conversion is ok if changing from one pointer type to another or from
9923 // a pointer to an integer of the same size.
9924 !((isa<PointerType>(OldRetTy) || OldRetTy == TD->getIntPtrType()) &&
Duncan Sands34b176a2008-06-17 15:55:30 +00009925 (isa<PointerType>(NewRetTy) || NewRetTy == TD->getIntPtrType())))
Chris Lattnerec479922007-01-06 02:09:32 +00009926 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +00009927
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009928 if (!Caller->use_empty() &&
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009929 // void -> non-void is handled specially
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009930 NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009931 return false; // Cannot transform this return value.
9932
Chris Lattner58d74912008-03-12 17:45:29 +00009933 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Devang Patel19c87462008-09-26 22:53:05 +00009934 Attributes RAttrs = CallerPAL.getRetAttributes();
Devang Patel05988662008-09-25 21:00:45 +00009935 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
Duncan Sands6c3470e2008-01-07 17:16:06 +00009936 return false; // Attribute not compatible with transformed value.
9937 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009938
Chris Lattnerf78616b2004-01-14 06:06:08 +00009939 // If the callsite is an invoke instruction, and the return value is used by
9940 // a PHI node in a successor, we cannot change the return type of the call
9941 // because there is no place to put the cast instruction (without breaking
9942 // the critical edge). Bail out in this case.
9943 if (!Caller->use_empty())
9944 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
9945 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
9946 UI != E; ++UI)
9947 if (PHINode *PN = dyn_cast<PHINode>(*UI))
9948 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00009949 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +00009950 return false;
9951 }
Chris Lattner9fe38862003-06-19 17:00:31 +00009952
9953 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
9954 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +00009955
Chris Lattner9fe38862003-06-19 17:00:31 +00009956 CallSite::arg_iterator AI = CS.arg_begin();
9957 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
9958 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +00009959 const Type *ActTy = (*AI)->getType();
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009960
9961 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009962 return false; // Cannot transform this parameter value.
9963
Devang Patel19c87462008-09-26 22:53:05 +00009964 if (CallerPAL.getParamAttributes(i + 1)
9965 & Attribute::typeIncompatible(ParamTy))
Chris Lattner58d74912008-03-12 17:45:29 +00009966 return false; // Attribute not compatible with transformed value.
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009967
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009968 // Converting from one pointer type to another or between a pointer and an
9969 // integer of the same size is safe even if we do not have a body.
Chris Lattnerec479922007-01-06 02:09:32 +00009970 bool isConvertible = ActTy == ParamTy ||
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009971 ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
9972 (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType()));
Reid Spencer5cbf9852007-01-30 20:08:39 +00009973 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +00009974 }
9975
9976 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +00009977 Callee->isDeclaration())
Chris Lattner58d74912008-03-12 17:45:29 +00009978 return false; // Do not delete arguments unless we have a function body.
Chris Lattner9fe38862003-06-19 17:00:31 +00009979
Chris Lattner58d74912008-03-12 17:45:29 +00009980 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
9981 !CallerPAL.isEmpty())
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009982 // In this case we have more arguments than the new function type, but we
Duncan Sandse1e520f2008-01-13 08:02:44 +00009983 // won't be dropping them. Check that these extra arguments have attributes
9984 // that are compatible with being a vararg call argument.
Chris Lattner58d74912008-03-12 17:45:29 +00009985 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
9986 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sandse1e520f2008-01-13 08:02:44 +00009987 break;
Devang Pateleaf42ab2008-09-23 23:03:40 +00009988 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Devang Patel05988662008-09-25 21:00:45 +00009989 if (PAttrs & Attribute::VarArgsIncompatible)
Duncan Sandse1e520f2008-01-13 08:02:44 +00009990 return false;
9991 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009992
Chris Lattner9fe38862003-06-19 17:00:31 +00009993 // Okay, we decided that this is a safe thing to do: go ahead and start
9994 // inserting cast instructions as necessary...
9995 std::vector<Value*> Args;
9996 Args.reserve(NumActualArgs);
Devang Patel05988662008-09-25 21:00:45 +00009997 SmallVector<AttributeWithIndex, 8> attrVec;
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009998 attrVec.reserve(NumCommonArgs);
9999
10000 // Get any return attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010001 Attributes RAttrs = CallerPAL.getRetAttributes();
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010002
10003 // If the return value is not being used, the type may not be compatible
10004 // with the existing attributes. Wipe out any problematic attributes.
Devang Patel05988662008-09-25 21:00:45 +000010005 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010006
10007 // Add the new return attributes.
10008 if (RAttrs)
Devang Patel05988662008-09-25 21:00:45 +000010009 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +000010010
10011 AI = CS.arg_begin();
10012 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10013 const Type *ParamTy = FT->getParamType(i);
10014 if ((*AI)->getType() == ParamTy) {
10015 Args.push_back(*AI);
10016 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +000010017 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +000010018 false, ParamTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010019 CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
Reid Spencer3da59db2006-11-27 01:05:10 +000010020 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner9fe38862003-06-19 17:00:31 +000010021 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010022
10023 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010024 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +000010025 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +000010026 }
10027
10028 // If the function takes more arguments than the call was taking, add them
10029 // now...
10030 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
10031 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
10032
10033 // If we are removing arguments to the function, emit an obnoxious warning...
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010034 if (FT->getNumParams() < NumActualArgs) {
Chris Lattner9fe38862003-06-19 17:00:31 +000010035 if (!FT->isVarArg()) {
Bill Wendlinge8156192006-12-07 01:30:32 +000010036 cerr << "WARNING: While resolving call to function '"
10037 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +000010038 } else {
10039 // Add all of the arguments in their promoted form to the arg list...
10040 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10041 const Type *PTy = getPromotedType((*AI)->getType());
10042 if (PTy != (*AI)->getType()) {
10043 // Must promote to pass through va_arg area!
Reid Spencerc5b206b2006-12-31 05:48:39 +000010044 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
10045 PTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010046 Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
Chris Lattner9fe38862003-06-19 17:00:31 +000010047 InsertNewInstBefore(Cast, *Caller);
10048 Args.push_back(Cast);
10049 } else {
10050 Args.push_back(*AI);
10051 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010052
Duncan Sandse1e520f2008-01-13 08:02:44 +000010053 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010054 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +000010055 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Duncan Sandse1e520f2008-01-13 08:02:44 +000010056 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010057 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010058 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010059
Devang Patel19c87462008-09-26 22:53:05 +000010060 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
10061 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10062
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010063 if (NewRetTy == Type::VoidTy)
Chris Lattner6934a042007-02-11 01:23:03 +000010064 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +000010065
Devang Patel05988662008-09-25 21:00:45 +000010066 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),attrVec.end());
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010067
Chris Lattner9fe38862003-06-19 17:00:31 +000010068 Instruction *NC;
10069 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010070 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010071 Args.begin(), Args.end(),
10072 Caller->getName(), Caller);
Reid Spencered3fa852007-07-30 19:53:57 +000010073 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010074 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +000010075 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000010076 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10077 Caller->getName(), Caller);
Duncan Sandsdc024672007-11-27 13:23:08 +000010078 CallInst *CI = cast<CallInst>(Caller);
10079 if (CI->isTailCall())
Chris Lattnera9e92112005-05-06 06:48:21 +000010080 cast<CallInst>(NC)->setTailCall();
Duncan Sandsdc024672007-11-27 13:23:08 +000010081 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010082 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +000010083 }
10084
Chris Lattner6934a042007-02-11 01:23:03 +000010085 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +000010086 Value *NV = NC;
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010087 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Chris Lattner9fe38862003-06-19 17:00:31 +000010088 if (NV->getType() != Type::VoidTy) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010089 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010090 OldRetTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010091 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +000010092
10093 // If this is an invoke instruction, we should insert it after the first
10094 // non-phi, instruction in the normal successor block.
10095 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman02dea8b2008-05-23 21:05:58 +000010096 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Chris Lattnerbb609042003-10-30 00:46:41 +000010097 InsertNewInstBefore(NC, *I);
10098 } else {
10099 // Otherwise, it's a call, just insert cast right after the call instr
10100 InsertNewInstBefore(NC, *Caller);
10101 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +000010102 AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +000010103 } else {
Chris Lattnerc30bda72004-10-17 21:22:38 +000010104 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +000010105 }
10106 }
10107
10108 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10109 Caller->replaceAllUsesWith(NV);
Chris Lattnerf22a5c62007-03-02 19:59:19 +000010110 Caller->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000010111 RemoveFromWorkList(Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +000010112 return true;
10113}
10114
Duncan Sandscdb6d922007-09-17 10:26:40 +000010115// transformCallThroughTrampoline - Turn a call to a function created by the
10116// init_trampoline intrinsic into a direct call to the underlying function.
10117//
10118Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10119 Value *Callee = CS.getCalledValue();
10120 const PointerType *PTy = cast<PointerType>(Callee->getType());
10121 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Devang Patel05988662008-09-25 21:00:45 +000010122 const AttrListPtr &Attrs = CS.getAttributes();
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010123
10124 // If the call already has the 'nest' attribute somewhere then give up -
10125 // otherwise 'nest' would occur twice after splicing in the chain.
Devang Patel05988662008-09-25 21:00:45 +000010126 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010127 return 0;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010128
10129 IntrinsicInst *Tramp =
10130 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10131
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +000010132 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sandscdb6d922007-09-17 10:26:40 +000010133 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10134 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10135
Devang Patel05988662008-09-25 21:00:45 +000010136 const AttrListPtr &NestAttrs = NestF->getAttributes();
Chris Lattner58d74912008-03-12 17:45:29 +000010137 if (!NestAttrs.isEmpty()) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000010138 unsigned NestIdx = 1;
10139 const Type *NestTy = 0;
Devang Patel05988662008-09-25 21:00:45 +000010140 Attributes NestAttr = Attribute::None;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010141
10142 // Look for a parameter marked with the 'nest' attribute.
10143 for (FunctionType::param_iterator I = NestFTy->param_begin(),
10144 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Devang Patel05988662008-09-25 21:00:45 +000010145 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000010146 // Record the parameter type and any other attributes.
10147 NestTy = *I;
Devang Patel19c87462008-09-26 22:53:05 +000010148 NestAttr = NestAttrs.getParamAttributes(NestIdx);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010149 break;
10150 }
10151
10152 if (NestTy) {
10153 Instruction *Caller = CS.getInstruction();
10154 std::vector<Value*> NewArgs;
10155 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10156
Devang Patel05988662008-09-25 21:00:45 +000010157 SmallVector<AttributeWithIndex, 8> NewAttrs;
Chris Lattner58d74912008-03-12 17:45:29 +000010158 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010159
Duncan Sandscdb6d922007-09-17 10:26:40 +000010160 // Insert the nest argument into the call argument list, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010161 // mean appending it. Likewise for attributes.
10162
Devang Patel19c87462008-09-26 22:53:05 +000010163 // Add any result attributes.
10164 if (Attributes Attr = Attrs.getRetAttributes())
Devang Patel05988662008-09-25 21:00:45 +000010165 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010166
Duncan Sandscdb6d922007-09-17 10:26:40 +000010167 {
10168 unsigned Idx = 1;
10169 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10170 do {
10171 if (Idx == NestIdx) {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010172 // Add the chain argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010173 Value *NestVal = Tramp->getOperand(3);
10174 if (NestVal->getType() != NestTy)
10175 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10176 NewArgs.push_back(NestVal);
Devang Patel05988662008-09-25 21:00:45 +000010177 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000010178 }
10179
10180 if (I == E)
10181 break;
10182
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010183 // Add the original argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010184 NewArgs.push_back(*I);
Devang Patel19c87462008-09-26 22:53:05 +000010185 if (Attributes Attr = Attrs.getParamAttributes(Idx))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010186 NewAttrs.push_back
Devang Patel05988662008-09-25 21:00:45 +000010187 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000010188
10189 ++Idx, ++I;
10190 } while (1);
10191 }
10192
Devang Patel19c87462008-09-26 22:53:05 +000010193 // Add any function attributes.
10194 if (Attributes Attr = Attrs.getFnAttributes())
10195 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10196
Duncan Sandscdb6d922007-09-17 10:26:40 +000010197 // The trampoline may have been bitcast to a bogus type (FTy).
10198 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010199 // with the chain parameter inserted.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010200
Duncan Sandscdb6d922007-09-17 10:26:40 +000010201 std::vector<const Type*> NewTypes;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010202 NewTypes.reserve(FTy->getNumParams()+1);
10203
Duncan Sandscdb6d922007-09-17 10:26:40 +000010204 // Insert the chain's type into the list of parameter types, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010205 // mean appending it.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010206 {
10207 unsigned Idx = 1;
10208 FunctionType::param_iterator I = FTy->param_begin(),
10209 E = FTy->param_end();
10210
10211 do {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010212 if (Idx == NestIdx)
10213 // Add the chain's type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010214 NewTypes.push_back(NestTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010215
10216 if (I == E)
10217 break;
10218
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010219 // Add the original type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010220 NewTypes.push_back(*I);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010221
10222 ++Idx, ++I;
10223 } while (1);
10224 }
10225
10226 // Replace the trampoline call with a direct call. Let the generic
10227 // code sort out any function type mismatches.
10228 FunctionType *NewFTy =
Duncan Sandsdc024672007-11-27 13:23:08 +000010229 FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
Christopher Lamb43ad6b32007-12-17 01:12:55 +000010230 Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
10231 NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
Devang Patel05988662008-09-25 21:00:45 +000010232 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),NewAttrs.end());
Duncan Sandscdb6d922007-09-17 10:26:40 +000010233
10234 Instruction *NewCaller;
10235 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010236 NewCaller = InvokeInst::Create(NewCallee,
10237 II->getNormalDest(), II->getUnwindDest(),
10238 NewArgs.begin(), NewArgs.end(),
10239 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010240 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010241 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010242 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000010243 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10244 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010245 if (cast<CallInst>(Caller)->isTailCall())
10246 cast<CallInst>(NewCaller)->setTailCall();
10247 cast<CallInst>(NewCaller)->
10248 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010249 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010250 }
10251 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10252 Caller->replaceAllUsesWith(NewCaller);
10253 Caller->eraseFromParent();
10254 RemoveFromWorkList(Caller);
10255 return 0;
10256 }
10257 }
10258
10259 // Replace the trampoline call with a direct call. Since there is no 'nest'
10260 // parameter, there is no need to adjust the argument list. Let the generic
10261 // code sort out any function type mismatches.
10262 Constant *NewCallee =
10263 NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
10264 CS.setCalledFunction(NewCallee);
10265 return CS.getInstruction();
10266}
10267
Chris Lattner7da52b22006-11-01 04:51:18 +000010268/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
10269/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
10270/// and a single binop.
10271Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10272 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010273 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
Chris Lattner7da52b22006-11-01 04:51:18 +000010274 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010275 Value *LHSVal = FirstInst->getOperand(0);
10276 Value *RHSVal = FirstInst->getOperand(1);
10277
10278 const Type *LHSType = LHSVal->getType();
10279 const Type *RHSType = RHSVal->getType();
Chris Lattner7da52b22006-11-01 04:51:18 +000010280
10281 // Scan to see if all operands are the same opcode, all have one use, and all
10282 // kill their operands (i.e. the operands have one use).
Chris Lattner05f18922008-12-01 02:34:36 +000010283 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
Chris Lattner7da52b22006-11-01 04:51:18 +000010284 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnera90a24c2006-11-01 04:55:47 +000010285 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencere4d87aa2006-12-23 06:05:41 +000010286 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattner9c080502006-11-01 07:43:41 +000010287 // types or GEP's with different index types.
10288 I->getOperand(0)->getType() != LHSType ||
10289 I->getOperand(1)->getType() != RHSType)
Chris Lattner7da52b22006-11-01 04:51:18 +000010290 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +000010291
10292 // If they are CmpInst instructions, check their predicates
10293 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10294 if (cast<CmpInst>(I)->getPredicate() !=
10295 cast<CmpInst>(FirstInst)->getPredicate())
10296 return 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010297
10298 // Keep track of which operand needs a phi node.
10299 if (I->getOperand(0) != LHSVal) LHSVal = 0;
10300 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattner7da52b22006-11-01 04:51:18 +000010301 }
10302
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010303 // Otherwise, this is safe to transform!
Chris Lattner53738a42006-11-08 19:42:28 +000010304
Chris Lattner7da52b22006-11-01 04:51:18 +000010305 Value *InLHS = FirstInst->getOperand(0);
Chris Lattner7da52b22006-11-01 04:51:18 +000010306 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner53738a42006-11-08 19:42:28 +000010307 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010308 if (LHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010309 NewLHS = PHINode::Create(LHSType,
10310 FirstInst->getOperand(0)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010311 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10312 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010313 InsertNewInstBefore(NewLHS, PN);
10314 LHSVal = NewLHS;
10315 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010316
10317 if (RHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010318 NewRHS = PHINode::Create(RHSType,
10319 FirstInst->getOperand(1)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010320 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10321 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010322 InsertNewInstBefore(NewRHS, PN);
10323 RHSVal = NewRHS;
10324 }
10325
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010326 // Add all operands to the new PHIs.
Chris Lattner05f18922008-12-01 02:34:36 +000010327 if (NewLHS || NewRHS) {
10328 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10329 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10330 if (NewLHS) {
10331 Value *NewInLHS = InInst->getOperand(0);
10332 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10333 }
10334 if (NewRHS) {
10335 Value *NewInRHS = InInst->getOperand(1);
10336 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10337 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010338 }
10339 }
10340
Chris Lattner7da52b22006-11-01 04:51:18 +000010341 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010342 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010343 CmpInst *CIOp = cast<CmpInst>(FirstInst);
10344 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
10345 RHSVal);
Chris Lattner7da52b22006-11-01 04:51:18 +000010346}
10347
Chris Lattner05f18922008-12-01 02:34:36 +000010348Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10349 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10350
10351 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
10352 FirstInst->op_end());
Chris Lattner36d3e322009-02-21 00:46:50 +000010353 // This is true if all GEP bases are allocas and if all indices into them are
10354 // constants.
10355 bool AllBasePointersAreAllocas = true;
Chris Lattner05f18922008-12-01 02:34:36 +000010356
10357 // Scan to see if all operands are the same opcode, all have one use, and all
10358 // kill their operands (i.e. the operands have one use).
10359 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10360 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10361 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10362 GEP->getNumOperands() != FirstInst->getNumOperands())
10363 return 0;
10364
Chris Lattner36d3e322009-02-21 00:46:50 +000010365 // Keep track of whether or not all GEPs are of alloca pointers.
10366 if (AllBasePointersAreAllocas &&
10367 (!isa<AllocaInst>(GEP->getOperand(0)) ||
10368 !GEP->hasAllConstantIndices()))
10369 AllBasePointersAreAllocas = false;
10370
Chris Lattner05f18922008-12-01 02:34:36 +000010371 // Compare the operand lists.
10372 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10373 if (FirstInst->getOperand(op) == GEP->getOperand(op))
10374 continue;
10375
10376 // Don't merge two GEPs when two operands differ (introducing phi nodes)
10377 // if one of the PHIs has a constant for the index. The index may be
10378 // substantially cheaper to compute for the constants, so making it a
10379 // variable index could pessimize the path. This also handles the case
10380 // for struct indices, which must always be constant.
10381 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10382 isa<ConstantInt>(GEP->getOperand(op)))
10383 return 0;
10384
10385 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10386 return 0;
10387 FixedOperands[op] = 0; // Needs a PHI.
10388 }
10389 }
10390
Chris Lattner36d3e322009-02-21 00:46:50 +000010391 // If all of the base pointers of the PHI'd GEPs are from allocas, don't
Chris Lattner21550882009-02-23 05:56:17 +000010392 // bother doing this transformation. At best, this will just save a bit of
Chris Lattner36d3e322009-02-21 00:46:50 +000010393 // offset calculation, but all the predecessors will have to materialize the
10394 // stack address into a register anyway. We'd actually rather *clone* the
10395 // load up into the predecessors so that we have a load of a gep of an alloca,
10396 // which can usually all be folded into the load.
10397 if (AllBasePointersAreAllocas)
10398 return 0;
10399
Chris Lattner05f18922008-12-01 02:34:36 +000010400 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
10401 // that is variable.
10402 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10403
10404 bool HasAnyPHIs = false;
10405 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10406 if (FixedOperands[i]) continue; // operand doesn't need a phi.
10407 Value *FirstOp = FirstInst->getOperand(i);
10408 PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10409 FirstOp->getName()+".pn");
10410 InsertNewInstBefore(NewPN, PN);
10411
10412 NewPN->reserveOperandSpace(e);
10413 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10414 OperandPhis[i] = NewPN;
10415 FixedOperands[i] = NewPN;
10416 HasAnyPHIs = true;
10417 }
10418
10419
10420 // Add all operands to the new PHIs.
10421 if (HasAnyPHIs) {
10422 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10423 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10424 BasicBlock *InBB = PN.getIncomingBlock(i);
10425
10426 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10427 if (PHINode *OpPhi = OperandPhis[op])
10428 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10429 }
10430 }
10431
10432 Value *Base = FixedOperands[0];
10433 return GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10434 FixedOperands.end());
10435}
10436
10437
Chris Lattner21550882009-02-23 05:56:17 +000010438/// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10439/// sink the load out of the block that defines it. This means that it must be
Chris Lattner36d3e322009-02-21 00:46:50 +000010440/// obvious the value of the load is not changed from the point of the load to
10441/// the end of the block it is in.
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010442///
10443/// Finally, it is safe, but not profitable, to sink a load targetting a
10444/// non-address-taken alloca. Doing so will cause us to not promote the alloca
10445/// to a register.
Chris Lattner36d3e322009-02-21 00:46:50 +000010446static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
Chris Lattner76c73142006-11-01 07:13:54 +000010447 BasicBlock::iterator BBI = L, E = L->getParent()->end();
10448
10449 for (++BBI; BBI != E; ++BBI)
10450 if (BBI->mayWriteToMemory())
10451 return false;
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010452
10453 // Check for non-address taken alloca. If not address-taken already, it isn't
10454 // profitable to do this xform.
10455 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10456 bool isAddressTaken = false;
10457 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10458 UI != E; ++UI) {
10459 if (isa<LoadInst>(UI)) continue;
10460 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10461 // If storing TO the alloca, then the address isn't taken.
10462 if (SI->getOperand(1) == AI) continue;
10463 }
10464 isAddressTaken = true;
10465 break;
10466 }
10467
Chris Lattner36d3e322009-02-21 00:46:50 +000010468 if (!isAddressTaken && AI->isStaticAlloca())
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010469 return false;
10470 }
10471
Chris Lattner36d3e322009-02-21 00:46:50 +000010472 // If this load is a load from a GEP with a constant offset from an alloca,
10473 // then we don't want to sink it. In its present form, it will be
10474 // load [constant stack offset]. Sinking it will cause us to have to
10475 // materialize the stack addresses in each predecessor in a register only to
10476 // do a shared load from register in the successor.
10477 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10478 if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10479 if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10480 return false;
10481
Chris Lattner76c73142006-11-01 07:13:54 +000010482 return true;
10483}
10484
Chris Lattner9fe38862003-06-19 17:00:31 +000010485
Chris Lattnerbac32862004-11-14 19:13:23 +000010486// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10487// operator and they all are only used by the PHI, PHI together their
10488// inputs, and do the operation once, to the result of the PHI.
10489Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10490 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10491
10492 // Scan the instruction, looking for input operations that can be folded away.
10493 // If all input operands to the phi are the same instruction (e.g. a cast from
10494 // the same type or "+42") we can pull the operation through the PHI, reducing
10495 // code size and simplifying code.
10496 Constant *ConstantOp = 0;
10497 const Type *CastSrcTy = 0;
Chris Lattner76c73142006-11-01 07:13:54 +000010498 bool isVolatile = false;
Chris Lattnerbac32862004-11-14 19:13:23 +000010499 if (isa<CastInst>(FirstInst)) {
10500 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer832254e2007-02-02 02:16:23 +000010501 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000010502 // Can fold binop, compare or shift here if the RHS is a constant,
10503 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattnerbac32862004-11-14 19:13:23 +000010504 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattner7da52b22006-11-01 04:51:18 +000010505 if (ConstantOp == 0)
10506 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner76c73142006-11-01 07:13:54 +000010507 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10508 isVolatile = LI->isVolatile();
10509 // We can't sink the load if the loaded value could be modified between the
10510 // load and the PHI.
10511 if (LI->getParent() != PN.getIncomingBlock(0) ||
Chris Lattner36d3e322009-02-21 00:46:50 +000010512 !isSafeAndProfitableToSinkLoad(LI))
Chris Lattner76c73142006-11-01 07:13:54 +000010513 return 0;
Chris Lattner71042962008-07-08 17:18:32 +000010514
10515 // If the PHI is of volatile loads and the load block has multiple
10516 // successors, sinking it would remove a load of the volatile value from
10517 // the path through the other successor.
10518 if (isVolatile &&
10519 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10520 return 0;
10521
Chris Lattner9c080502006-11-01 07:43:41 +000010522 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner05f18922008-12-01 02:34:36 +000010523 return FoldPHIArgGEPIntoPHI(PN);
Chris Lattnerbac32862004-11-14 19:13:23 +000010524 } else {
10525 return 0; // Cannot fold this operation.
10526 }
10527
10528 // Check to see if all arguments are the same operation.
10529 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10530 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10531 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencere4d87aa2006-12-23 06:05:41 +000010532 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattnerbac32862004-11-14 19:13:23 +000010533 return 0;
10534 if (CastSrcTy) {
10535 if (I->getOperand(0)->getType() != CastSrcTy)
10536 return 0; // Cast operation must match.
Chris Lattner76c73142006-11-01 07:13:54 +000010537 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000010538 // We can't sink the load if the loaded value could be modified between
10539 // the load and the PHI.
Chris Lattner76c73142006-11-01 07:13:54 +000010540 if (LI->isVolatile() != isVolatile ||
10541 LI->getParent() != PN.getIncomingBlock(i) ||
Chris Lattner36d3e322009-02-21 00:46:50 +000010542 !isSafeAndProfitableToSinkLoad(LI))
Chris Lattner76c73142006-11-01 07:13:54 +000010543 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +000010544
Chris Lattner71042962008-07-08 17:18:32 +000010545 // If the PHI is of volatile loads and the load block has multiple
10546 // successors, sinking it would remove a load of the volatile value from
10547 // the path through the other successor.
Chris Lattner40700fe2008-04-29 17:28:22 +000010548 if (isVolatile &&
10549 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10550 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +000010551
Chris Lattnerbac32862004-11-14 19:13:23 +000010552 } else if (I->getOperand(1) != ConstantOp) {
10553 return 0;
10554 }
10555 }
10556
10557 // Okay, they are all the same operation. Create a new PHI node of the
10558 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greif051a9502008-04-06 20:25:17 +000010559 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10560 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +000010561 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +000010562
10563 Value *InVal = FirstInst->getOperand(0);
10564 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +000010565
10566 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +000010567 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10568 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10569 if (NewInVal != InVal)
10570 InVal = 0;
10571 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10572 }
10573
10574 Value *PhiVal;
10575 if (InVal) {
10576 // The new PHI unions all of the same values together. This is really
10577 // common, so we handle it intelligently here for compile-time speed.
10578 PhiVal = InVal;
10579 delete NewPN;
10580 } else {
10581 InsertNewInstBefore(NewPN, PN);
10582 PhiVal = NewPN;
10583 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010584
Chris Lattnerbac32862004-11-14 19:13:23 +000010585 // Insert and return the new operation.
Reid Spencer3da59db2006-11-27 01:05:10 +000010586 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010587 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattner54545ac2008-04-29 17:13:43 +000010588 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010589 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +000010590 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010591 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +000010592 PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +000010593 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10594
10595 // If this was a volatile load that we are merging, make sure to loop through
10596 // and mark all the input loads as non-volatile. If we don't do this, we will
10597 // insert a new volatile load and the old ones will not be deletable.
10598 if (isVolatile)
10599 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10600 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10601
10602 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattnerbac32862004-11-14 19:13:23 +000010603}
Chris Lattnera1be5662002-05-02 17:06:02 +000010604
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010605/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10606/// that is dead.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010607static bool DeadPHICycle(PHINode *PN,
10608 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010609 if (PN->use_empty()) return true;
10610 if (!PN->hasOneUse()) return false;
10611
10612 // Remember this node, and if we find the cycle, return.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010613 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010614 return true;
Chris Lattner92103de2007-08-28 04:23:55 +000010615
10616 // Don't scan crazily complex things.
10617 if (PotentiallyDeadPHIs.size() == 16)
10618 return false;
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010619
10620 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10621 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +000010622
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010623 return false;
10624}
10625
Chris Lattnercf5008a2007-11-06 21:52:06 +000010626/// PHIsEqualValue - Return true if this phi node is always equal to
10627/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
10628/// z = some value; x = phi (y, z); y = phi (x, z)
10629static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
10630 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10631 // See if we already saw this PHI node.
10632 if (!ValueEqualPHIs.insert(PN))
10633 return true;
10634
10635 // Don't scan crazily complex things.
10636 if (ValueEqualPHIs.size() == 16)
10637 return false;
10638
10639 // Scan the operands to see if they are either phi nodes or are equal to
10640 // the value.
10641 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10642 Value *Op = PN->getIncomingValue(i);
10643 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10644 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10645 return false;
10646 } else if (Op != NonPhiInVal)
10647 return false;
10648 }
10649
10650 return true;
10651}
10652
10653
Chris Lattner473945d2002-05-06 18:06:38 +000010654// PHINode simplification
10655//
Chris Lattner7e708292002-06-25 16:13:24 +000010656Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +000010657 // If LCSSA is around, don't mess with Phi nodes
Chris Lattnerf964f322007-03-04 04:27:24 +000010658 if (MustPreserveLCSSA) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +000010659
Owen Anderson7e057142006-07-10 22:03:18 +000010660 if (Value *V = PN.hasConstantValue())
10661 return ReplaceInstUsesWith(PN, V);
10662
Owen Anderson7e057142006-07-10 22:03:18 +000010663 // If all PHI operands are the same operation, pull them through the PHI,
10664 // reducing code size.
10665 if (isa<Instruction>(PN.getIncomingValue(0)) &&
Chris Lattner05f18922008-12-01 02:34:36 +000010666 isa<Instruction>(PN.getIncomingValue(1)) &&
10667 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10668 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10669 // FIXME: The hasOneUse check will fail for PHIs that use the value more
10670 // than themselves more than once.
Owen Anderson7e057142006-07-10 22:03:18 +000010671 PN.getIncomingValue(0)->hasOneUse())
10672 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10673 return Result;
10674
10675 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
10676 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10677 // PHI)... break the cycle.
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010678 if (PN.hasOneUse()) {
10679 Instruction *PHIUser = cast<Instruction>(PN.use_back());
10680 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattner0e5444b2007-03-26 20:40:50 +000010681 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Anderson7e057142006-07-10 22:03:18 +000010682 PotentiallyDeadPHIs.insert(&PN);
10683 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
10684 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10685 }
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010686
10687 // If this phi has a single use, and if that use just computes a value for
10688 // the next iteration of a loop, delete the phi. This occurs with unused
10689 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
10690 // common case here is good because the only other things that catch this
10691 // are induction variable analysis (sometimes) and ADCE, which is only run
10692 // late.
10693 if (PHIUser->hasOneUse() &&
10694 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10695 PHIUser->use_back() == &PN) {
10696 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10697 }
10698 }
Owen Anderson7e057142006-07-10 22:03:18 +000010699
Chris Lattnercf5008a2007-11-06 21:52:06 +000010700 // We sometimes end up with phi cycles that non-obviously end up being the
10701 // same value, for example:
10702 // z = some value; x = phi (y, z); y = phi (x, z)
10703 // where the phi nodes don't necessarily need to be in the same block. Do a
10704 // quick check to see if the PHI node only contains a single non-phi value, if
10705 // so, scan to see if the phi cycle is actually equal to that value.
10706 {
10707 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10708 // Scan for the first non-phi operand.
10709 while (InValNo != NumOperandVals &&
10710 isa<PHINode>(PN.getIncomingValue(InValNo)))
10711 ++InValNo;
10712
10713 if (InValNo != NumOperandVals) {
10714 Value *NonPhiInVal = PN.getOperand(InValNo);
10715
10716 // Scan the rest of the operands to see if there are any conflicts, if so
10717 // there is no need to recursively scan other phis.
10718 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10719 Value *OpVal = PN.getIncomingValue(InValNo);
10720 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10721 break;
10722 }
10723
10724 // If we scanned over all operands, then we have one unique value plus
10725 // phi values. Scan PHI nodes to see if they all merge in each other or
10726 // the value.
10727 if (InValNo == NumOperandVals) {
10728 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10729 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10730 return ReplaceInstUsesWith(PN, NonPhiInVal);
10731 }
10732 }
10733 }
Chris Lattner60921c92003-12-19 05:58:40 +000010734 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +000010735}
10736
Reid Spencer17212df2006-12-12 09:18:51 +000010737static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
10738 Instruction *InsertPoint,
10739 InstCombiner *IC) {
Reid Spencerabaa8ca2007-01-08 16:32:00 +000010740 unsigned PtrSize = DTy->getPrimitiveSizeInBits();
10741 unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +000010742 // We must cast correctly to the pointer type. Ensure that we
10743 // sign extend the integer value if it is smaller as this is
10744 // used for address computation.
10745 Instruction::CastOps opcode =
10746 (VTySize < PtrSize ? Instruction::SExt :
10747 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
10748 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
Chris Lattner28977af2004-04-05 01:30:19 +000010749}
10750
Chris Lattnera1be5662002-05-02 17:06:02 +000010751
Chris Lattner7e708292002-06-25 16:13:24 +000010752Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +000010753 Value *PtrOp = GEP.getOperand(0);
Chris Lattner9bc14642007-04-28 00:57:34 +000010754 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
Chris Lattner7e708292002-06-25 16:13:24 +000010755 // If so, eliminate the noop.
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010756 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +000010757 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010758
Chris Lattnere87597f2004-10-16 18:11:37 +000010759 if (isa<UndefValue>(GEP.getOperand(0)))
10760 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
10761
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010762 bool HasZeroPointerIndex = false;
10763 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
10764 HasZeroPointerIndex = C->isNullValue();
10765
10766 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +000010767 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +000010768
Chris Lattner28977af2004-04-05 01:30:19 +000010769 // Eliminate unneeded casts for indices.
10770 bool MadeChange = false;
Chris Lattnerdb9654e2007-03-25 20:43:09 +000010771
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010772 gep_type_iterator GTI = gep_type_begin(GEP);
Gabor Greif177dd3f2008-06-12 21:37:33 +000010773 for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end();
10774 i != e; ++i, ++GTI) {
Sanjiv Gupta7787d4a2009-04-24 02:37:54 +000010775 if (isa<SequentialType>(*GTI)) {
Gabor Greif177dd3f2008-06-12 21:37:33 +000010776 if (CastInst *CI = dyn_cast<CastInst>(*i)) {
Chris Lattner76b7a062007-01-15 07:02:54 +000010777 if (CI->getOpcode() == Instruction::ZExt ||
10778 CI->getOpcode() == Instruction::SExt) {
10779 const Type *SrcTy = CI->getOperand(0)->getType();
10780 // We can eliminate a cast from i32 to i64 iff the target
10781 // is a 32-bit pointer target.
10782 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
10783 MadeChange = true;
Gabor Greif177dd3f2008-06-12 21:37:33 +000010784 *i = CI->getOperand(0);
Chris Lattner28977af2004-04-05 01:30:19 +000010785 }
10786 }
10787 }
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010788 // If we are using a wider index than needed for this platform, shrink it
Dan Gohman4f833d42008-09-11 23:06:38 +000010789 // to what we need. If narrower, sign-extend it to what we need.
10790 // If the incoming value needs a cast instruction,
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010791 // insert it. This explicit cast can make subsequent optimizations more
10792 // obvious.
Gabor Greif177dd3f2008-06-12 21:37:33 +000010793 Value *Op = *i;
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010794 if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
Chris Lattner4f1134e2004-04-17 18:16:10 +000010795 if (Constant *C = dyn_cast<Constant>(Op)) {
Gabor Greif177dd3f2008-06-12 21:37:33 +000010796 *i = ConstantExpr::getTrunc(C, TD->getIntPtrType());
Chris Lattner4f1134e2004-04-17 18:16:10 +000010797 MadeChange = true;
10798 } else {
Reid Spencer17212df2006-12-12 09:18:51 +000010799 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
10800 GEP);
Gabor Greif177dd3f2008-06-12 21:37:33 +000010801 *i = Op;
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010802 MadeChange = true;
10803 }
Dan Gohman4f833d42008-09-11 23:06:38 +000010804 } else if (TD->getTypeSizeInBits(Op->getType()) < TD->getPointerSizeInBits()) {
10805 if (Constant *C = dyn_cast<Constant>(Op)) {
10806 *i = ConstantExpr::getSExt(C, TD->getIntPtrType());
10807 MadeChange = true;
10808 } else {
10809 Op = InsertCastBefore(Instruction::SExt, Op, TD->getIntPtrType(),
10810 GEP);
10811 *i = Op;
10812 MadeChange = true;
10813 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010814 }
Chris Lattner28977af2004-04-05 01:30:19 +000010815 }
Chris Lattnerdb9654e2007-03-25 20:43:09 +000010816 }
Chris Lattner28977af2004-04-05 01:30:19 +000010817 if (MadeChange) return &GEP;
10818
Chris Lattner90ac28c2002-08-02 19:29:35 +000010819 // Combine Indices - If the source pointer to this getelementptr instruction
10820 // is a getelementptr instruction, combine the indices of the two
10821 // getelementptr instructions into a single instruction.
10822 //
Chris Lattner72588fc2007-02-15 22:48:32 +000010823 SmallVector<Value*, 8> SrcGEPOperands;
Chris Lattner574da9b2005-01-13 20:14:25 +000010824 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner72588fc2007-02-15 22:48:32 +000010825 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
Chris Lattnerebd985c2004-03-25 22:59:29 +000010826
10827 if (!SrcGEPOperands.empty()) {
Chris Lattner620ce142004-05-07 22:09:22 +000010828 // Note that if our source is a gep chain itself that we wait for that
10829 // chain to be resolved before we perform this transformation. This
10830 // avoids us creating a TON of code in some cases.
10831 //
10832 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
10833 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
10834 return 0; // Wait until our source is folded to completion.
10835
Chris Lattner72588fc2007-02-15 22:48:32 +000010836 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +000010837
10838 // Find out whether the last index in the source GEP is a sequential idx.
10839 bool EndsWithSequential = false;
10840 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
10841 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +000010842 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000010843
Chris Lattner90ac28c2002-08-02 19:29:35 +000010844 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +000010845 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +000010846 // Replace: gep (gep %P, long B), long A, ...
10847 // With: T = long A+B; gep %P, T, ...
10848 //
Chris Lattner620ce142004-05-07 22:09:22 +000010849 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner28977af2004-04-05 01:30:19 +000010850 if (SO1 == Constant::getNullValue(SO1->getType())) {
10851 Sum = GO1;
10852 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
10853 Sum = SO1;
10854 } else {
10855 // If they aren't the same type, convert both to an integer of the
10856 // target's pointer size.
10857 if (SO1->getType() != GO1->getType()) {
10858 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +000010859 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +000010860 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +000010861 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +000010862 } else {
Duncan Sands514ab342007-11-01 20:53:16 +000010863 unsigned PS = TD->getPointerSizeInBits();
10864 if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +000010865 // Convert GO1 to SO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +000010866 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000010867
Duncan Sands514ab342007-11-01 20:53:16 +000010868 } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +000010869 // Convert SO1 to GO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +000010870 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000010871 } else {
10872 const Type *PT = TD->getIntPtrType();
Reid Spencer17212df2006-12-12 09:18:51 +000010873 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
10874 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000010875 }
10876 }
10877 }
Chris Lattner620ce142004-05-07 22:09:22 +000010878 if (isa<Constant>(SO1) && isa<Constant>(GO1))
10879 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
10880 else {
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010881 Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Chris Lattner48595f12004-06-10 02:07:29 +000010882 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner620ce142004-05-07 22:09:22 +000010883 }
Chris Lattner28977af2004-04-05 01:30:19 +000010884 }
Chris Lattner620ce142004-05-07 22:09:22 +000010885
10886 // Recycle the GEP we already have if possible.
10887 if (SrcGEPOperands.size() == 2) {
10888 GEP.setOperand(0, SrcGEPOperands[0]);
10889 GEP.setOperand(1, Sum);
10890 return &GEP;
10891 } else {
10892 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
10893 SrcGEPOperands.end()-1);
10894 Indices.push_back(Sum);
10895 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
10896 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010897 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +000010898 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanfd939082005-04-21 23:48:37 +000010899 SrcGEPOperands.size() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +000010900 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerebd985c2004-03-25 22:59:29 +000010901 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
10902 SrcGEPOperands.end());
Chris Lattner90ac28c2002-08-02 19:29:35 +000010903 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
10904 }
10905
10906 if (!Indices.empty())
Gabor Greif051a9502008-04-06 20:25:17 +000010907 return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
10908 Indices.end(), GEP.getName());
Chris Lattner9b761232002-08-17 22:21:59 +000010909
Chris Lattner620ce142004-05-07 22:09:22 +000010910 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattner9b761232002-08-17 22:21:59 +000010911 // GEP of global variable. If all of the indices for this GEP are
10912 // constants, we can promote this to a constexpr instead of an instruction.
10913
10914 // Scan for nonconstants...
Chris Lattner55eb1c42007-01-31 04:40:53 +000010915 SmallVector<Constant*, 8> Indices;
Chris Lattner9b761232002-08-17 22:21:59 +000010916 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
10917 for (; I != E && isa<Constant>(*I); ++I)
10918 Indices.push_back(cast<Constant>(*I));
10919
10920 if (I == E) { // If they are all constants...
Chris Lattner55eb1c42007-01-31 04:40:53 +000010921 Constant *CE = ConstantExpr::getGetElementPtr(GV,
10922 &Indices[0],Indices.size());
Chris Lattner9b761232002-08-17 22:21:59 +000010923
10924 // Replace all uses of the GEP with the new constexpr...
10925 return ReplaceInstUsesWith(GEP, CE);
10926 }
Reid Spencer3da59db2006-11-27 01:05:10 +000010927 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
Chris Lattnereed48272005-09-13 00:40:14 +000010928 if (!isa<PointerType>(X->getType())) {
10929 // Not interesting. Source pointer must be a cast from pointer.
10930 } else if (HasZeroPointerIndex) {
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010931 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
10932 // into : GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +000010933 //
Duncan Sands5b7cfb02009-03-02 09:18:21 +000010934 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
10935 // into : GEP i8* X, ...
10936 //
Chris Lattnereed48272005-09-13 00:40:14 +000010937 // This occurs when the program declares an array extern like "int X[];"
Chris Lattnereed48272005-09-13 00:40:14 +000010938 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
10939 const PointerType *XTy = cast<PointerType>(X->getType());
Duncan Sands5b7cfb02009-03-02 09:18:21 +000010940 if (const ArrayType *CATy =
10941 dyn_cast<ArrayType>(CPTy->getElementType())) {
10942 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
10943 if (CATy->getElementType() == XTy->getElementType()) {
10944 // -> GEP i8* X, ...
10945 SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
10946 return GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
10947 GEP.getName());
10948 } else if (const ArrayType *XATy =
10949 dyn_cast<ArrayType>(XTy->getElementType())) {
10950 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
Chris Lattnereed48272005-09-13 00:40:14 +000010951 if (CATy->getElementType() == XATy->getElementType()) {
Duncan Sands5b7cfb02009-03-02 09:18:21 +000010952 // -> GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +000010953 // At this point, we know that the cast source type is a pointer
10954 // to an array of the same type as the destination pointer
10955 // array. Because the array type is never stepped over (there
10956 // is a leading zero) we can fold the cast into this GEP.
10957 GEP.setOperand(0, X);
10958 return &GEP;
10959 }
Duncan Sands5b7cfb02009-03-02 09:18:21 +000010960 }
10961 }
Chris Lattnereed48272005-09-13 00:40:14 +000010962 } else if (GEP.getNumOperands() == 2) {
10963 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010964 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
10965 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnereed48272005-09-13 00:40:14 +000010966 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
10967 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
10968 if (isa<ArrayType>(SrcElTy) &&
Duncan Sandsceb4d1a2009-01-12 20:38:59 +000010969 TD->getTypePaddedSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
10970 TD->getTypePaddedSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +000010971 Value *Idx[2];
10972 Idx[0] = Constant::getNullValue(Type::Int32Ty);
10973 Idx[1] = GEP.getOperand(1);
Chris Lattnereed48272005-09-13 00:40:14 +000010974 Value *V = InsertNewInstBefore(
Gabor Greif051a9502008-04-06 20:25:17 +000010975 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
Reid Spencer3da59db2006-11-27 01:05:10 +000010976 // V and GEP are both pointer types --> BitCast
10977 return new BitCastInst(V, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010978 }
Chris Lattner7835cdd2005-09-13 18:36:04 +000010979
10980 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010981 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +000010982 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010983 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +000010984
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010985 if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
Chris Lattner7835cdd2005-09-13 18:36:04 +000010986 uint64_t ArrayEltSize =
Duncan Sandsceb4d1a2009-01-12 20:38:59 +000010987 TD->getTypePaddedSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000010988
10989 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
10990 // allow either a mul, shift, or constant here.
10991 Value *NewIdx = 0;
10992 ConstantInt *Scale = 0;
10993 if (ArrayEltSize == 1) {
10994 NewIdx = GEP.getOperand(1);
10995 Scale = ConstantInt::get(NewIdx->getType(), 1);
10996 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattner6e2f8432005-09-14 17:32:56 +000010997 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000010998 Scale = CI;
10999 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11000 if (Inst->getOpcode() == Instruction::Shl &&
11001 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +000011002 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11003 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
11004 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011005 NewIdx = Inst->getOperand(0);
11006 } else if (Inst->getOpcode() == Instruction::Mul &&
11007 isa<ConstantInt>(Inst->getOperand(1))) {
11008 Scale = cast<ConstantInt>(Inst->getOperand(1));
11009 NewIdx = Inst->getOperand(0);
11010 }
11011 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011012
Chris Lattner7835cdd2005-09-13 18:36:04 +000011013 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011014 // out, perform the transformation. Note, we don't know whether Scale is
11015 // signed or not. We'll use unsigned version of division/modulo
11016 // operation after making sure Scale doesn't have the sign bit set.
Chris Lattner58b1ac72009-02-25 18:20:01 +000011017 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011018 Scale->getZExtValue() % ArrayEltSize == 0) {
11019 Scale = ConstantInt::get(Scale->getType(),
11020 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +000011021 if (Scale->getZExtValue() != 1) {
Reid Spencer17212df2006-12-12 09:18:51 +000011022 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011023 false /*ZExt*/);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000011024 Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
Chris Lattner7835cdd2005-09-13 18:36:04 +000011025 NewIdx = InsertNewInstBefore(Sc, GEP);
11026 }
11027
11028 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +000011029 Value *Idx[2];
11030 Idx[0] = Constant::getNullValue(Type::Int32Ty);
11031 Idx[1] = NewIdx;
Reid Spencer3da59db2006-11-27 01:05:10 +000011032 Instruction *NewGEP =
Gabor Greif051a9502008-04-06 20:25:17 +000011033 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +000011034 NewGEP = InsertNewInstBefore(NewGEP, GEP);
11035 // The NewGEP must be pointer typed, so must the old one -> BitCast
11036 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000011037 }
11038 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011039 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000011040 }
Chris Lattner58407792009-01-09 04:53:57 +000011041
Chris Lattner46cd5a12009-01-09 05:44:56 +000011042 /// See if we can simplify:
11043 /// X = bitcast A to B*
11044 /// Y = gep X, <...constant indices...>
11045 /// into a gep of the original struct. This is important for SROA and alias
11046 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattner58407792009-01-09 04:53:57 +000011047 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +000011048 if (!isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
11049 // Determine how much the GEP moves the pointer. We are guaranteed to get
11050 // a constant back from EmitGEPOffset.
11051 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
11052 int64_t Offset = OffsetV->getSExtValue();
11053
11054 // If this GEP instruction doesn't move the pointer, just replace the GEP
11055 // with a bitcast of the real input to the dest type.
11056 if (Offset == 0) {
11057 // If the bitcast is of an allocation, and the allocation will be
11058 // converted to match the type of the cast, don't touch this.
11059 if (isa<AllocationInst>(BCI->getOperand(0))) {
11060 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11061 if (Instruction *I = visitBitCast(*BCI)) {
11062 if (I != BCI) {
11063 I->takeName(BCI);
11064 BCI->getParent()->getInstList().insert(BCI, I);
11065 ReplaceInstUsesWith(*BCI, I);
11066 }
11067 return &GEP;
Chris Lattner58407792009-01-09 04:53:57 +000011068 }
Chris Lattner58407792009-01-09 04:53:57 +000011069 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000011070 return new BitCastInst(BCI->getOperand(0), GEP.getType());
Chris Lattner58407792009-01-09 04:53:57 +000011071 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000011072
11073 // Otherwise, if the offset is non-zero, we need to find out if there is a
11074 // field at Offset in 'A's type. If so, we can pull the cast through the
11075 // GEP.
11076 SmallVector<Value*, 8> NewIndices;
11077 const Type *InTy =
11078 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
11079 if (FindElementAtOffset(InTy, Offset, NewIndices, TD)) {
11080 Instruction *NGEP =
11081 GetElementPtrInst::Create(BCI->getOperand(0), NewIndices.begin(),
11082 NewIndices.end());
11083 if (NGEP->getType() == GEP.getType()) return NGEP;
11084 InsertNewInstBefore(NGEP, GEP);
11085 NGEP->takeName(&GEP);
11086 return new BitCastInst(NGEP, GEP.getType());
11087 }
Chris Lattner58407792009-01-09 04:53:57 +000011088 }
11089 }
11090
Chris Lattner8a2a3112001-12-14 16:52:21 +000011091 return 0;
11092}
11093
Chris Lattner0864acf2002-11-04 16:18:53 +000011094Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
11095 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011096 if (AI.isArrayAllocation()) { // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +000011097 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11098 const Type *NewTy =
11099 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattner0006bd72002-11-09 00:49:43 +000011100 AllocationInst *New = 0;
Chris Lattner0864acf2002-11-04 16:18:53 +000011101
11102 // Create and insert the replacement instruction...
11103 if (isa<MallocInst>(AI))
Nate Begeman14b05292005-11-05 09:21:28 +000011104 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000011105 else {
11106 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman14b05292005-11-05 09:21:28 +000011107 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000011108 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011109
11110 InsertNewInstBefore(New, AI);
Misha Brukmanfd939082005-04-21 23:48:37 +000011111
Chris Lattner0864acf2002-11-04 16:18:53 +000011112 // Scan to the end of the allocation instructions, to skip over a block of
Dale Johannesena8915182009-03-11 22:19:43 +000011113 // allocas if possible...also skip interleaved debug info
Chris Lattner0864acf2002-11-04 16:18:53 +000011114 //
11115 BasicBlock::iterator It = New;
Dale Johannesena8915182009-03-11 22:19:43 +000011116 while (isa<AllocationInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
Chris Lattner0864acf2002-11-04 16:18:53 +000011117
11118 // Now that I is pointing to the first non-allocation-inst in the block,
11119 // insert our getelementptr instruction...
11120 //
Reid Spencerc5b206b2006-12-31 05:48:39 +000011121 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
David Greeneb8f74792007-09-04 15:46:09 +000011122 Value *Idx[2];
11123 Idx[0] = NullIdx;
11124 Idx[1] = NullIdx;
Gabor Greif051a9502008-04-06 20:25:17 +000011125 Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
11126 New->getName()+".sub", It);
Chris Lattner0864acf2002-11-04 16:18:53 +000011127
11128 // Now make everything use the getelementptr instead of the original
11129 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +000011130 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +000011131 } else if (isa<UndefValue>(AI.getArraySize())) {
11132 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +000011133 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011134 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011135
Dan Gohman6893cd72009-01-13 20:18:38 +000011136 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
11137 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
Chris Lattner46d232d2009-03-17 17:55:15 +000011138 // Note that we only do this for alloca's, because malloc should allocate
11139 // and return a unique pointer, even for a zero byte allocation.
Dan Gohman6893cd72009-01-13 20:18:38 +000011140 if (TD->getTypePaddedSize(AI.getAllocatedType()) == 0)
11141 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
11142
11143 // If the alignment is 0 (unspecified), assign it the preferred alignment.
11144 if (AI.getAlignment() == 0)
11145 AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11146 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011147
Chris Lattner0864acf2002-11-04 16:18:53 +000011148 return 0;
11149}
11150
Chris Lattner67b1e1b2003-12-07 01:24:23 +000011151Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
11152 Value *Op = FI.getOperand(0);
11153
Chris Lattner17be6352004-10-18 02:59:09 +000011154 // free undef -> unreachable.
11155 if (isa<UndefValue>(Op)) {
11156 // Insert a new store to null because we cannot modify the CFG here.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +000011157 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +000011158 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
Chris Lattner17be6352004-10-18 02:59:09 +000011159 return EraseInstFromFunction(FI);
11160 }
Chris Lattner6fe55412007-04-14 00:20:02 +000011161
Chris Lattner6160e852004-02-28 04:57:37 +000011162 // If we have 'free null' delete the instruction. This can happen in stl code
11163 // when lots of inlining happens.
Chris Lattner17be6352004-10-18 02:59:09 +000011164 if (isa<ConstantPointerNull>(Op))
Chris Lattner7bcc0e72004-02-28 05:22:00 +000011165 return EraseInstFromFunction(FI);
Chris Lattner6fe55412007-04-14 00:20:02 +000011166
11167 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
11168 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
11169 FI.setOperand(0, CI->getOperand(0));
11170 return &FI;
11171 }
11172
11173 // Change free (gep X, 0,0,0,0) into free(X)
11174 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11175 if (GEPI->hasAllZeroIndices()) {
11176 AddToWorkList(GEPI);
11177 FI.setOperand(0, GEPI->getOperand(0));
11178 return &FI;
11179 }
11180 }
11181
11182 // Change free(malloc) into nothing, if the malloc has a single use.
11183 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
11184 if (MI->hasOneUse()) {
11185 EraseInstFromFunction(FI);
11186 return EraseInstFromFunction(*MI);
11187 }
Chris Lattner6160e852004-02-28 04:57:37 +000011188
Chris Lattner67b1e1b2003-12-07 01:24:23 +000011189 return 0;
11190}
11191
11192
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011193/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patel99db6ad2007-10-18 19:52:32 +000011194static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling587c01d2008-02-26 10:53:30 +000011195 const TargetData *TD) {
Chris Lattnerb89e0712004-07-13 01:49:43 +000011196 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +000011197 Value *CastOp = CI->getOperand(0);
Chris Lattnerb89e0712004-07-13 01:49:43 +000011198
Nick Lewycky48f95ad2009-05-08 06:47:37 +000011199 if (TD) {
11200 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
11201 // Instead of loading constant c string, use corresponding integer value
11202 // directly if string length is small enough.
11203 std::string Str;
11204 if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
11205 unsigned len = Str.length();
11206 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
11207 unsigned numBits = Ty->getPrimitiveSizeInBits();
11208 // Replace LI with immediate integer store.
11209 if ((numBits >> 3) == len + 1) {
11210 APInt StrVal(numBits, 0);
11211 APInt SingleChar(numBits, 0);
11212 if (TD->isLittleEndian()) {
11213 for (signed i = len-1; i >= 0; i--) {
11214 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11215 StrVal = (StrVal << 8) | SingleChar;
11216 }
11217 } else {
11218 for (unsigned i = 0; i < len; i++) {
11219 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11220 StrVal = (StrVal << 8) | SingleChar;
11221 }
11222 // Append NULL at the end.
11223 SingleChar = 0;
Bill Wendling587c01d2008-02-26 10:53:30 +000011224 StrVal = (StrVal << 8) | SingleChar;
11225 }
Nick Lewycky48f95ad2009-05-08 06:47:37 +000011226 Value *NL = ConstantInt::get(StrVal);
11227 return IC.ReplaceInstUsesWith(LI, NL);
Bill Wendling587c01d2008-02-26 10:53:30 +000011228 }
Devang Patel99db6ad2007-10-18 19:52:32 +000011229 }
11230 }
11231 }
11232
Mon P Wang6753f952009-02-07 22:19:29 +000011233 const PointerType *DestTy = cast<PointerType>(CI->getType());
11234 const Type *DestPTy = DestTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000011235 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Mon P Wang6753f952009-02-07 22:19:29 +000011236
11237 // If the address spaces don't match, don't eliminate the cast.
11238 if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11239 return 0;
11240
Chris Lattnerb89e0712004-07-13 01:49:43 +000011241 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000011242
Reid Spencer42230162007-01-22 05:51:25 +000011243 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000011244 isa<VectorType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +000011245 // If the source is an array, the code below will not succeed. Check to
11246 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11247 // constants.
11248 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11249 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11250 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +000011251 Value *Idxs[2];
11252 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
11253 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerf9527852005-01-31 04:50:46 +000011254 SrcTy = cast<PointerType>(CastOp->getType());
11255 SrcPTy = SrcTy->getElementType();
11256 }
11257
Reid Spencer42230162007-01-22 05:51:25 +000011258 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000011259 isa<VectorType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +000011260 // Do not allow turning this into a load of an integer, which is then
11261 // casted to a pointer, this pessimizes pointer analysis a lot.
11262 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Reid Spencer42230162007-01-22 05:51:25 +000011263 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
11264 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +000011265
Chris Lattnerf9527852005-01-31 04:50:46 +000011266 // Okay, we are casting from one integer or pointer type to another of
11267 // the same size. Instead of casting the pointer before the load, cast
11268 // the result of the loaded value.
11269 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
11270 CI->getName(),
11271 LI.isVolatile()),LI);
11272 // Now cast the result of the load.
Reid Spencerd977d862006-12-12 23:36:14 +000011273 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerf9527852005-01-31 04:50:46 +000011274 }
Chris Lattnerb89e0712004-07-13 01:49:43 +000011275 }
11276 }
11277 return 0;
11278}
11279
Chris Lattnerc10aced2004-09-19 18:43:46 +000011280/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattner8a375202004-09-19 19:18:10 +000011281/// from this value cannot trap. If it is not obviously safe to load from the
11282/// specified pointer, we do a quick local scan of the basic block containing
11283/// ScanFrom, to determine if the address is already accessed.
11284static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
Duncan Sands892c7e42007-09-19 10:10:31 +000011285 // If it is an alloca it is always safe to load from.
11286 if (isa<AllocaInst>(V)) return true;
11287
Duncan Sands46318cd2007-09-19 10:25:38 +000011288 // If it is a global variable it is mostly safe to load from.
Duncan Sands892c7e42007-09-19 10:10:31 +000011289 if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
Duncan Sands46318cd2007-09-19 10:25:38 +000011290 // Don't try to evaluate aliases. External weak GV can be null.
Duncan Sands892c7e42007-09-19 10:10:31 +000011291 return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
Chris Lattner8a375202004-09-19 19:18:10 +000011292
11293 // Otherwise, be a little bit agressive by scanning the local block where we
11294 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +000011295 // from/to. If so, the previous load or store would have already trapped,
11296 // so there is no harm doing an extra load (also, CSE will later eliminate
11297 // the load entirely).
Chris Lattner8a375202004-09-19 19:18:10 +000011298 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
11299
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +000011300 while (BBI != E) {
Chris Lattner8a375202004-09-19 19:18:10 +000011301 --BBI;
11302
Chris Lattner2de3fec2008-06-20 05:12:56 +000011303 // If we see a free or a call (which might do a free) the pointer could be
11304 // marked invalid.
Dale Johannesend1c135c2009-03-13 19:23:20 +000011305 if (isa<FreeInst>(BBI) ||
11306 (isa<CallInst>(BBI) && !isa<DbgInfoIntrinsic>(BBI)))
Chris Lattner2de3fec2008-06-20 05:12:56 +000011307 return false;
11308
Chris Lattner8a375202004-09-19 19:18:10 +000011309 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
11310 if (LI->getOperand(0) == V) return true;
Chris Lattner2de3fec2008-06-20 05:12:56 +000011311 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
Chris Lattner8a375202004-09-19 19:18:10 +000011312 if (SI->getOperand(1) == V) return true;
Chris Lattner2de3fec2008-06-20 05:12:56 +000011313 }
Misha Brukmanfd939082005-04-21 23:48:37 +000011314
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +000011315 }
Chris Lattner8a375202004-09-19 19:18:10 +000011316 return false;
Chris Lattnerc10aced2004-09-19 18:43:46 +000011317}
11318
Chris Lattner833b8a42003-06-26 05:06:25 +000011319Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11320 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +000011321
Dan Gohman9941f742007-07-20 16:34:21 +000011322 // Attempt to improve the alignment.
Dan Gohman926b0a22009-02-16 00:44:23 +000011323 unsigned KnownAlign =
11324 GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
Dan Gohmaneee962e2008-04-10 18:43:06 +000011325 if (KnownAlign >
11326 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11327 LI.getAlignment()))
Dan Gohman9941f742007-07-20 16:34:21 +000011328 LI.setAlignment(KnownAlign);
11329
Chris Lattner37366c12005-05-01 04:24:53 +000011330 // load (cast X) --> cast (load X) iff safe
Reid Spencer3ed469c2006-11-02 20:25:50 +000011331 if (isa<CastInst>(Op))
Devang Patel99db6ad2007-10-18 19:52:32 +000011332 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattner37366c12005-05-01 04:24:53 +000011333 return Res;
11334
11335 // None of the following transforms are legal for volatile loads.
11336 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +000011337
Dan Gohman2276a7b2008-10-15 23:19:35 +000011338 // Do really simple store-to-load forwarding and load CSE, to catch cases
11339 // where there are several consequtive memory accesses to the same location,
11340 // separated by a few arithmetic operations.
11341 BasicBlock::iterator BBI = &LI;
Chris Lattner4aebaee2008-11-27 08:56:30 +000011342 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11343 return ReplaceInstUsesWith(LI, AvailableVal);
Chris Lattner37366c12005-05-01 04:24:53 +000011344
Christopher Lambb15147e2007-12-29 07:56:53 +000011345 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11346 const Value *GEPI0 = GEPI->getOperand(0);
11347 // TODO: Consider a target hook for valid address spaces for this xform.
11348 if (isa<ConstantPointerNull>(GEPI0) &&
11349 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
Chris Lattner37366c12005-05-01 04:24:53 +000011350 // Insert a new store to null instruction before the load to indicate
11351 // that this code is not reachable. We do this instead of inserting
11352 // an unreachable instruction directly because we cannot modify the
11353 // CFG.
11354 new StoreInst(UndefValue::get(LI.getType()),
11355 Constant::getNullValue(Op->getType()), &LI);
11356 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11357 }
Christopher Lambb15147e2007-12-29 07:56:53 +000011358 }
Chris Lattner37366c12005-05-01 04:24:53 +000011359
Chris Lattnere87597f2004-10-16 18:11:37 +000011360 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner37366c12005-05-01 04:24:53 +000011361 // load null/undef -> undef
Christopher Lambb15147e2007-12-29 07:56:53 +000011362 // TODO: Consider a target hook for valid address spaces for this xform.
11363 if (isa<UndefValue>(C) || (C->isNullValue() &&
11364 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
Chris Lattner17be6352004-10-18 02:59:09 +000011365 // Insert a new store to null instruction before the load to indicate that
11366 // this code is not reachable. We do this instead of inserting an
11367 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattner37366c12005-05-01 04:24:53 +000011368 new StoreInst(UndefValue::get(LI.getType()),
11369 Constant::getNullValue(Op->getType()), &LI);
Chris Lattnere87597f2004-10-16 18:11:37 +000011370 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner17be6352004-10-18 02:59:09 +000011371 }
Chris Lattner833b8a42003-06-26 05:06:25 +000011372
Chris Lattnere87597f2004-10-16 18:11:37 +000011373 // Instcombine load (constant global) into the value loaded.
11374 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Duncan Sands64da9402009-03-21 21:27:31 +000011375 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Chris Lattnere87597f2004-10-16 18:11:37 +000011376 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +000011377
Chris Lattnere87597f2004-10-16 18:11:37 +000011378 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011379 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
Chris Lattnere87597f2004-10-16 18:11:37 +000011380 if (CE->getOpcode() == Instruction::GetElementPtr) {
11381 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Duncan Sands64da9402009-03-21 21:27:31 +000011382 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Chris Lattner363f2a22005-09-26 05:28:06 +000011383 if (Constant *V =
11384 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattnere87597f2004-10-16 18:11:37 +000011385 return ReplaceInstUsesWith(LI, V);
Chris Lattner37366c12005-05-01 04:24:53 +000011386 if (CE->getOperand(0)->isNullValue()) {
11387 // Insert a new store to null instruction before the load to indicate
11388 // that this code is not reachable. We do this instead of inserting
11389 // an unreachable instruction directly because we cannot modify the
11390 // CFG.
11391 new StoreInst(UndefValue::get(LI.getType()),
11392 Constant::getNullValue(Op->getType()), &LI);
11393 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11394 }
11395
Reid Spencer3da59db2006-11-27 01:05:10 +000011396 } else if (CE->isCast()) {
Devang Patel99db6ad2007-10-18 19:52:32 +000011397 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattnere87597f2004-10-16 18:11:37 +000011398 return Res;
11399 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011400 }
Chris Lattnere87597f2004-10-16 18:11:37 +000011401 }
Chris Lattner8d2e8882007-08-11 18:48:48 +000011402
11403 // If this load comes from anywhere in a constant global, and if the global
11404 // is all undef or zero, we know what it loads.
Duncan Sands5d0392c2008-10-01 15:25:41 +000011405 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
Duncan Sands64da9402009-03-21 21:27:31 +000011406 if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
Chris Lattner8d2e8882007-08-11 18:48:48 +000011407 if (GV->getInitializer()->isNullValue())
11408 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
11409 else if (isa<UndefValue>(GV->getInitializer()))
11410 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11411 }
11412 }
Chris Lattnerf499eac2004-04-08 20:39:49 +000011413
Chris Lattner37366c12005-05-01 04:24:53 +000011414 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000011415 // Change select and PHI nodes to select values instead of addresses: this
11416 // helps alias analysis out a lot, allows many others simplifications, and
11417 // exposes redundancy in the code.
11418 //
11419 // Note that we cannot do the transformation unless we know that the
11420 // introduced loads cannot trap! Something like this is valid as long as
11421 // the condition is always false: load (select bool %C, int* null, int* %G),
11422 // but it would not be valid if we transformed it to load from null
11423 // unconditionally.
11424 //
11425 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11426 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +000011427 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11428 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000011429 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000011430 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +000011431 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000011432 SI->getOperand(2)->getName()+".val"), LI);
Gabor Greif051a9502008-04-06 20:25:17 +000011433 return SelectInst::Create(SI->getCondition(), V1, V2);
Chris Lattnerc10aced2004-09-19 18:43:46 +000011434 }
11435
Chris Lattner684fe212004-09-23 15:46:00 +000011436 // load (select (cond, null, P)) -> load P
11437 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11438 if (C->isNullValue()) {
11439 LI.setOperand(0, SI->getOperand(2));
11440 return &LI;
11441 }
11442
11443 // load (select (cond, P, null)) -> load P
11444 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11445 if (C->isNullValue()) {
11446 LI.setOperand(0, SI->getOperand(1));
11447 return &LI;
11448 }
Chris Lattnerc10aced2004-09-19 18:43:46 +000011449 }
11450 }
Chris Lattner833b8a42003-06-26 05:06:25 +000011451 return 0;
11452}
11453
Reid Spencer55af2b52007-01-19 21:20:31 +000011454/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattner3914f722009-01-24 01:00:13 +000011455/// when possible. This makes it generally easy to do alias analysis and/or
11456/// SROA/mem2reg of the memory object.
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011457static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11458 User *CI = cast<User>(SI.getOperand(1));
11459 Value *CastOp = CI->getOperand(0);
11460
11461 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011462 const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11463 if (SrcTy == 0) return 0;
11464
11465 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011466
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011467 if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11468 return 0;
11469
Chris Lattner3914f722009-01-24 01:00:13 +000011470 /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11471 /// to its first element. This allows us to handle things like:
11472 /// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11473 /// on 32-bit hosts.
11474 SmallVector<Value*, 4> NewGEPIndices;
11475
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011476 // If the source is an array, the code below will not succeed. Check to
11477 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11478 // constants.
Chris Lattner3914f722009-01-24 01:00:13 +000011479 if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11480 // Index through pointer.
11481 Constant *Zero = Constant::getNullValue(Type::Int32Ty);
11482 NewGEPIndices.push_back(Zero);
11483
11484 while (1) {
11485 if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
Torok Edwin08ffee52009-01-24 17:16:04 +000011486 if (!STy->getNumElements()) /* Struct can be empty {} */
Torok Edwin629e92b2009-01-24 11:30:49 +000011487 break;
Chris Lattner3914f722009-01-24 01:00:13 +000011488 NewGEPIndices.push_back(Zero);
11489 SrcPTy = STy->getElementType(0);
11490 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11491 NewGEPIndices.push_back(Zero);
11492 SrcPTy = ATy->getElementType();
11493 } else {
11494 break;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011495 }
Chris Lattner3914f722009-01-24 01:00:13 +000011496 }
11497
11498 SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
11499 }
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011500
11501 if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11502 return 0;
11503
Chris Lattner71759c42009-01-16 20:12:52 +000011504 // If the pointers point into different address spaces or if they point to
11505 // values with different sizes, we can't do the transformation.
11506 if (SrcTy->getAddressSpace() !=
11507 cast<PointerType>(CI->getType())->getAddressSpace() ||
11508 IC.getTargetData().getTypeSizeInBits(SrcPTy) !=
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011509 IC.getTargetData().getTypeSizeInBits(DestPTy))
11510 return 0;
11511
11512 // Okay, we are casting from one integer or pointer type to another of
11513 // the same size. Instead of casting the pointer before
11514 // the store, cast the value to be stored.
11515 Value *NewCast;
11516 Value *SIOp0 = SI.getOperand(0);
11517 Instruction::CastOps opcode = Instruction::BitCast;
11518 const Type* CastSrcTy = SIOp0->getType();
11519 const Type* CastDstTy = SrcPTy;
11520 if (isa<PointerType>(CastDstTy)) {
11521 if (CastSrcTy->isInteger())
11522 opcode = Instruction::IntToPtr;
11523 } else if (isa<IntegerType>(CastDstTy)) {
11524 if (isa<PointerType>(SIOp0->getType()))
11525 opcode = Instruction::PtrToInt;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011526 }
Chris Lattner3914f722009-01-24 01:00:13 +000011527
11528 // SIOp0 is a pointer to aggregate and this is a store to the first field,
11529 // emit a GEP to index into its first field.
11530 if (!NewGEPIndices.empty()) {
11531 if (Constant *C = dyn_cast<Constant>(CastOp))
11532 CastOp = ConstantExpr::getGetElementPtr(C, &NewGEPIndices[0],
11533 NewGEPIndices.size());
11534 else
11535 CastOp = IC.InsertNewInstBefore(
11536 GetElementPtrInst::Create(CastOp, NewGEPIndices.begin(),
11537 NewGEPIndices.end()), SI);
11538 }
11539
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011540 if (Constant *C = dyn_cast<Constant>(SIOp0))
11541 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
11542 else
11543 NewCast = IC.InsertNewInstBefore(
11544 CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
11545 SI);
11546 return new StoreInst(NewCast, CastOp);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011547}
11548
Chris Lattner4aebaee2008-11-27 08:56:30 +000011549/// equivalentAddressValues - Test if A and B will obviously have the same
11550/// value. This includes recognizing that %t0 and %t1 will have the same
11551/// value in code like this:
Dan Gohman0f8b53f2009-03-03 02:55:14 +000011552/// %t0 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000011553/// store i32 0, i32* %t0
Dan Gohman0f8b53f2009-03-03 02:55:14 +000011554/// %t1 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000011555/// %t2 = load i32* %t1
11556///
11557static bool equivalentAddressValues(Value *A, Value *B) {
11558 // Test if the values are trivially equivalent.
11559 if (A == B) return true;
11560
11561 // Test if the values come form identical arithmetic instructions.
11562 if (isa<BinaryOperator>(A) ||
11563 isa<CastInst>(A) ||
11564 isa<PHINode>(A) ||
11565 isa<GetElementPtrInst>(A))
11566 if (Instruction *BI = dyn_cast<Instruction>(B))
11567 if (cast<Instruction>(A)->isIdenticalTo(BI))
11568 return true;
11569
11570 // Otherwise they may not be equivalent.
11571 return false;
11572}
11573
Dale Johannesen4945c652009-03-03 21:26:39 +000011574// If this instruction has two uses, one of which is a llvm.dbg.declare,
11575// return the llvm.dbg.declare.
11576DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11577 if (!V->hasNUses(2))
11578 return 0;
11579 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11580 UI != E; ++UI) {
11581 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11582 return DI;
11583 if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11584 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11585 return DI;
11586 }
11587 }
11588 return 0;
11589}
11590
Chris Lattner2f503e62005-01-31 05:36:43 +000011591Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11592 Value *Val = SI.getOperand(0);
11593 Value *Ptr = SI.getOperand(1);
11594
11595 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner9ca96412006-02-08 03:25:32 +000011596 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000011597 ++NumCombined;
11598 return 0;
11599 }
Chris Lattner836692d2007-01-15 06:51:56 +000011600
11601 // If the RHS is an alloca with a single use, zapify the store, making the
11602 // alloca dead.
Dale Johannesen4945c652009-03-03 21:26:39 +000011603 // If the RHS is an alloca with a two uses, the other one being a
11604 // llvm.dbg.declare, zapify the store and the declare, making the
11605 // alloca dead. We must do this to prevent declare's from affecting
11606 // codegen.
11607 if (!SI.isVolatile()) {
11608 if (Ptr->hasOneUse()) {
11609 if (isa<AllocaInst>(Ptr)) {
Chris Lattner836692d2007-01-15 06:51:56 +000011610 EraseInstFromFunction(SI);
11611 ++NumCombined;
11612 return 0;
11613 }
Dale Johannesen4945c652009-03-03 21:26:39 +000011614 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11615 if (isa<AllocaInst>(GEP->getOperand(0))) {
11616 if (GEP->getOperand(0)->hasOneUse()) {
11617 EraseInstFromFunction(SI);
11618 ++NumCombined;
11619 return 0;
11620 }
11621 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11622 EraseInstFromFunction(*DI);
11623 EraseInstFromFunction(SI);
11624 ++NumCombined;
11625 return 0;
11626 }
11627 }
11628 }
11629 }
11630 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11631 EraseInstFromFunction(*DI);
11632 EraseInstFromFunction(SI);
11633 ++NumCombined;
11634 return 0;
11635 }
Chris Lattner836692d2007-01-15 06:51:56 +000011636 }
Chris Lattner2f503e62005-01-31 05:36:43 +000011637
Dan Gohman9941f742007-07-20 16:34:21 +000011638 // Attempt to improve the alignment.
Dan Gohman926b0a22009-02-16 00:44:23 +000011639 unsigned KnownAlign =
11640 GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
Dan Gohmaneee962e2008-04-10 18:43:06 +000011641 if (KnownAlign >
11642 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11643 SI.getAlignment()))
Dan Gohman9941f742007-07-20 16:34:21 +000011644 SI.setAlignment(KnownAlign);
11645
Dale Johannesenacb51a32009-03-03 01:43:03 +000011646 // Do really simple DSE, to catch cases where there are several consecutive
Chris Lattner9ca96412006-02-08 03:25:32 +000011647 // stores to the same location, separated by a few arithmetic operations. This
11648 // situation often occurs with bitfield accesses.
11649 BasicBlock::iterator BBI = &SI;
11650 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11651 --ScanInsts) {
Dale Johannesen0d6596b2009-03-04 01:20:34 +000011652 --BBI;
Dale Johannesencdb16aa2009-03-04 01:53:05 +000011653 // Don't count debug info directives, lest they affect codegen,
11654 // and we skip pointer-to-pointer bitcasts, which are NOPs.
11655 // It is necessary for correctness to skip those that feed into a
11656 // llvm.dbg.declare, as these are not present when debugging is off.
Dale Johannesen4ded40a2009-03-03 22:36:47 +000011657 if (isa<DbgInfoIntrinsic>(BBI) ||
Dale Johannesencdb16aa2009-03-04 01:53:05 +000011658 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
Dale Johannesenacb51a32009-03-03 01:43:03 +000011659 ScanInsts++;
Dale Johannesenacb51a32009-03-03 01:43:03 +000011660 continue;
11661 }
Chris Lattner9ca96412006-02-08 03:25:32 +000011662
11663 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11664 // Prev store isn't volatile, and stores to the same location?
Chris Lattner4aebaee2008-11-27 08:56:30 +000011665 if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11666 SI.getOperand(1))) {
Chris Lattner9ca96412006-02-08 03:25:32 +000011667 ++NumDeadStore;
11668 ++BBI;
11669 EraseInstFromFunction(*PrevSI);
11670 continue;
11671 }
11672 break;
11673 }
11674
Chris Lattnerb4db97f2006-05-26 19:19:20 +000011675 // If this is a load, we have to stop. However, if the loaded value is from
11676 // the pointer we're loading and is producing the pointer we're storing,
11677 // then *this* store is dead (X = load P; store X -> P).
11678 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Dan Gohman2276a7b2008-10-15 23:19:35 +000011679 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11680 !SI.isVolatile()) {
Chris Lattnerb4db97f2006-05-26 19:19:20 +000011681 EraseInstFromFunction(SI);
11682 ++NumCombined;
11683 return 0;
11684 }
11685 // Otherwise, this is a load from some other location. Stores before it
11686 // may not be dead.
11687 break;
11688 }
11689
Chris Lattner9ca96412006-02-08 03:25:32 +000011690 // Don't skip over loads or things that can modify memory.
Chris Lattner0ef546e2008-05-08 17:20:30 +000011691 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +000011692 break;
11693 }
11694
11695
11696 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +000011697
11698 // store X, null -> turns into 'unreachable' in SimplifyCFG
11699 if (isa<ConstantPointerNull>(Ptr)) {
11700 if (!isa<UndefValue>(Val)) {
11701 SI.setOperand(0, UndefValue::get(Val->getType()));
11702 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattnerdbab3862007-03-02 21:28:56 +000011703 AddToWorkList(U); // Dropped a use.
Chris Lattner2f503e62005-01-31 05:36:43 +000011704 ++NumCombined;
11705 }
11706 return 0; // Do not modify these!
11707 }
11708
11709 // store undef, Ptr -> noop
11710 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +000011711 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000011712 ++NumCombined;
11713 return 0;
11714 }
11715
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011716 // If the pointer destination is a cast, see if we can fold the cast into the
11717 // source instead.
Reid Spencer3ed469c2006-11-02 20:25:50 +000011718 if (isa<CastInst>(Ptr))
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011719 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11720 return Res;
11721 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer3da59db2006-11-27 01:05:10 +000011722 if (CE->isCast())
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011723 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11724 return Res;
11725
Chris Lattner408902b2005-09-12 23:23:25 +000011726
Dale Johannesen4084c4e2009-03-05 02:06:48 +000011727 // If this store is the last instruction in the basic block (possibly
11728 // excepting debug info instructions and the pointer bitcasts that feed
11729 // into them), and if the block ends with an unconditional branch, try
11730 // to move it to the successor block.
11731 BBI = &SI;
11732 do {
11733 ++BBI;
11734 } while (isa<DbgInfoIntrinsic>(BBI) ||
11735 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
Chris Lattner408902b2005-09-12 23:23:25 +000011736 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011737 if (BI->isUnconditional())
11738 if (SimplifyStoreAtEndOfBlock(SI))
11739 return 0; // xform done!
Chris Lattner408902b2005-09-12 23:23:25 +000011740
Chris Lattner2f503e62005-01-31 05:36:43 +000011741 return 0;
11742}
11743
Chris Lattner3284d1f2007-04-15 00:07:55 +000011744/// SimplifyStoreAtEndOfBlock - Turn things like:
11745/// if () { *P = v1; } else { *P = v2 }
11746/// into a phi node with a store in the successor.
11747///
Chris Lattner31755a02007-04-15 01:02:18 +000011748/// Simplify things like:
11749/// *P = v1; if () { *P = v2; }
11750/// into a phi node with a store in the successor.
11751///
Chris Lattner3284d1f2007-04-15 00:07:55 +000011752bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11753 BasicBlock *StoreBB = SI.getParent();
11754
11755 // Check to see if the successor block has exactly two incoming edges. If
11756 // so, see if the other predecessor contains a store to the same location.
11757 // if so, insert a PHI node (if needed) and move the stores down.
Chris Lattner31755a02007-04-15 01:02:18 +000011758 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Chris Lattner3284d1f2007-04-15 00:07:55 +000011759
11760 // Determine whether Dest has exactly two predecessors and, if so, compute
11761 // the other predecessor.
Chris Lattner31755a02007-04-15 01:02:18 +000011762 pred_iterator PI = pred_begin(DestBB);
11763 BasicBlock *OtherBB = 0;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011764 if (*PI != StoreBB)
Chris Lattner31755a02007-04-15 01:02:18 +000011765 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011766 ++PI;
Chris Lattner31755a02007-04-15 01:02:18 +000011767 if (PI == pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011768 return false;
11769
11770 if (*PI != StoreBB) {
Chris Lattner31755a02007-04-15 01:02:18 +000011771 if (OtherBB)
Chris Lattner3284d1f2007-04-15 00:07:55 +000011772 return false;
Chris Lattner31755a02007-04-15 01:02:18 +000011773 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011774 }
Chris Lattner31755a02007-04-15 01:02:18 +000011775 if (++PI != pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011776 return false;
Eli Friedman66fe80a2008-06-13 21:17:49 +000011777
11778 // Bail out if all the relevant blocks aren't distinct (this can happen,
11779 // for example, if SI is in an infinite loop)
11780 if (StoreBB == DestBB || OtherBB == DestBB)
11781 return false;
11782
Chris Lattner31755a02007-04-15 01:02:18 +000011783 // Verify that the other block ends in a branch and is not otherwise empty.
11784 BasicBlock::iterator BBI = OtherBB->getTerminator();
Chris Lattner3284d1f2007-04-15 00:07:55 +000011785 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
Chris Lattner31755a02007-04-15 01:02:18 +000011786 if (!OtherBr || BBI == OtherBB->begin())
Chris Lattner3284d1f2007-04-15 00:07:55 +000011787 return false;
11788
Chris Lattner31755a02007-04-15 01:02:18 +000011789 // If the other block ends in an unconditional branch, check for the 'if then
11790 // else' case. there is an instruction before the branch.
11791 StoreInst *OtherStore = 0;
11792 if (OtherBr->isUnconditional()) {
Chris Lattner31755a02007-04-15 01:02:18 +000011793 --BBI;
Dale Johannesen4084c4e2009-03-05 02:06:48 +000011794 // Skip over debugging info.
11795 while (isa<DbgInfoIntrinsic>(BBI) ||
11796 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11797 if (BBI==OtherBB->begin())
11798 return false;
11799 --BBI;
11800 }
11801 // If this isn't a store, or isn't a store to the same location, bail out.
Chris Lattner31755a02007-04-15 01:02:18 +000011802 OtherStore = dyn_cast<StoreInst>(BBI);
11803 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
11804 return false;
11805 } else {
Chris Lattnerd717c182007-05-05 22:32:24 +000011806 // Otherwise, the other block ended with a conditional branch. If one of the
Chris Lattner31755a02007-04-15 01:02:18 +000011807 // destinations is StoreBB, then we have the if/then case.
11808 if (OtherBr->getSuccessor(0) != StoreBB &&
11809 OtherBr->getSuccessor(1) != StoreBB)
11810 return false;
11811
11812 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
Chris Lattnerd717c182007-05-05 22:32:24 +000011813 // if/then triangle. See if there is a store to the same ptr as SI that
11814 // lives in OtherBB.
Chris Lattner31755a02007-04-15 01:02:18 +000011815 for (;; --BBI) {
11816 // Check to see if we find the matching store.
11817 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
11818 if (OtherStore->getOperand(1) != SI.getOperand(1))
11819 return false;
11820 break;
11821 }
Eli Friedman6903a242008-06-13 22:02:12 +000011822 // If we find something that may be using or overwriting the stored
11823 // value, or if we run out of instructions, we can't do the xform.
11824 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
Chris Lattner31755a02007-04-15 01:02:18 +000011825 BBI == OtherBB->begin())
11826 return false;
11827 }
11828
11829 // In order to eliminate the store in OtherBr, we have to
Eli Friedman6903a242008-06-13 22:02:12 +000011830 // make sure nothing reads or overwrites the stored value in
11831 // StoreBB.
Chris Lattner31755a02007-04-15 01:02:18 +000011832 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
11833 // FIXME: This should really be AA driven.
Eli Friedman6903a242008-06-13 22:02:12 +000011834 if (I->mayReadFromMemory() || I->mayWriteToMemory())
Chris Lattner31755a02007-04-15 01:02:18 +000011835 return false;
11836 }
11837 }
Chris Lattner3284d1f2007-04-15 00:07:55 +000011838
Chris Lattner31755a02007-04-15 01:02:18 +000011839 // Insert a PHI node now if we need it.
Chris Lattner3284d1f2007-04-15 00:07:55 +000011840 Value *MergedVal = OtherStore->getOperand(0);
11841 if (MergedVal != SI.getOperand(0)) {
Gabor Greif051a9502008-04-06 20:25:17 +000011842 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Chris Lattner3284d1f2007-04-15 00:07:55 +000011843 PN->reserveOperandSpace(2);
11844 PN->addIncoming(SI.getOperand(0), SI.getParent());
Chris Lattner31755a02007-04-15 01:02:18 +000011845 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
11846 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Chris Lattner3284d1f2007-04-15 00:07:55 +000011847 }
11848
11849 // Advance to a place where it is safe to insert the new store and
11850 // insert it.
Dan Gohman02dea8b2008-05-23 21:05:58 +000011851 BBI = DestBB->getFirstNonPHI();
Chris Lattner3284d1f2007-04-15 00:07:55 +000011852 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
11853 OtherStore->isVolatile()), *BBI);
11854
11855 // Nuke the old stores.
11856 EraseInstFromFunction(SI);
11857 EraseInstFromFunction(*OtherStore);
11858 ++NumCombined;
11859 return true;
11860}
11861
Chris Lattner2f503e62005-01-31 05:36:43 +000011862
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000011863Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
11864 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +000011865 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000011866 BasicBlock *TrueDest;
11867 BasicBlock *FalseDest;
11868 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
11869 !isa<Constant>(X)) {
11870 // Swap Destinations and condition...
11871 BI.setCondition(X);
11872 BI.setSuccessor(0, FalseDest);
11873 BI.setSuccessor(1, TrueDest);
11874 return &BI;
11875 }
11876
Reid Spencere4d87aa2006-12-23 06:05:41 +000011877 // Cannonicalize fcmp_one -> fcmp_oeq
11878 FCmpInst::Predicate FPred; Value *Y;
11879 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
11880 TrueDest, FalseDest)))
11881 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
11882 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
11883 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000011884 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
Chris Lattner6934a042007-02-11 01:23:03 +000011885 Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
11886 NewSCC->takeName(I);
Reid Spencere4d87aa2006-12-23 06:05:41 +000011887 // Swap Destinations and condition...
11888 BI.setCondition(NewSCC);
11889 BI.setSuccessor(0, FalseDest);
11890 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000011891 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000011892 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000011893 AddToWorkList(NewSCC);
Reid Spencere4d87aa2006-12-23 06:05:41 +000011894 return &BI;
11895 }
11896
11897 // Cannonicalize icmp_ne -> icmp_eq
11898 ICmpInst::Predicate IPred;
11899 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
11900 TrueDest, FalseDest)))
11901 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
11902 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
11903 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
11904 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000011905 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
Chris Lattner6934a042007-02-11 01:23:03 +000011906 Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
11907 NewSCC->takeName(I);
Chris Lattner40f5d702003-06-04 05:10:11 +000011908 // Swap Destinations and condition...
Chris Lattneracd1f0f2004-07-30 07:50:03 +000011909 BI.setCondition(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000011910 BI.setSuccessor(0, FalseDest);
11911 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000011912 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000011913 I->eraseFromParent();;
Chris Lattnerdbab3862007-03-02 21:28:56 +000011914 AddToWorkList(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000011915 return &BI;
11916 }
Misha Brukmanfd939082005-04-21 23:48:37 +000011917
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000011918 return 0;
11919}
Chris Lattner0864acf2002-11-04 16:18:53 +000011920
Chris Lattner46238a62004-07-03 00:26:11 +000011921Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
11922 Value *Cond = SI.getCondition();
11923 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
11924 if (I->getOpcode() == Instruction::Add)
11925 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
11926 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
11927 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattnere87597f2004-10-16 18:11:37 +000011928 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +000011929 AddRHS));
11930 SI.setOperand(0, I->getOperand(0));
Chris Lattnerdbab3862007-03-02 21:28:56 +000011931 AddToWorkList(I);
Chris Lattner46238a62004-07-03 00:26:11 +000011932 return &SI;
11933 }
11934 }
11935 return 0;
11936}
11937
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000011938Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000011939 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000011940
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000011941 if (!EV.hasIndices())
11942 return ReplaceInstUsesWith(EV, Agg);
11943
11944 if (Constant *C = dyn_cast<Constant>(Agg)) {
11945 if (isa<UndefValue>(C))
11946 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
11947
11948 if (isa<ConstantAggregateZero>(C))
11949 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
11950
11951 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
11952 // Extract the element indexed by the first index out of the constant
11953 Value *V = C->getOperand(*EV.idx_begin());
11954 if (EV.getNumIndices() > 1)
11955 // Extract the remaining indices out of the constant indexed by the
11956 // first index
11957 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
11958 else
11959 return ReplaceInstUsesWith(EV, V);
11960 }
11961 return 0; // Can't handle other constants
11962 }
11963 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
11964 // We're extracting from an insertvalue instruction, compare the indices
11965 const unsigned *exti, *exte, *insi, *inse;
11966 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
11967 exte = EV.idx_end(), inse = IV->idx_end();
11968 exti != exte && insi != inse;
11969 ++exti, ++insi) {
11970 if (*insi != *exti)
11971 // The insert and extract both reference distinctly different elements.
11972 // This means the extract is not influenced by the insert, and we can
11973 // replace the aggregate operand of the extract with the aggregate
11974 // operand of the insert. i.e., replace
11975 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
11976 // %E = extractvalue { i32, { i32 } } %I, 0
11977 // with
11978 // %E = extractvalue { i32, { i32 } } %A, 0
11979 return ExtractValueInst::Create(IV->getAggregateOperand(),
11980 EV.idx_begin(), EV.idx_end());
11981 }
11982 if (exti == exte && insi == inse)
11983 // Both iterators are at the end: Index lists are identical. Replace
11984 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
11985 // %C = extractvalue { i32, { i32 } } %B, 1, 0
11986 // with "i32 42"
11987 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
11988 if (exti == exte) {
11989 // The extract list is a prefix of the insert list. i.e. replace
11990 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
11991 // %E = extractvalue { i32, { i32 } } %I, 1
11992 // with
11993 // %X = extractvalue { i32, { i32 } } %A, 1
11994 // %E = insertvalue { i32 } %X, i32 42, 0
11995 // by switching the order of the insert and extract (though the
11996 // insertvalue should be left in, since it may have other uses).
11997 Value *NewEV = InsertNewInstBefore(
11998 ExtractValueInst::Create(IV->getAggregateOperand(),
11999 EV.idx_begin(), EV.idx_end()),
12000 EV);
12001 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12002 insi, inse);
12003 }
12004 if (insi == inse)
12005 // The insert list is a prefix of the extract list
12006 // We can simply remove the common indices from the extract and make it
12007 // operate on the inserted value instead of the insertvalue result.
12008 // i.e., replace
12009 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12010 // %E = extractvalue { i32, { i32 } } %I, 1, 0
12011 // with
12012 // %E extractvalue { i32 } { i32 42 }, 0
12013 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
12014 exti, exte);
12015 }
12016 // Can't simplify extracts from other values. Note that nested extracts are
12017 // already simplified implicitely by the above (extract ( extract (insert) )
12018 // will be translated into extract ( insert ( extract ) ) first and then just
12019 // the value inserted, if appropriate).
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012020 return 0;
12021}
12022
Chris Lattner220b0cf2006-03-05 00:22:33 +000012023/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12024/// is to leave as a vector operation.
12025static bool CheapToScalarize(Value *V, bool isConstant) {
12026 if (isa<ConstantAggregateZero>(V))
12027 return true;
Reid Spencer9d6565a2007-02-15 02:26:10 +000012028 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000012029 if (isConstant) return true;
12030 // If all elts are the same, we can extract.
12031 Constant *Op0 = C->getOperand(0);
12032 for (unsigned i = 1; i < C->getNumOperands(); ++i)
12033 if (C->getOperand(i) != Op0)
12034 return false;
12035 return true;
12036 }
12037 Instruction *I = dyn_cast<Instruction>(V);
12038 if (!I) return false;
12039
12040 // Insert element gets simplified to the inserted element or is deleted if
12041 // this is constant idx extract element and its a constant idx insertelt.
12042 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12043 isa<ConstantInt>(I->getOperand(2)))
12044 return true;
12045 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12046 return true;
12047 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12048 if (BO->hasOneUse() &&
12049 (CheapToScalarize(BO->getOperand(0), isConstant) ||
12050 CheapToScalarize(BO->getOperand(1), isConstant)))
12051 return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +000012052 if (CmpInst *CI = dyn_cast<CmpInst>(I))
12053 if (CI->hasOneUse() &&
12054 (CheapToScalarize(CI->getOperand(0), isConstant) ||
12055 CheapToScalarize(CI->getOperand(1), isConstant)))
12056 return true;
Chris Lattner220b0cf2006-03-05 00:22:33 +000012057
12058 return false;
12059}
12060
Chris Lattnerd2b7cec2007-02-14 05:52:17 +000012061/// Read and decode a shufflevector mask.
12062///
12063/// It turns undef elements into values that are larger than the number of
12064/// elements in the input.
Chris Lattner863bcff2006-05-25 23:48:38 +000012065static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12066 unsigned NElts = SVI->getType()->getNumElements();
12067 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12068 return std::vector<unsigned>(NElts, 0);
12069 if (isa<UndefValue>(SVI->getOperand(2)))
12070 return std::vector<unsigned>(NElts, 2*NElts);
12071
12072 std::vector<unsigned> Result;
Reid Spencer9d6565a2007-02-15 02:26:10 +000012073 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Gabor Greif177dd3f2008-06-12 21:37:33 +000012074 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12075 if (isa<UndefValue>(*i))
Chris Lattner863bcff2006-05-25 23:48:38 +000012076 Result.push_back(NElts*2); // undef -> 8
12077 else
Gabor Greif177dd3f2008-06-12 21:37:33 +000012078 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
Chris Lattner863bcff2006-05-25 23:48:38 +000012079 return Result;
12080}
12081
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012082/// FindScalarElement - Given a vector and an element number, see if the scalar
12083/// value is already around as a register, for example if it were inserted then
12084/// extracted from the vector.
12085static Value *FindScalarElement(Value *V, unsigned EltNo) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000012086 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12087 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +000012088 unsigned Width = PTy->getNumElements();
12089 if (EltNo >= Width) // Out of range access.
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012090 return UndefValue::get(PTy->getElementType());
12091
12092 if (isa<UndefValue>(V))
12093 return UndefValue::get(PTy->getElementType());
12094 else if (isa<ConstantAggregateZero>(V))
12095 return Constant::getNullValue(PTy->getElementType());
Reid Spencer9d6565a2007-02-15 02:26:10 +000012096 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012097 return CP->getOperand(EltNo);
12098 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12099 // If this is an insert to a variable element, we don't know what it is.
Reid Spencerb83eb642006-10-20 07:07:24 +000012100 if (!isa<ConstantInt>(III->getOperand(2)))
12101 return 0;
12102 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012103
12104 // If this is an insert to the element we are looking for, return the
12105 // inserted value.
Reid Spencerb83eb642006-10-20 07:07:24 +000012106 if (EltNo == IIElt)
12107 return III->getOperand(1);
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012108
12109 // Otherwise, the insertelement doesn't modify the value, recurse on its
12110 // vector input.
12111 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner389a6f52006-04-10 23:06:36 +000012112 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Mon P Wangaeb06d22008-11-10 04:46:22 +000012113 unsigned LHSWidth =
12114 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
Chris Lattner863bcff2006-05-25 23:48:38 +000012115 unsigned InEl = getShuffleMask(SVI)[EltNo];
Mon P Wangaeb06d22008-11-10 04:46:22 +000012116 if (InEl < LHSWidth)
Chris Lattner863bcff2006-05-25 23:48:38 +000012117 return FindScalarElement(SVI->getOperand(0), InEl);
Mon P Wangaeb06d22008-11-10 04:46:22 +000012118 else if (InEl < LHSWidth*2)
12119 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth);
Chris Lattner863bcff2006-05-25 23:48:38 +000012120 else
12121 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012122 }
12123
12124 // Otherwise, we don't know.
12125 return 0;
12126}
12127
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012128Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Dan Gohman07a96762007-07-16 14:29:03 +000012129 // If vector val is undef, replace extract with scalar undef.
Chris Lattner1f13c882006-03-31 18:25:14 +000012130 if (isa<UndefValue>(EI.getOperand(0)))
12131 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12132
Dan Gohman07a96762007-07-16 14:29:03 +000012133 // If vector val is constant 0, replace extract with scalar 0.
Chris Lattner1f13c882006-03-31 18:25:14 +000012134 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
12135 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
12136
Reid Spencer9d6565a2007-02-15 02:26:10 +000012137 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Matthijs Kooijmanb4d6a5a2008-06-11 09:00:12 +000012138 // If vector val is constant with all elements the same, replace EI with
12139 // that element. When the elements are not identical, we cannot replace yet
12140 // (we do that below, but only when the index is constant).
Chris Lattner220b0cf2006-03-05 00:22:33 +000012141 Constant *op0 = C->getOperand(0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012142 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +000012143 if (C->getOperand(i) != op0) {
12144 op0 = 0;
12145 break;
12146 }
12147 if (op0)
12148 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012149 }
Chris Lattner220b0cf2006-03-05 00:22:33 +000012150
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012151 // If extracting a specified index from the vector, see if we can recursively
12152 // find a previously computed scalar that was inserted into the vector.
Reid Spencerb83eb642006-10-20 07:07:24 +000012153 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner85464092007-04-09 01:37:55 +000012154 unsigned IndexVal = IdxC->getZExtValue();
12155 unsigned VectorWidth =
12156 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
12157
12158 // If this is extracting an invalid index, turn this into undef, to avoid
12159 // crashing the code below.
12160 if (IndexVal >= VectorWidth)
12161 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12162
Chris Lattner867b99f2006-10-05 06:55:50 +000012163 // This instruction only demands the single element from the input vector.
12164 // If the input vector has a single use, simplify it based on this use
12165 // property.
Chris Lattner85464092007-04-09 01:37:55 +000012166 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Evan Cheng388df622009-02-03 10:05:09 +000012167 APInt UndefElts(VectorWidth, 0);
12168 APInt DemandedMask(VectorWidth, 1 << IndexVal);
Chris Lattner867b99f2006-10-05 06:55:50 +000012169 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Evan Cheng388df622009-02-03 10:05:09 +000012170 DemandedMask, UndefElts)) {
Chris Lattner867b99f2006-10-05 06:55:50 +000012171 EI.setOperand(0, V);
12172 return &EI;
12173 }
12174 }
12175
Reid Spencerb83eb642006-10-20 07:07:24 +000012176 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012177 return ReplaceInstUsesWith(EI, Elt);
Chris Lattnerb7300fa2007-04-14 23:02:14 +000012178
12179 // If the this extractelement is directly using a bitcast from a vector of
12180 // the same number of elements, see if we can find the source element from
12181 // it. In this case, we will end up needing to bitcast the scalars.
12182 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12183 if (const VectorType *VT =
12184 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12185 if (VT->getNumElements() == VectorWidth)
12186 if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
12187 return new BitCastInst(Elt, EI.getType());
12188 }
Chris Lattner389a6f52006-04-10 23:06:36 +000012189 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012190
Chris Lattner73fa49d2006-05-25 22:53:38 +000012191 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012192 if (I->hasOneUse()) {
12193 // Push extractelement into predecessor operation if legal and
12194 // profitable to do so
12195 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000012196 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
12197 if (CheapToScalarize(BO, isConstantElt)) {
12198 ExtractElementInst *newEI0 =
12199 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
12200 EI.getName()+".lhs");
12201 ExtractElementInst *newEI1 =
12202 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
12203 EI.getName()+".rhs");
12204 InsertNewInstBefore(newEI0, EI);
12205 InsertNewInstBefore(newEI1, EI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000012206 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Chris Lattner220b0cf2006-03-05 00:22:33 +000012207 }
Reid Spencer3ed469c2006-11-02 20:25:50 +000012208 } else if (isa<LoadInst>(I)) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +000012209 unsigned AS =
12210 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +000012211 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
12212 PointerType::get(EI.getType(), AS),EI);
Gabor Greifb1dbcd82008-05-15 10:04:30 +000012213 GetElementPtrInst *GEP =
12214 GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012215 InsertNewInstBefore(GEP, EI);
12216 return new LoadInst(GEP);
Chris Lattner73fa49d2006-05-25 22:53:38 +000012217 }
12218 }
12219 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
12220 // Extracting the inserted element?
12221 if (IE->getOperand(2) == EI.getOperand(1))
12222 return ReplaceInstUsesWith(EI, IE->getOperand(1));
12223 // If the inserted and extracted elements are constants, they must not
12224 // be the same value, extract from the pre-inserted value instead.
12225 if (isa<Constant>(IE->getOperand(2)) &&
12226 isa<Constant>(EI.getOperand(1))) {
12227 AddUsesToWorkList(EI);
12228 EI.setOperand(0, IE->getOperand(0));
12229 return &EI;
12230 }
12231 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12232 // If this is extracting an element from a shufflevector, figure out where
12233 // it came from and extract from the appropriate input element instead.
Reid Spencerb83eb642006-10-20 07:07:24 +000012234 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12235 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner863bcff2006-05-25 23:48:38 +000012236 Value *Src;
Mon P Wangaeb06d22008-11-10 04:46:22 +000012237 unsigned LHSWidth =
12238 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12239
12240 if (SrcIdx < LHSWidth)
Chris Lattner863bcff2006-05-25 23:48:38 +000012241 Src = SVI->getOperand(0);
Mon P Wangaeb06d22008-11-10 04:46:22 +000012242 else if (SrcIdx < LHSWidth*2) {
12243 SrcIdx -= LHSWidth;
Chris Lattner863bcff2006-05-25 23:48:38 +000012244 Src = SVI->getOperand(1);
12245 } else {
12246 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +000012247 }
Chris Lattner867b99f2006-10-05 06:55:50 +000012248 return new ExtractElementInst(Src, SrcIdx);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012249 }
12250 }
Chris Lattner73fa49d2006-05-25 22:53:38 +000012251 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012252 return 0;
12253}
12254
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012255/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12256/// elements from either LHS or RHS, return the shuffle mask and true.
12257/// Otherwise, return false.
12258static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
12259 std::vector<Constant*> &Mask) {
12260 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12261 "Invalid CollectSingleShuffleElements");
Reid Spencer9d6565a2007-02-15 02:26:10 +000012262 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012263
12264 if (isa<UndefValue>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000012265 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012266 return true;
12267 } else if (V == LHS) {
12268 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000012269 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012270 return true;
12271 } else if (V == RHS) {
12272 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000012273 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012274 return true;
12275 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12276 // If this is an insert of an extract from some other vector, include it.
12277 Value *VecOp = IEI->getOperand(0);
12278 Value *ScalarOp = IEI->getOperand(1);
12279 Value *IdxOp = IEI->getOperand(2);
12280
Chris Lattnerd929f062006-04-27 21:14:21 +000012281 if (!isa<ConstantInt>(IdxOp))
12282 return false;
Reid Spencerb83eb642006-10-20 07:07:24 +000012283 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerd929f062006-04-27 21:14:21 +000012284
12285 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
12286 // Okay, we can handle this if the vector we are insertinting into is
12287 // transitively ok.
12288 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
12289 // If so, update the mask to reflect the inserted undef.
Reid Spencerc5b206b2006-12-31 05:48:39 +000012290 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
Chris Lattnerd929f062006-04-27 21:14:21 +000012291 return true;
12292 }
12293 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12294 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012295 EI->getOperand(0)->getType() == V->getType()) {
12296 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000012297 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012298
12299 // This must be extracting from either LHS or RHS.
12300 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12301 // Okay, we can handle this if the vector we are insertinting into is
12302 // transitively ok.
12303 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
12304 // If so, update the mask to reflect the inserted value.
12305 if (EI->getOperand(0) == LHS) {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012306 Mask[InsertedIdx % NumElts] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000012307 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012308 } else {
12309 assert(EI->getOperand(0) == RHS);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012310 Mask[InsertedIdx % NumElts] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000012311 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012312
12313 }
12314 return true;
12315 }
12316 }
12317 }
12318 }
12319 }
12320 // TODO: Handle shufflevector here!
12321
12322 return false;
12323}
12324
12325/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12326/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
12327/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +000012328static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012329 Value *&RHS) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000012330 assert(isa<VectorType>(V->getType()) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012331 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +000012332 "Invalid shuffle!");
Reid Spencer9d6565a2007-02-15 02:26:10 +000012333 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattnerefb47352006-04-15 01:39:45 +000012334
12335 if (isa<UndefValue>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000012336 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000012337 return V;
12338 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000012339 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
Chris Lattnerefb47352006-04-15 01:39:45 +000012340 return V;
12341 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12342 // If this is an insert of an extract from some other vector, include it.
12343 Value *VecOp = IEI->getOperand(0);
12344 Value *ScalarOp = IEI->getOperand(1);
12345 Value *IdxOp = IEI->getOperand(2);
12346
12347 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12348 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12349 EI->getOperand(0)->getType() == V->getType()) {
12350 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000012351 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12352 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000012353
12354 // Either the extracted from or inserted into vector must be RHSVec,
12355 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012356 if (EI->getOperand(0) == RHS || RHS == 0) {
12357 RHS = EI->getOperand(0);
12358 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012359 Mask[InsertedIdx % NumElts] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000012360 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000012361 return V;
12362 }
12363
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012364 if (VecOp == RHS) {
12365 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +000012366 // Everything but the extracted element is replaced with the RHS.
12367 for (unsigned i = 0; i != NumElts; ++i) {
12368 if (i != InsertedIdx)
Reid Spencerc5b206b2006-12-31 05:48:39 +000012369 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
Chris Lattnerefb47352006-04-15 01:39:45 +000012370 }
12371 return V;
12372 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012373
12374 // If this insertelement is a chain that comes from exactly these two
12375 // vectors, return the vector and the effective shuffle.
12376 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
12377 return EI->getOperand(0);
12378
Chris Lattnerefb47352006-04-15 01:39:45 +000012379 }
12380 }
12381 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012382 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +000012383
12384 // Otherwise, can't do anything fancy. Return an identity vector.
12385 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000012386 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattnerefb47352006-04-15 01:39:45 +000012387 return V;
12388}
12389
12390Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12391 Value *VecOp = IE.getOperand(0);
12392 Value *ScalarOp = IE.getOperand(1);
12393 Value *IdxOp = IE.getOperand(2);
12394
Chris Lattner599ded12007-04-09 01:11:16 +000012395 // Inserting an undef or into an undefined place, remove this.
12396 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12397 ReplaceInstUsesWith(IE, VecOp);
12398
Chris Lattnerefb47352006-04-15 01:39:45 +000012399 // If the inserted element was extracted from some other vector, and if the
12400 // indexes are constant, try to turn this into a shufflevector operation.
12401 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12402 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12403 EI->getOperand(0)->getType() == IE.getType()) {
12404 unsigned NumVectorElts = IE.getType()->getNumElements();
Chris Lattnere34e9a22007-04-14 23:32:02 +000012405 unsigned ExtractedIdx =
12406 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Reid Spencerb83eb642006-10-20 07:07:24 +000012407 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000012408
12409 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12410 return ReplaceInstUsesWith(IE, VecOp);
12411
12412 if (InsertedIdx >= NumVectorElts) // Out of range insert.
12413 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
12414
12415 // If we are extracting a value from a vector, then inserting it right
12416 // back into the same place, just use the input vector.
12417 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12418 return ReplaceInstUsesWith(IE, VecOp);
12419
12420 // We could theoretically do this for ANY input. However, doing so could
12421 // turn chains of insertelement instructions into a chain of shufflevector
12422 // instructions, and right now we do not merge shufflevectors. As such,
12423 // only do this in a situation where it is clear that there is benefit.
12424 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
12425 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
12426 // the values of VecOp, except then one read from EIOp0.
12427 // Build a new shuffle mask.
12428 std::vector<Constant*> Mask;
12429 if (isa<UndefValue>(VecOp))
Reid Spencerc5b206b2006-12-31 05:48:39 +000012430 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000012431 else {
12432 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Reid Spencerc5b206b2006-12-31 05:48:39 +000012433 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
Chris Lattnerefb47352006-04-15 01:39:45 +000012434 NumVectorElts));
12435 }
Reid Spencerc5b206b2006-12-31 05:48:39 +000012436 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000012437 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Reid Spencer9d6565a2007-02-15 02:26:10 +000012438 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000012439 }
12440
12441 // If this insertelement isn't used by some other insertelement, turn it
12442 // (and any insertelements it points to), into one big shuffle.
12443 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12444 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012445 Value *RHS = 0;
12446 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
12447 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
12448 // We now have a shuffle of LHS, RHS, Mask.
Reid Spencer9d6565a2007-02-15 02:26:10 +000012449 return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000012450 }
12451 }
12452 }
12453
12454 return 0;
12455}
12456
12457
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012458Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12459 Value *LHS = SVI.getOperand(0);
12460 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +000012461 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012462
12463 bool MadeChange = false;
Mon P Wangaeb06d22008-11-10 04:46:22 +000012464
Chris Lattner867b99f2006-10-05 06:55:50 +000012465 // Undefined shuffle mask -> undefined value.
Chris Lattner863bcff2006-05-25 23:48:38 +000012466 if (isa<UndefValue>(SVI.getOperand(2)))
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012467 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
Dan Gohman488fbfc2008-09-09 18:11:14 +000012468
Dan Gohman488fbfc2008-09-09 18:11:14 +000012469 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
Mon P Wangaeb06d22008-11-10 04:46:22 +000012470
12471 if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12472 return 0;
12473
Evan Cheng388df622009-02-03 10:05:09 +000012474 APInt UndefElts(VWidth, 0);
12475 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12476 if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
Dan Gohman3139ff82008-09-11 22:47:57 +000012477 LHS = SVI.getOperand(0);
12478 RHS = SVI.getOperand(1);
Dan Gohman488fbfc2008-09-09 18:11:14 +000012479 MadeChange = true;
Dan Gohman3139ff82008-09-11 22:47:57 +000012480 }
Chris Lattnerefb47352006-04-15 01:39:45 +000012481
Chris Lattner863bcff2006-05-25 23:48:38 +000012482 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
12483 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12484 if (LHS == RHS || isa<UndefValue>(LHS)) {
12485 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012486 // shuffle(undef,undef,mask) -> undef.
12487 return ReplaceInstUsesWith(SVI, LHS);
12488 }
12489
Chris Lattner863bcff2006-05-25 23:48:38 +000012490 // Remap any references to RHS to use LHS.
12491 std::vector<Constant*> Elts;
12492 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000012493 if (Mask[i] >= 2*e)
Reid Spencerc5b206b2006-12-31 05:48:39 +000012494 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012495 else {
12496 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
Dan Gohman4ce96272008-08-06 18:17:32 +000012497 (Mask[i] < e && isa<UndefValue>(LHS))) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000012498 Mask[i] = 2*e; // Turn into undef.
Dan Gohman4ce96272008-08-06 18:17:32 +000012499 Elts.push_back(UndefValue::get(Type::Int32Ty));
12500 } else {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012501 Mask[i] = Mask[i] % e; // Force to LHS.
Dan Gohman4ce96272008-08-06 18:17:32 +000012502 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
12503 }
Chris Lattner7b2e27922006-05-26 00:29:06 +000012504 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012505 }
Chris Lattner863bcff2006-05-25 23:48:38 +000012506 SVI.setOperand(0, SVI.getOperand(1));
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012507 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Reid Spencer9d6565a2007-02-15 02:26:10 +000012508 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012509 LHS = SVI.getOperand(0);
12510 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012511 MadeChange = true;
12512 }
12513
Chris Lattner7b2e27922006-05-26 00:29:06 +000012514 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +000012515 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +000012516
Chris Lattner863bcff2006-05-25 23:48:38 +000012517 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12518 if (Mask[i] >= e*2) continue; // Ignore undef values.
12519 // Is this an identity shuffle of the LHS value?
12520 isLHSID &= (Mask[i] == i);
12521
12522 // Is this an identity shuffle of the RHS value?
12523 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +000012524 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012525
Chris Lattner863bcff2006-05-25 23:48:38 +000012526 // Eliminate identity shuffles.
12527 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12528 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012529
Chris Lattner7b2e27922006-05-26 00:29:06 +000012530 // If the LHS is a shufflevector itself, see if we can combine it with this
12531 // one without producing an unusual shuffle. Here we are really conservative:
12532 // we are absolutely afraid of producing a shuffle mask not in the input
12533 // program, because the code gen may not be smart enough to turn a merged
12534 // shuffle into two specific shuffles: it may produce worse code. As such,
12535 // we only merge two shuffles if the result is one of the two input shuffle
12536 // masks. In this case, merging the shuffles just removes one instruction,
12537 // which we know is safe. This is good for things like turning:
12538 // (splat(splat)) -> splat.
12539 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12540 if (isa<UndefValue>(RHS)) {
12541 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12542
12543 std::vector<unsigned> NewMask;
12544 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12545 if (Mask[i] >= 2*e)
12546 NewMask.push_back(2*e);
12547 else
12548 NewMask.push_back(LHSMask[Mask[i]]);
12549
12550 // If the result mask is equal to the src shuffle or this shuffle mask, do
12551 // the replacement.
12552 if (NewMask == LHSMask || NewMask == Mask) {
Mon P Wangfe6d2cd2009-01-26 04:39:00 +000012553 unsigned LHSInNElts =
12554 cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
Chris Lattner7b2e27922006-05-26 00:29:06 +000012555 std::vector<Constant*> Elts;
12556 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
Mon P Wangfe6d2cd2009-01-26 04:39:00 +000012557 if (NewMask[i] >= LHSInNElts*2) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000012558 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012559 } else {
Reid Spencerc5b206b2006-12-31 05:48:39 +000012560 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012561 }
12562 }
12563 return new ShuffleVectorInst(LHSSVI->getOperand(0),
12564 LHSSVI->getOperand(1),
Reid Spencer9d6565a2007-02-15 02:26:10 +000012565 ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012566 }
12567 }
12568 }
Chris Lattnerc5eff442007-01-30 22:32:46 +000012569
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012570 return MadeChange ? &SVI : 0;
12571}
12572
12573
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012574
Chris Lattnerea1c4542004-12-08 23:43:58 +000012575
12576/// TryToSinkInstruction - Try to move the specified instruction from its
12577/// current block into the beginning of DestBlock, which can only happen if it's
12578/// safe to move the instruction past all of the instructions between it and the
12579/// end of its block.
12580static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12581 assert(I->hasOneUse() && "Invariants didn't hold!");
12582
Chris Lattner108e9022005-10-27 17:13:11 +000012583 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Duncan Sands7af1c782009-05-06 06:49:50 +000012584 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
Chris Lattnerbfc538c2008-05-09 15:07:33 +000012585 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +000012586
Chris Lattnerea1c4542004-12-08 23:43:58 +000012587 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +000012588 if (isa<AllocaInst>(I) && I->getParent() ==
12589 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +000012590 return false;
12591
Chris Lattner96a52a62004-12-09 07:14:34 +000012592 // We can only sink load instructions if there is nothing between the load and
12593 // the end of block that could change the value.
Chris Lattner2539e332008-05-08 17:37:37 +000012594 if (I->mayReadFromMemory()) {
12595 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Chris Lattner96a52a62004-12-09 07:14:34 +000012596 Scan != E; ++Scan)
12597 if (Scan->mayWriteToMemory())
12598 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +000012599 }
Chris Lattnerea1c4542004-12-08 23:43:58 +000012600
Dan Gohman02dea8b2008-05-23 21:05:58 +000012601 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Chris Lattnerea1c4542004-12-08 23:43:58 +000012602
Dale Johannesenbd8e6502009-03-03 01:09:07 +000012603 CopyPrecedingStopPoint(I, InsertPos);
Chris Lattner4bc5f802005-08-08 19:11:57 +000012604 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +000012605 ++NumSunkInst;
12606 return true;
12607}
12608
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012609
12610/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12611/// all reachable code to the worklist.
12612///
12613/// This has a couple of tricks to make the code faster and more powerful. In
12614/// particular, we constant fold and DCE instructions as we go, to avoid adding
12615/// them to the worklist (this significantly speeds up instcombine on code where
12616/// many instructions are dead or constant). Additionally, if we find a branch
12617/// whose condition is a known constant, we only visit the reachable successors.
12618///
12619static void AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +000012620 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +000012621 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012622 const TargetData *TD) {
Chris Lattner2806dff2008-08-15 04:03:01 +000012623 SmallVector<BasicBlock*, 256> Worklist;
Chris Lattner2c7718a2007-03-23 19:17:18 +000012624 Worklist.push_back(BB);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012625
Chris Lattner2c7718a2007-03-23 19:17:18 +000012626 while (!Worklist.empty()) {
12627 BB = Worklist.back();
12628 Worklist.pop_back();
12629
12630 // We have now visited this block! If we've already been here, ignore it.
12631 if (!Visited.insert(BB)) continue;
Devang Patel7fe1dec2008-11-19 18:56:50 +000012632
12633 DbgInfoIntrinsic *DBI_Prev = NULL;
Chris Lattner2c7718a2007-03-23 19:17:18 +000012634 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12635 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012636
Chris Lattner2c7718a2007-03-23 19:17:18 +000012637 // DCE instruction if trivially dead.
12638 if (isInstructionTriviallyDead(Inst)) {
12639 ++NumDeadInst;
12640 DOUT << "IC: DCE: " << *Inst;
12641 Inst->eraseFromParent();
12642 continue;
12643 }
12644
12645 // ConstantProp instruction if trivially constant.
12646 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
12647 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
12648 Inst->replaceAllUsesWith(C);
12649 ++NumConstProp;
12650 Inst->eraseFromParent();
12651 continue;
12652 }
Chris Lattner3ccc6bc2007-07-20 22:06:41 +000012653
Devang Patel7fe1dec2008-11-19 18:56:50 +000012654 // If there are two consecutive llvm.dbg.stoppoint calls then
12655 // it is likely that the optimizer deleted code in between these
12656 // two intrinsics.
12657 DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12658 if (DBI_Next) {
12659 if (DBI_Prev
12660 && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12661 && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
12662 IC.RemoveFromWorkList(DBI_Prev);
12663 DBI_Prev->eraseFromParent();
12664 }
12665 DBI_Prev = DBI_Next;
Zhou Sheng8313ef42009-02-23 10:14:11 +000012666 } else {
12667 DBI_Prev = 0;
Devang Patel7fe1dec2008-11-19 18:56:50 +000012668 }
12669
Chris Lattner2c7718a2007-03-23 19:17:18 +000012670 IC.AddToWorkList(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012671 }
Chris Lattner2c7718a2007-03-23 19:17:18 +000012672
12673 // Recursively visit successors. If this is a branch or switch on a
12674 // constant, only visit the reachable successor.
12675 TerminatorInst *TI = BB->getTerminator();
12676 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12677 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12678 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky91436992008-03-09 08:50:23 +000012679 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewycky280a6e62008-04-25 16:53:59 +000012680 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000012681 continue;
12682 }
12683 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12684 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12685 // See if this is an explicit destination.
12686 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12687 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky91436992008-03-09 08:50:23 +000012688 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewycky280a6e62008-04-25 16:53:59 +000012689 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000012690 continue;
12691 }
12692
12693 // Otherwise it is the default destination.
12694 Worklist.push_back(SI->getSuccessor(0));
12695 continue;
12696 }
12697 }
12698
12699 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12700 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012701 }
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012702}
12703
Chris Lattnerec9c3582007-03-03 02:04:50 +000012704bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012705 bool Changed = false;
Chris Lattnerbc61e662003-11-02 05:57:39 +000012706 TD = &getAnalysis<TargetData>();
Chris Lattnerec9c3582007-03-03 02:04:50 +000012707
12708 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12709 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +000012710
Chris Lattnerb3d59702005-07-07 20:40:38 +000012711 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012712 // Do a depth-first traversal of the function, populate the worklist with
12713 // the reachable instructions. Ignore blocks that are not reachable. Keep
12714 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +000012715 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerdbab3862007-03-02 21:28:56 +000012716 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +000012717
Chris Lattnerb3d59702005-07-07 20:40:38 +000012718 // Do a quick scan over the function. If we find any blocks that are
12719 // unreachable, remove any instructions inside of them. This prevents
12720 // the instcombine code from having to deal with some bad special cases.
12721 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12722 if (!Visited.count(BB)) {
12723 Instruction *Term = BB->getTerminator();
12724 while (Term != BB->begin()) { // Remove instrs bottom-up
12725 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +000012726
Bill Wendlingb7427032006-11-26 09:46:52 +000012727 DOUT << "IC: DCE: " << *I;
Dale Johannesenff278b12009-03-10 21:19:49 +000012728 // A debug intrinsic shouldn't force another iteration if we weren't
12729 // going to do one without it.
12730 if (!isa<DbgInfoIntrinsic>(I)) {
12731 ++NumDeadInst;
12732 Changed = true;
12733 }
Chris Lattnerb3d59702005-07-07 20:40:38 +000012734 if (!I->use_empty())
12735 I->replaceAllUsesWith(UndefValue::get(I->getType()));
12736 I->eraseFromParent();
12737 }
12738 }
12739 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000012740
Chris Lattnerdbab3862007-03-02 21:28:56 +000012741 while (!Worklist.empty()) {
12742 Instruction *I = RemoveOneFromWorkList();
12743 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +000012744
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012745 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +000012746 if (isInstructionTriviallyDead(I)) {
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012747 // Add operands to the worklist.
Chris Lattner4bb7c022003-10-06 17:11:01 +000012748 if (I->getNumOperands() < 4)
Chris Lattner7bcc0e72004-02-28 05:22:00 +000012749 AddUsesToWorkList(*I);
Chris Lattner62b14df2002-09-02 04:59:56 +000012750 ++NumDeadInst;
Chris Lattner4bb7c022003-10-06 17:11:01 +000012751
Bill Wendlingb7427032006-11-26 09:46:52 +000012752 DOUT << "IC: DCE: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000012753
12754 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000012755 RemoveFromWorkList(I);
Chris Lattner1e19d602009-01-31 07:04:22 +000012756 Changed = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +000012757 continue;
12758 }
Chris Lattner62b14df2002-09-02 04:59:56 +000012759
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012760 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattner0a19ffa2007-01-30 23:16:15 +000012761 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Bill Wendlingb7427032006-11-26 09:46:52 +000012762 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000012763
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012764 // Add operands to the worklist.
Chris Lattner7bcc0e72004-02-28 05:22:00 +000012765 AddUsesToWorkList(*I);
Chris Lattnerc736d562002-12-05 22:41:53 +000012766 ReplaceInstUsesWith(*I, C);
12767
Chris Lattner62b14df2002-09-02 04:59:56 +000012768 ++NumConstProp;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012769 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000012770 RemoveFromWorkList(I);
Chris Lattner1e19d602009-01-31 07:04:22 +000012771 Changed = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +000012772 continue;
Chris Lattner62b14df2002-09-02 04:59:56 +000012773 }
Chris Lattner4bb7c022003-10-06 17:11:01 +000012774
Dan Gohman31e4c772009-05-07 19:43:39 +000012775 if (TD &&
12776 (I->getType()->getTypeID() == Type::VoidTyID ||
12777 I->isTrapping())) {
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +000012778 // See if we can constant fold its operands.
Chris Lattner1e19d602009-01-31 07:04:22 +000012779 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
12780 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i))
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +000012781 if (Constant *NewC = ConstantFoldConstantExpression(CE, TD))
Chris Lattner1e19d602009-01-31 07:04:22 +000012782 if (NewC != CE) {
12783 i->set(NewC);
12784 Changed = true;
12785 }
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +000012786 }
12787
Chris Lattnerea1c4542004-12-08 23:43:58 +000012788 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohmanfc74abf2008-07-23 00:34:11 +000012789 if (I->hasOneUse()) {
Chris Lattnerea1c4542004-12-08 23:43:58 +000012790 BasicBlock *BB = I->getParent();
12791 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
12792 if (UserParent != BB) {
12793 bool UserIsSuccessor = false;
12794 // See if the user is one of our successors.
12795 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
12796 if (*SI == UserParent) {
12797 UserIsSuccessor = true;
12798 break;
12799 }
12800
12801 // If the user is one of our immediate successors, and if that successor
12802 // only has us as a predecessors (we'd have to split the critical edge
12803 // otherwise), we can keep going.
12804 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
12805 next(pred_begin(UserParent)) == pred_end(UserParent))
12806 // Okay, the CFG is simple enough, try to sink this instruction.
12807 Changed |= TryToSinkInstruction(I, UserParent);
12808 }
12809 }
12810
Chris Lattner8a2a3112001-12-14 16:52:21 +000012811 // Now that we have an instruction, try combining it to simplify it...
Reid Spencera9b81012007-03-26 17:44:01 +000012812#ifndef NDEBUG
12813 std::string OrigI;
12814#endif
12815 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
Chris Lattner90ac28c2002-08-02 19:29:35 +000012816 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +000012817 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012818 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000012819 if (Result != I) {
Bill Wendlingb7427032006-11-26 09:46:52 +000012820 DOUT << "IC: Old = " << *I
12821 << " New = " << *Result;
Chris Lattner0cea42a2004-03-13 23:54:27 +000012822
Chris Lattnerf523d062004-06-09 05:08:07 +000012823 // Everything uses the new instruction now.
12824 I->replaceAllUsesWith(Result);
12825
12826 // Push the new instruction and any users onto the worklist.
Chris Lattnerdbab3862007-03-02 21:28:56 +000012827 AddToWorkList(Result);
Chris Lattnerf523d062004-06-09 05:08:07 +000012828 AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000012829
Chris Lattner6934a042007-02-11 01:23:03 +000012830 // Move the name to the new instruction first.
12831 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000012832
12833 // Insert the new instruction into the basic block...
12834 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +000012835 BasicBlock::iterator InsertPos = I;
12836
12837 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
12838 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
12839 ++InsertPos;
12840
12841 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000012842
Chris Lattner00d51312004-05-01 23:27:23 +000012843 // Make sure that we reprocess all operands now that we reduced their
12844 // use counts.
Chris Lattnerdbab3862007-03-02 21:28:56 +000012845 AddUsesToWorkList(*I);
Chris Lattner216d4d82004-05-01 23:19:52 +000012846
Chris Lattnerf523d062004-06-09 05:08:07 +000012847 // Instructions can end up on the worklist more than once. Make sure
12848 // we do not process an instruction that has been deleted.
Chris Lattnerdbab3862007-03-02 21:28:56 +000012849 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000012850
12851 // Erase the old instruction.
12852 InstParent->getInstList().erase(I);
Chris Lattner7e708292002-06-25 16:13:24 +000012853 } else {
Evan Chengc7baf682007-03-27 16:44:48 +000012854#ifndef NDEBUG
Reid Spencera9b81012007-03-26 17:44:01 +000012855 DOUT << "IC: Mod = " << OrigI
12856 << " New = " << *I;
Evan Chengc7baf682007-03-27 16:44:48 +000012857#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +000012858
Chris Lattner90ac28c2002-08-02 19:29:35 +000012859 // If the instruction was modified, it's possible that it is now dead.
12860 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +000012861 if (isInstructionTriviallyDead(I)) {
12862 // Make sure we process all operands now that we are reducing their
12863 // use counts.
Chris Lattnerec9c3582007-03-03 02:04:50 +000012864 AddUsesToWorkList(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000012865
Chris Lattner00d51312004-05-01 23:27:23 +000012866 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012867 // occurrences of this instruction.
Chris Lattnerdbab3862007-03-02 21:28:56 +000012868 RemoveFromWorkList(I);
Chris Lattner2f503e62005-01-31 05:36:43 +000012869 I->eraseFromParent();
Chris Lattnerf523d062004-06-09 05:08:07 +000012870 } else {
Chris Lattnerec9c3582007-03-03 02:04:50 +000012871 AddToWorkList(I);
12872 AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +000012873 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000012874 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012875 Changed = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +000012876 }
12877 }
12878
Chris Lattnerec9c3582007-03-03 02:04:50 +000012879 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattnera9ff5eb2007-08-05 08:47:58 +000012880
12881 // Do an explicit clear, this shrinks the map if needed.
12882 WorklistMap.clear();
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012883 return Changed;
Chris Lattnerbd0ef772002-02-26 21:46:54 +000012884}
12885
Chris Lattnerec9c3582007-03-03 02:04:50 +000012886
12887bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +000012888 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
12889
Chris Lattnerec9c3582007-03-03 02:04:50 +000012890 bool EverMadeChange = false;
12891
12892 // Iterate while there is work to do.
12893 unsigned Iteration = 0;
Bill Wendlinga6c31122008-05-14 22:45:20 +000012894 while (DoOneIteration(F, Iteration++))
Chris Lattnerec9c3582007-03-03 02:04:50 +000012895 EverMadeChange = true;
12896 return EverMadeChange;
12897}
12898
Brian Gaeke96d4bf72004-07-27 17:43:21 +000012899FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012900 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +000012901}